<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/layout.php';

if (empty($_SESSION['user_id'])) {
    header('Location: ../index.html?e=1');
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('h')) {
    function h($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('branch_name_ar_simple')) {
    function branch_name_ar_simple(int $branchId): string
    {
        return match ($branchId) {
            1 => 'أبوظبي',
            2 => 'دبي',
            3 => 'الشارقة',
            4 => 'العين',
            default => 'غير محدد',
        };
    }
}

if (!function_exists('case_status_ar')) {
    function case_status_ar(?string $status): string
    {
        return match (strtoupper(trim((string)$status))) {
            'NEW'    => 'جديدة',
            'WORK'   => 'قيد العمل',
            'COURT'  => 'في المحكمة',
            'CLOSED' => 'مغلقة',
            default  => '-',
        };
    }
}

$clientId    = (int)($_GET['id'] ?? 0);
$addedFlag   = (string)($_GET['added'] ?? '');
$updatedFlag = (string)($_GET['updated'] ?? '');
$branchId    = (int)($_SESSION['branch_id'] ?? 1);
$role        = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isAdmin     = in_array($role, ['OWNER', 'ADMIN'], true);

if ($clientId <= 0) {
    http_response_code(404);
    exit('العميل غير موجود.');
}

$sql = "
    SELECT
        id,
        name,
        id_number,
        phone,
        email,
        notes,
        reminder_date,
        created_at,
        document,
        branch_id
    FROM clients
    WHERE id = :id
";

$params = [':id' => $clientId];

if (!$isAdmin) {
    $sql .= " AND branch_id = :branch_id ";
    $params[':branch_id'] = $branchId;
}

$sql .= " LIMIT 1 ";

$st = $pdo->prepare($sql);
$st->execute($params);
$client = $st->fetch();

if (!$client) {
    http_response_code(404);
    exit('تعذر العثور على العميل.');
}

$documentUrl = '';
if (!empty($client['document'])) {
    $documentUrl = '../uploads/clients/' . rawurlencode((string)$client['document']);
}

$clientCases = [];
$casesCount  = 0;

try {
    $sqlCases = "
        SELECT
            id,
            case_no,
            title,
            status,
            next_hearing_date,
            created_at,
            branch_id
        FROM cases
        WHERE client_id = :client_id
    ";

    $paramsCases = [':client_id' => $clientId];

    if (!$isAdmin) {
        $sqlCases .= " AND branch_id = :branch_id ";
        $paramsCases[':branch_id'] = $branchId;
    }

    $sqlCases .= " ORDER BY id DESC ";

    $stCases = $pdo->prepare($sqlCases);
    $stCases->execute($paramsCases);
    $clientCases = $stCases->fetchAll();

    $casesCount = count($clientCases);
} catch (Throwable $e) {
    $clientCases = [];
    $casesCount = 0;
}

$latestCase = $clientCases[0] ?? null;

$clientPhoneRaw = trim((string)($client['phone'] ?? ''));
$clientEmailRaw = trim((string)($client['email'] ?? ''));

$waNumber = preg_replace('/[^0-9]/', '', $clientPhoneRaw);
if ($waNumber !== '' && str_starts_with($waNumber, '0')) {
    $waNumber = '971' . ltrim($waNumber, '0');
}

$phoneHref = $clientPhoneRaw !== '' ? 'tel:' . preg_replace('/\s+/', '', $clientPhoneRaw) : '';
$waHref    = $waNumber !== '' ? 'https://wa.me/' . $waNumber : '';
$mailHref  = $clientEmailRaw !== '' ? 'mailto:' . $clientEmailRaw : '';

render_layout_start('عرض العميل');
?>

<style>
html{scroll-behavior:smooth}

.client-view-shell{width:100%;max-width:100%}
.client-view-hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:16px;align-items:start;margin-bottom:18px}
.client-view-hero-card{border:1px solid rgba(255,255,255,.08);background:linear-gradient(135deg, rgba(255,255,255,.05), rgba(255,255,255,.03));border-radius:22px;padding:22px;box-shadow:0 14px 34px rgba(0,0,0,.18)}
.client-view-title{margin:0 0 8px;font-size:34px;font-weight:900;line-height:1.1;color:#fff}
.client-view-sub{margin:0;color:var(--layout-muted);font-size:15px;line-height:1.8}
.client-view-actions-top{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.client-view-top-btn{display:inline-flex;align-items:center;justify-content:center;min-height:50px;padding:0 18px;border-radius:15px;text-decoration:none;font-weight:800;white-space:nowrap;border:1px solid rgba(255,255,255,.10);background:rgba(255,255,255,.05);color:#fff}
.client-view-top-btn.primary{border:1px solid rgba(0,106,122,.45);background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18))}
.client-view-top-btn.danger{border:1px solid rgba(255,107,107,.32);background:linear-gradient(180deg, rgba(255,107,107,.28), rgba(160,30,30,.24));color:#fff}
.client-view-alert{border-radius:16px;padding:14px 16px;margin-bottom:18px;font-weight:800;background:rgba(76,217,100,.12);border:1px solid rgba(76,217,100,.28);color:#fff}

.client-view-card{border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);border-radius:24px;overflow:hidden;box-shadow:0 14px 34px rgba(0,0,0,.16)}
.client-view-card-head{padding:18px 20px;border-bottom:1px solid rgba(255,255,255,.08);background:linear-gradient(180deg, rgba(255,255,255,.04), rgba(255,255,255,.02));display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}
.client-view-card-title{margin:0;color:#fff;font-size:18px;font-weight:900}
.client-view-card-body{padding:20px}

.client-quick-actions{display:flex;flex-wrap:wrap;gap:10px}
.client-quick-btn{display:inline-flex;align-items:center;justify-content:center;min-height:42px;padding:0 14px;border-radius:12px;text-decoration:none;font-size:13px;font-weight:800;color:#fff;border:1px solid rgba(255,255,255,.10);background:rgba(255,255,255,.05);transition:.18s ease}
.client-quick-btn:hover{transform:translateY(-1px);background:rgba(255,255,255,.08)}
.client-quick-btn.primary{border:1px solid rgba(0,106,122,.45);background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18))}
.client-quick-btn.gold{border:1px solid rgba(212,175,55,.35);background:linear-gradient(180deg, rgba(212,175,55,.28), rgba(120,90,10,.18))}
.client-quick-btn.danger{border:1px solid rgba(255,107,107,.32);background:linear-gradient(180deg, rgba(255,107,107,.24), rgba(160,30,30,.20))}

.client-view-grid{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(320px,.7fr);gap:18px}
.client-view-info-grid{display:grid;grid-template-columns:repeat(2, minmax(0,1fr));gap:14px}
.client-view-field{border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.03);border-radius:18px;padding:14px;min-width:0}
.client-view-field.full{grid-column:1 / -1}
.client-view-label{color:var(--layout-muted);font-size:13px;margin-bottom:8px}
.client-view-value{color:#fff;font-size:15px;font-weight:800;line-height:1.8;word-break:break-word}
.client-view-side-stack{display:flex;flex-direction:column;gap:18px}
.client-view-badge{display:inline-flex;align-items:center;justify-content:center;min-width:82px;padding:7px 14px;border-radius:999px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.10);color:#fff;font-size:12px;font-weight:900}
.client-view-side-list{display:flex;flex-direction:column;gap:12px}
.client-view-side-item{border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.03);border-radius:16px;padding:14px}
.client-view-side-item .k{color:var(--layout-muted);font-size:12px;margin-bottom:6px}
.client-view-side-item .v{color:#fff;font-size:14px;font-weight:800;word-break:break-word}
.client-view-file{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.03);border-radius:16px;padding:14px}
.client-view-file a{display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:0 14px;border-radius:12px;text-decoration:none;font-size:13px;font-weight:800;color:#fff;background:#0b91b1;border:1px solid rgba(255,255,255,.08)}
.client-view-empty{color:var(--layout-muted);font-size:14px;line-height:1.8}

.client-cases-list{display:grid;gap:12px}
.client-case-item{border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.03);border-radius:18px;padding:14px}
.client-case-top{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}
.client-case-title{color:#fff;font-size:16px;font-weight:900;line-height:1.7;margin-bottom:6px}
.client-case-meta{color:var(--layout-muted);font-size:13px;line-height:1.9}
.client-case-actions{margin-top:12px;display:flex;gap:10px;flex-wrap:wrap}
.client-case-btn{display:inline-flex;align-items:center;justify-content:center;min-height:38px;padding:0 14px;border-radius:12px;text-decoration:none;font-size:13px;font-weight:800;color:#fff;border:1px solid rgba(255,255,255,.10);background:rgba(255,255,255,.05)}
.client-case-btn.primary{border:1px solid rgba(0,106,122,.45);background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18))}

@media (max-width: 980px){
  .client-view-hero{grid-template-columns:1fr}
  .client-view-grid{grid-template-columns:1fr}
  .client-view-info-grid{grid-template-columns:1fr}
  .client-view-title{font-size:28px}
}
</style>

<div class="client-view-shell">
  <?php if ($addedFlag === '1'): ?>
    <div class="client-view-alert">تمت إضافة العميل بنجاح.</div>
  <?php endif; ?>

  <?php if ($updatedFlag === '1'): ?>
    <div class="client-view-alert">تم تحديث بيانات العميل بنجاح.</div>
  <?php endif; ?>

  <div class="client-view-hero">
    <div class="client-view-hero-card">
      <h1 class="client-view-title"><?= h((string)($client['name'] ?? 'ملف العميل')) ?></h1>
      <p class="client-view-sub">عرض بيانات العميل الكاملة والملاحظات والمرفقات والقضايا المرتبطة به داخل النظام.</p>
    </div>

    <div class="client-view-actions-top">
      <a class="client-view-top-btn" href="<?= h(u('clients/index.php')) ?>">العودة</a>
      <a class="client-view-top-btn primary" href="<?= h(u('case_add.php?client_id=' . (int)$client['id'])) ?>">إضافة قضية لهذا العميل</a>
      <a class="client-view-top-btn primary" href="<?= h(u('clients/edit.php?id=' . (int)$client['id'])) ?>">تعديل العميل</a>
      <a class="client-view-top-btn danger" href="<?= h(u('clients/delete.php?id=' . (int)$client['id'])) ?>" onclick="return confirm('هل أنت متأكد من حذف هذا العميل؟');">حذف العميل</a>
    </div>
  </div>

  <div class="client-view-card" style="margin-bottom:18px;">
    <div class="client-view-card-head">
      <h2 class="client-view-card-title">إجراءات سريعة</h2>
    </div>

    <div class="client-view-card-body">
      <div class="client-quick-actions">
        <a class="client-quick-btn primary" href="<?= h(u('case_add.php?client_id=' . (int)$client['id'])) ?>">إضافة قضية جديدة</a>
        <a class="client-quick-btn" href="<?= h(u('clients/edit.php?id=' . (int)$client['id'])) ?>">تعديل العميل</a>
        <a class="client-quick-btn" href="#clientCasesSection">عرض القضايا</a>

        <?php if ($latestCase): ?>
          <a class="client-quick-btn gold" href="<?= h(u('case_view.php?id=' . (int)$latestCase['id'])) ?>">فتح آخر قضية</a>
        <?php endif; ?>

        <?php if ($waHref !== ''): ?>
          <a class="client-quick-btn" href="<?= h($waHref) ?>" target="_blank" rel="noopener">واتساب</a>
        <?php endif; ?>

        <?php if ($phoneHref !== ''): ?>
          <a class="client-quick-btn" href="<?= h($phoneHref) ?>">اتصال</a>
        <?php endif; ?>

        <?php if ($mailHref !== ''): ?>
          <a class="client-quick-btn" href="<?= h($mailHref) ?>">إرسال بريد</a>
        <?php endif; ?>

        <a class="client-quick-btn" href="javascript:void(0)" onclick="window.print()">طباعة الملف</a>
        <a class="client-quick-btn danger" href="<?= h(u('clients/delete.php?id=' . (int)$client['id'])) ?>" onclick="return confirm('هل أنت متأكد من حذف هذا العميل؟');">حذف العميل</a>
      </div>
    </div>
  </div>

  <div class="client-view-grid">
    <div>
      <div class="client-view-card">
        <div class="client-view-card-head">
          <h2 class="client-view-card-title">البيانات الأساسية</h2>
        </div>

        <div class="client-view-card-body">
          <div class="client-view-info-grid">
            <div class="client-view-field">
              <div class="client-view-label">اسم العميل</div>
              <div class="client-view-value"><?= h((string)($client['name'] ?? '-')) ?></div>
            </div>

            <div class="client-view-field">
              <div class="client-view-label">رقم العميل</div>
              <div class="client-view-value">#<?= (int)($client['id'] ?? 0) ?></div>
            </div>

            <div class="client-view-field">
              <div class="client-view-label">رقم الهوية</div>
              <div class="client-view-value"><?= h((string)($client['id_number'] ?? '-')) ?></div>
            </div>

            <div class="client-view-field">
              <div class="client-view-label">الهاتف</div>
              <div class="client-view-value"><?= h((string)($client['phone'] ?? '-')) ?></div>
            </div>

            <div class="client-view-field">
              <div class="client-view-label">البريد الإلكتروني</div>
              <div class="client-view-value"><?= h((string)($client['email'] ?? '-')) ?></div>
            </div>

            <div class="client-view-field">
              <div class="client-view-label">الفرع</div>
              <div class="client-view-value">
                <span class="client-view-badge"><?= h(branch_name_ar_simple((int)($client['branch_id'] ?? 0))) ?></span>
              </div>
            </div>

            <div class="client-view-field full">
              <div class="client-view-label">ملاحظات</div>
              <div class="client-view-value"><?= nl2br(h((string)($client['notes'] ?? '-'))) ?></div>
            </div>
          </div>
        </div>
      </div>

      <div class="client-view-card" id="clientCasesSection" style="margin-top:18px;">
        <div class="client-view-card-head">
          <h2 class="client-view-card-title">القضايا المرتبطة</h2>
          <span class="client-view-badge"><?= (int)$casesCount ?> قضية</span>
        </div>

        <div class="client-view-card-body">
          <?php if ($clientCases): ?>
            <div class="client-cases-list">
              <?php foreach ($clientCases as $case): ?>
                <div class="client-case-item">
                  <div class="client-case-top">
                    <div>
                      <div class="client-case-title"><?= h((string)($case['title'] ?: 'بدون عنوان')) ?></div>
                      <div class="client-case-meta">
                        رقم القضية: <?= h((string)($case['case_no'] ?: '-')) ?><br>
                        الحالة: <?= h(case_status_ar($case['status'] ?? '')) ?><br>
                        الفرع: <?= h(branch_name_ar_simple((int)($case['branch_id'] ?? 0))) ?><br>
                        تاريخ الإضافة: <?= h(!empty($case['created_at']) ? date('Y-m-d H:i', strtotime((string)$case['created_at'])) : '-') ?><br>
                        الجلسة القادمة: <?= h((string)($case['next_hearing_date'] ?: '-')) ?>
                      </div>
                    </div>

                    <span class="client-view-badge"><?= h(case_status_ar($case['status'] ?? '')) ?></span>
                  </div>

                  <div class="client-case-actions">
                    <a class="client-case-btn primary" href="<?= h(u('case_view.php?id=' . (int)$case['id'])) ?>">فتح القضية</a>
                    <a class="client-case-btn" href="<?= h(u('case_edit.php?id=' . (int)$case['id'])) ?>">تعديل القضية</a>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php else: ?>
            <div class="client-view-empty">لا توجد قضايا مرتبطة بهذا العميل حتى الآن.</div>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <div class="client-view-side-stack">
      <div class="client-view-card">
        <div class="client-view-card-head">
          <h2 class="client-view-card-title">تفاصيل إضافية</h2>
        </div>

        <div class="client-view-card-body">
          <div class="client-view-side-list">
            <div class="client-view-side-item">
              <div class="k">تاريخ الإضافة</div>
              <div class="v"><?= h(!empty($client['created_at']) ? date('Y-m-d H:i', strtotime((string)$client['created_at'])) : '-') ?></div>
            </div>

            <div class="client-view-side-item">
              <div class="k">تاريخ التذكير</div>
              <div class="v"><?= h(!empty($client['reminder_date']) ? (string)$client['reminder_date'] : '-') ?></div>
            </div>

            <div class="client-view-side-item">
              <div class="k">عدد القضايا المرتبطة</div>
              <div class="v"><?= (int)$casesCount ?></div>
            </div>
          </div>
        </div>
      </div>

      <div class="client-view-card">
        <div class="client-view-card-head">
          <h2 class="client-view-card-title">المرفق</h2>
        </div>

        <div class="client-view-card-body">
          <?php if ($documentUrl !== ''): ?>
            <div class="client-view-file">
              <div class="client-view-empty"><?= h((string)$client['document']) ?></div>
              <a href="<?= h($documentUrl) ?>" target="_blank" rel="noopener">فتح الملف</a>
            </div>
          <?php else: ?>
            <div class="client-view-empty">لا يوجد ملف مرفق لهذا العميل.</div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<?php render_layout_end(); ?>