<?php
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/db_tools.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.php';
require_login();

$pdo = db();
ensure_audit_tables($pdo);
ensure_company_profile_columns($pdo);
$cid = (int)$_SESSION['company_id'];
$canEdit = in_array($_SESSION['user_role'] ?? '', ['owner','admin'], true);

$stmt = $pdo->prepare("SELECT * FROM companies WHERE id=? LIMIT 1");
$stmt->execute([$cid]);
$c = $stmt->fetch();

$err = '';
$ok = '';
$openModal = false;

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $openModal = true;

  if(!$canEdit){
    $err = "ليس لديك صلاحية";
  } else {
    $name = trim($_POST['name'] ?? '');
    $currency = trim($_POST['currency'] ?? 'EGP');
    $taxFileNo = trim($_POST['tax_file_no'] ?? '');
    $commercialRegisterNo = trim($_POST['commercial_register_no'] ?? '');
    $phone1 = trim($_POST['phone1'] ?? '');
    $phone2 = trim($_POST['phone2'] ?? '');
    $logoPath = $c['logo_path'] ?? null;

    if(!$name) {
      $err = "اسم الشركة مطلوب";
    } else {
      if (!empty($_FILES['logo']['name'] ?? '')) {
        $allowed = [
          'image/jpeg'    => 'jpg',
          'image/png'     => 'png',
          'image/webp'    => 'webp',
          'image/svg+xml' => 'svg'
        ];

        $mime = mime_content_type($_FILES['logo']['tmp_name']);

        if (!isset($allowed[$mime])) {
          $err = 'صيغة اللوجو غير مدعومة. ارفع JPG أو PNG أو WEBP أو SVG';
        } elseif (($_FILES['logo']['size'] ?? 0) > 2 * 1024 * 1024) {
          $err = 'حجم اللوجو يجب ألا يزيد عن 2 ميجابايت';
        } else {
          $dir = __DIR__ . '/../uploads/company';
          if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
          }

          $ext = $allowed[$mime];
          $fileName = 'company_' . $cid . '_' . time() . '.' . $ext;
          $destAbs = $dir . '/' . $fileName;

          if (!move_uploaded_file($_FILES['logo']['tmp_name'], $destAbs)) {
            $err = 'تعذر رفع اللوجو';
          } else {
            $logoPath = '/uploads/company/' . $fileName;
          }
        }
      }

      if (!$err) {
        $stmt = $pdo->prepare("
          UPDATE companies
          SET name=?, currency=?, tax_file_no=?, commercial_register_no=?, phone1=?, phone2=?, logo_path=?
          WHERE id=?
        ");
        $stmt->execute([
          $name,
          $currency,
          $taxFileNo ?: null,
          $commercialRegisterNo ?: null,
          $phone1 ?: null,
          $phone2 ?: null,
          $logoPath,
          $cid
        ]);

        $_SESSION['company_name'] = $name;
        audit_log($pdo, ['company_id'=>$cid,'user_id'=>(int)($_SESSION['user_id'] ?? 0),'module'=>'settings','action'=>'UPDATE_COMPANY','entity_type'=>'company','entity_id'=>(string)$cid,'description'=>'تحديث بيانات الشركة الأساسية']);
        $ok = "تم حفظ بيانات الشركة";
        $openModal = false;

        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id=? LIMIT 1");
        $stmt->execute([$cid]);
        $c = $stmt->fetch();
      }
    }
  }
}

render_layout(
  "الشركة",
  "الرئيسية <span class='mx-1'>/</span> الإعدادات <span class='mx-1'>/</span> الشركة",
  function() use ($c, $err, $ok, $canEdit, $openModal) {
    $posted = static function(string $key, $fallback = '') {
      return $_POST[$key] ?? $fallback;
    };
?>
<style>
  .company-page .cardx{border-radius:18px}
  .company-page .company-hero{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
  .company-page .logo-box-view{
    width:96px;height:96px;border-radius:24px;background:#f8f9fa;border:1px solid #e9ecef;
    display:flex;align-items:center;justify-content:center;overflow:hidden;flex:0 0 auto;
  }
  .company-page .logo-box-view img{width:100%;height:100%;object-fit:contain;background:#fff;padding:10px}
  .company-page .logo-box-view .bi{font-size:2rem;color:#94a3b8}
  .company-page .summary-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
  .company-page .summary-item{padding:.9rem 1rem;border:1px solid #ececec;border-radius:14px;background:#fff;min-height:78px}
  .company-page .summary-item .label{color:#64748b;font-size:.85rem;margin-bottom:.35rem}
  .company-page .summary-item .value{font-weight:700;word-break:break-word}
  .company-page .company-actions{display:flex;gap:.75rem;flex-wrap:wrap}
  .company-page .company-actions .btn{min-height:44px}
  .company-page .form-label{font-weight:600;margin-bottom:.45rem}
  .company-page .form-control{min-height:46px;border-radius:12px}
  .company-page .logo-preview{
    width:100%;display:flex;align-items:center;gap:12px;flex-wrap:wrap;border:1px solid #dee2e6;
    border-radius:18px;padding:10px 12px;background:#f8f9fa;overflow:hidden
  }
  .company-page .logo-preview img{
    width:42px;height:42px;object-fit:contain;background:#fff;border-radius:12px;padding:6px;flex:0 0 auto;cursor:zoom-in
  }
  .company-page .logo-preview-actions{display:flex;gap:.5rem;flex-wrap:wrap;margin-top:.45rem}
  .company-page .logo-preview-actions .btn{min-height:36px;padding:.35rem .7rem;border-radius:12px}
  .company-page .logo-preview-text{min-width:0;flex:1 1 220px}
  .company-page .logo-preview-text .path{word-break:break-word}
  .company-page .modal.modal-erp .modal-dialog{max-width:min(760px, calc(100vw - 1.2rem))}
  @media (max-width: 767.98px){
    .company-page{padding-bottom:12px}
    .company-page .cardx{padding:1rem !important;border-radius:16px}
    .company-page .company-hero{align-items:flex-start}
    .company-page .logo-box-view{width:76px;height:76px;border-radius:18px}
    .company-page .summary-grid{grid-template-columns:1fr}
    .company-page .logo-preview{flex-direction:column;align-items:flex-start;text-align:right}
    .company-page .logo-preview img{width:40px;height:40px}
    .company-page .company-actions{flex-direction:column}
    .company-page .company-actions .btn,
    .company-page .company-actions a{width:100%;justify-content:center}
  }
</style>

<div class="company-page">
  <?php if($err): ?>
    <div class="alert alert-danger mt-3 mb-0"><?= h($err) ?></div>
  <?php endif; ?>

  <?php if($ok): ?>
    <div class="alert alert-success mt-3 mb-0"><?= h($ok) ?></div>
  <?php endif; ?>

  <div class="row g-3 mt-3">
    <div class="col-12 col-xl-8">
      <div class="card cardx p-3 p-md-4 h-100">
        <div class="company-hero mb-3">
          <div class="logo-box-view">
            <?php if(!empty($c['logo_path'])): ?>
              <img src="<?= h(url($c['logo_path'])) ?>" alt="Logo">
            <?php else: ?>
              <i class="bi bi-building"></i>
            <?php endif; ?>
          </div>
          <div class="flex-grow-1 min-w-0">
            <div class="fw-bold fs-4 mb-1"><?= h($c['name'] ?? '-') ?></div>
            <div class="text-secondary small">بيانات الشركة الأساسية المستخدمة في الشاشات والتقارير والطباعة.</div>
          </div>
        </div>

        <div class="summary-grid">
          <div class="summary-item">
            <div class="label">العملة</div>
            <div class="value"><?= h($c['currency'] ?? '-') ?></div>
          </div>
          <div class="summary-item">
            <div class="label">رقم الملف الضريبي</div>
            <div class="value"><?= h($c['tax_file_no'] ?? '-') ?></div>
          </div>
          <div class="summary-item">
            <div class="label">رقم السجل التجاري</div>
            <div class="value"><?= h($c['commercial_register_no'] ?? '-') ?></div>
          </div>
          <div class="summary-item">
            <div class="label">أرقام الشركة</div>
            <div class="value"><?= h(trim(($c['phone1'] ?? '') . ' / ' . ($c['phone2'] ?? ''), ' /')) ?: '-' ?></div>
          </div>
          <div class="summary-item" style="grid-column:1/-1;">
            <div class="label">مسار اللوجو</div>
            <div class="value small"><?= !empty($c['logo_path']) ? h($c['logo_path']) : '-' ?></div>
          </div>
        </div>

        <div class="company-actions mt-3">
          <?php if($canEdit): ?>
            <button type="button" class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#companyModal">
              <i class="bi bi-pencil-square"></i>
              فتح نافذة التعديل
            </button>
          <?php endif; ?>
          <a class="btn btn-outline-secondary" href="<?= url('/index.php') ?>">رجوع</a>
        </div>
      </div>
    </div>

    <div class="col-12 col-xl-4">
      <div class="card cardx p-3 p-md-4 h-100">
        <div class="fw-bold mb-2">ملاحظات</div>
        <div class="small text-secondary mb-3">يمكنك تحديث اسم الشركة والعملة والبيانات الرسمية واللوجو من خلال نافذة منبثقة بدون مغادرة الصفحة.</div>
        <div class="vstack gap-2 small">
          <div class="summary-item">
            <div class="label">الصلاحية المطلوبة</div>
            <div class="value"><?= $canEdit ? 'Owner / Admin' : 'عرض فقط' ?></div>
          </div>
          <div class="summary-item">
            <div class="label">رفع اللوجو</div>
            <div class="value">JPG / PNG / WEBP / SVG حتى 2MB</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<?php if($canEdit): ?>
<div class="modal fade modal-erp" id="companyModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title">تعديل بيانات الشركة</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">

          <div class="row g-3 modal-inline-grid">
            <div class="col-12 col-md-8">
              <label class="form-label">اسم الشركة</label>
              <input class="form-control" name="name" value="<?= h($posted('name', $c['name'] ?? '')) ?>" required>
            </div>

            <div class="col-12 col-md-4">
              <label class="form-label">العملة</label>
              <input class="form-control" name="currency" value="<?= h($posted('currency', $c['currency'] ?? 'EGP')) ?>">
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">رقم الملف الضريبي</label>
              <input class="form-control" name="tax_file_no" value="<?= h($posted('tax_file_no', $c['tax_file_no'] ?? '')) ?>">
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">رقم السجل التجاري</label>
              <input class="form-control" name="commercial_register_no" value="<?= h($posted('commercial_register_no', $c['commercial_register_no'] ?? '')) ?>">
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">رقم الشركة 1</label>
              <input class="form-control" name="phone1" value="<?= h($posted('phone1', $c['phone1'] ?? '')) ?>">
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">رقم الشركة 2</label>
              <input class="form-control" name="phone2" value="<?= h($posted('phone2', $c['phone2'] ?? '')) ?>">
            </div>

            <div class="col-12">
              <label class="form-label">لوجو الشركة</label>
              <input class="form-control" type="file" name="logo" accept=".jpg,.jpeg,.png,.webp,.svg,image/*">
              <div class="text-secondary small mt-2">الحد الأقصى 2 ميجابايت.</div>
            </div>

            <?php if(!empty($c['logo_path'])): ?>
              <div class="col-12">
                <div class="logo-preview">
                  <img src="<?= h(url($c['logo_path'])) ?>" alt="Logo" data-image-preview="<?= h(url($c['logo_path'])) ?>" data-image-title="لوجو الشركة">
                  <div class="logo-preview-text">
                    <div class="fw-bold mb-1">اللوجو الحالي (صغير ويمكن تكبيره)</div>
                    <div class="text-secondary small path"><?= h($c['logo_path']) ?></div>
                    <div class="logo-preview-actions">
                      <button type="button" class="btn btn-sm btn-outline-secondary" data-image-preview="<?= h(url($c['logo_path'])) ?>" data-image-title="لوجو الشركة"><i class="bi bi-arrows-fullscreen"></i> معاينة</button>
                    </div>
                  </div>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark">
            <i class="bi bi-check2-circle"></i>
            حفظ
          </button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>

<?php if($openModal && $canEdit): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('companyModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>
<?php
});
?>
