<?php
declare(strict_types=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();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$caseId = (int)($_GET['case_id'] ?? $_GET['id'] ?? 0);
if ($caseId <= 0) {
    http_response_code(400);
    exit('Case ID missing');
}

function fileUrl(string $path, string $baseUrl): string
{
    $p = trim($path);
    if ($p === '') return '#';

    if (preg_match('~^https?://~i', $p)) return $p;

    $p = ltrim($p, '/');

    if (preg_match('~^uploads/~i', $p)) {
        return $baseUrl . '/HLG-Justice-Hub/' . $p;
    }

    if (preg_match('~^HLG-Justice-Hub/~i', $p)) {
        return $baseUrl . '/' . $p;
    }

    return $baseUrl . '/' . $p;
}

$name = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

$sessionBranchId = (int)($_SESSION['branch_id'] ?? 0);
if ($sessionBranchId <= 0) $sessionBranchId = 1;

/* ====== Case info ====== */
$case = [];
try {
    if (in_array($role, ['OWNER', 'ADMIN'], true)) {
        $st = $pdo->prepare("SELECT id, case_no, title, branch_id FROM cases WHERE id=? LIMIT 1");
        $st->execute([$caseId]);
    } else {
        $st = $pdo->prepare("SELECT id, case_no, title, branch_id FROM cases WHERE id=? AND branch_id=? LIMIT 1");
        $st->execute([$caseId, $sessionBranchId]);
    }
    $case = (array)$st->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $case = [];
}

if (empty($case)) {
    http_response_code(403);
    exit('غير مصرح أو القضية غير موجودة في فرعك');
}

$branchId = (int)$case['branch_id'];

/* اسم الفرع */
try {
    $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id=? LIMIT 1");
    $st->execute([$branchId]);
    $currentBranchName = (string)($st->fetchColumn() ?: 'الفرع');
} catch (Throwable $e) {
    $currentBranchName = match ($branchId) {
        2 => 'دبي',
        3 => 'الشارقة',
        default => 'أبوظبي',
    };
}

/* ====== Back URL ====== */
$backUrl = u('cases.php');
if (!empty($_SERVER['HTTP_REFERER'])) {
    $ref = (string)$_SERVER['HTTP_REFERER'];
    $refHost = (string)(parse_url($ref, PHP_URL_HOST) ?? '');
    $myHost  = (string)($_SERVER['HTTP_HOST'] ?? '');
    if ($refHost !== '' && $myHost !== '' && strtolower($refHost) === strtolower($myHost)) {
        $backUrl = $ref;
    }
}

/* ====== Files ====== */
$files = [];
try {
    $st = $pdo->prepare("
        SELECT id, file_name, file_path, file_type, file_size, created_at
        FROM case_files
        WHERE case_id = ? AND branch_id = ?
        ORDER BY id DESC
    ");
    $st->execute([$caseId, $branchId]);
    $files = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $files = [];
}

/* ====== base url ====== */
$baseUrl = rtrim(
    ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http')
    . '://' .
    ($_SERVER['HTTP_HOST'] ?? ''),
    '/'
);

render_layout_start('مستندات القضية');
?>

<style>
  .case-documents-page{
    color:#0b1b1f;
  }

  .case-documents-page *{
    box-sizing:border-box;
  }

  .case-documents-page .topbar-local{
    height:68px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:10px 12px;
    background:#fff;
    border:1px solid #e6edef;
    border-radius:18px;
    box-shadow:0 10px 25px rgba(0,0,0,.05);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:18px;
  }

  .case-documents-page .top-left{
    display:flex;
    align-items:center;
    gap:10px;
  }

  .case-documents-page .branch-switch{
    position:relative;
    display:inline-flex;
    align-items:center;
  }

  .case-documents-page .branch-btn{
    display:flex;
    align-items:center;
    gap:8px;
    background:#fff;
    border:1px solid #e6edef;
    border-radius:999px;
    padding:10px 12px;
    cursor:pointer;
    font-family:inherit;
    box-shadow:0 8px 18px rgba(0,0,0,.06);
  }

  .case-documents-page .branch-btn.locked{
    cursor:default;
    box-shadow:none;
  }

  .case-documents-page .branch-dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:#006a7a;
    box-shadow:0 0 0 4px rgba(0,106,122,.12);
  }

  .case-documents-page .branch-name{
    font-weight:800;
    color:#0b1b1f;
  }

  .case-documents-page .branch-caret{
    opacity:.7;
    font-size:14px;
  }

  .case-documents-page .branch-menu{
    position:absolute;
    top:calc(100% + 8px);
    right:0;
    min-width:170px;
    background:#fff;
    border:1px solid #e6edef;
    border-radius:14px;
    box-shadow:0 18px 40px rgba(0,0,0,.12);
    padding:8px;
    display:none;
    z-index:999;
  }

  .case-documents-page .branch-choice{
    width:100%;
    text-align:right;
    background:transparent;
    border:0;
    padding:10px;
    border-radius:10px;
    cursor:pointer;
    font-family:inherit;
    font-weight:800;
  }

  .case-documents-page .branch-choice:hover{
    background:#f4f7f8;
  }

  .case-documents-page .page-head{
    margin:18px 6px 14px;
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
  }

  .case-documents-page .titleWrap{
    display:flex;
    flex-direction:column;
    gap:2px;
  }

  .case-documents-page .pageTitle{
    font-size:30px;
    font-weight:900;
    color:#ffffff;
    margin:0;
  }

  .case-documents-page .pageSub{
    color:rgba(255,255,255,.72);
    font-size:14px;
  }

  .case-documents-page .actions{
    display:flex;
    gap:10px;
    align-items:center;
  }

  .case-documents-page .btnLink{
    display:inline-flex;
    align-items:center;
    gap:8px;
    height:40px;
    padding:0 14px;
    border-radius:999px;
    border:1px solid #e6edef;
    background:#fff;
    font-weight:900;
    color:#006a7a;
    text-decoration:none;
  }

  .case-documents-page .grid{
    display:grid;
    grid-template-columns:1.25fr .75fr;
    gap:14px;
  }

  @media(max-width:980px){
    .case-documents-page .grid{
      grid-template-columns:1fr;
    }
  }

  .case-documents-page .box{
    border:1px solid #e6edef;
    border-radius:16px;
    background:#fbfeff;
    overflow:hidden;
  }

  .case-documents-page .boxHead{
    padding:12px 14px;
    border-bottom:1px solid #e6edef;
    display:flex;
    justify-content:space-between;
    align-items:center;
    background:#fff;
  }

  .case-documents-page .boxHead .h{
    font-weight:900;
  }

  .case-documents-page .pill2{
    font-size:12px;
    color:#0b1b1f;
    background:#f3f7f8;
    border:1px solid #e6edef;
    padding:4px 10px;
    border-radius:999px;
    font-weight:900;
  }

  .case-documents-page .list{
    padding:10px;
  }

  .case-documents-page .empty{
    padding:14px;
    color:#6b7a7f;
  }

  .case-documents-page .fileRow{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    padding:10px;
    border:1px solid transparent;
    border-radius:14px;
  }

  .case-documents-page .fileRow:hover{
    background:#f7fbfc;
    border-color:#e6edef;
  }

  .case-documents-page .fileName{
    font-weight:900;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    max-width:520px;
  }

  .case-documents-page .fileMeta{
    color:#6b7a7f;
    font-size:12.5px;
    margin-top:3px;
  }

  .case-documents-page .fileActions{
    display:flex;
    gap:8px;
    flex:0 0 auto;
    flex-wrap:nowrap;
    white-space:nowrap;
  }

  .case-documents-page .btn{
    height:38px;
    padding:0 12px;
    border-radius:12px;
    border:1px solid #e6edef;
    background:#fff;
    cursor:pointer;
    font-weight:900;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
    gap:6px;
    font-family:inherit;
  }

  .case-documents-page .btn.primary{
    background:#006a7a;
    border-color:#006a7a;
    color:#fff;
  }

  .case-documents-page .uWrap{
    padding:12px 14px;
  }

  .case-documents-page .uRow{
    display:flex;
    gap:10px;
    align-items:center;
    flex-wrap:wrap;
  }

  .case-documents-page input[type="file"]{
    flex:1 1 260px;
    height:44px;
    border-radius:12px;
    border:1px solid #e6edef;
    padding:8px 10px;
    background:#fff;
  }

  .case-documents-page .status{
    color:#6b7a7f;
    font-size:13px;
    margin-top:10px;
  }

  .case-documents-page .hint{
    color:#6b7a7f;
    font-size:12.5px;
    margin-top:8px;
  }
</style>

<div class="case-documents-page">
  <div class="topbar-local">
    <div class="top-left">
      <div class="branch-switch">
        <?php if (!in_array($role, ['OWNER', 'ADMIN'], true)): ?>
          <div class="branch-btn locked" aria-expanded="false">
            <span class="branch-dot"></span>
            <span class="branch-name"><?= h($currentBranchName) ?></span>
          </div>
        <?php else: ?>
          <button class="branch-btn" type="button" id="branchBtn" aria-haspopup="true" aria-expanded="false">
            <span class="branch-dot"></span>
            <span class="branch-name"><?= h($currentBranchName) ?></span>
            <span class="branch-caret">▾</span>
          </button>

          <div class="branch-menu" id="branchMenu" role="menu" aria-label="Branch menu">
            <form action="<?= h(u('branch_switch.php')) ?>" method="post">
              <input type="hidden" name="branch_id" value="1">
              <button type="submit" class="branch-choice">أبوظبي</button>
            </form>
            <form action="<?= h(u('branch_switch.php')) ?>" method="post">
              <input type="hidden" name="branch_id" value="2">
              <button type="submit" class="branch-choice">دبي</button>
            </form>
            <form action="<?= h(u('branch_switch.php')) ?>" method="post">
              <input type="hidden" name="branch_id" value="3">
              <button type="submit" class="branch-choice">الشارقة</button>
            </form>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="page-head">
    <div class="titleWrap">
      <h1 class="pageTitle">مستندات القضية</h1>
      <div class="pageSub">
        رقم: <?= h((string)($case['case_no'] ?? $caseId)) ?>
        <?php if (!empty($case['title'])): ?> — <?= h((string)$case['title']) ?><?php endif; ?>
      </div>
    </div>

    <div class="actions">
      <a class="btnLink" href="<?= h($backUrl) ?>">رجوع</a>
    </div>
  </div>

  <div class="grid">
    <div class="box">
      <div class="boxHead">
        <div class="h">المرفقات</div>
        <div class="pill2"><?= (int)count($files) ?> ملف</div>
      </div>

      <div class="list">
        <?php if (empty($files)): ?>
          <div class="empty">لا توجد مرفقات لهذه القضية حتى الآن.</div>
        <?php else: ?>
          <?php foreach ($files as $f): ?>
            <?php
              $fid   = (int)($f['id'] ?? 0);
              $nameF = (string)($f['file_name'] ?? 'ملف');
              $path  = (string)($f['file_path'] ?? '');
              $dt    = (string)($f['created_at'] ?? '');
              $size  = (int)($f['file_size'] ?? 0);
              $kb    = $size > 0 ? round($size / 1024) : 0;
              $url   = fileUrl($path, $baseUrl);
            ?>
            <div class="fileRow">
              <div style="min-width:0">
                <div class="fileName"><?= h($nameF) ?></div>
                <div class="fileMeta">
                  <?= $kb ? h((string)$kb) . ' KB' : '' ?>
                  <?= $dt ? h(' • ' . $dt) : '' ?>
                </div>
              </div>

              <div class="fileActions">
                <a class="btn" href="<?= h(u('download_case_file.php?id=' . $fid . '&mode=view')) ?>" target="_blank" rel="noopener">فتح</a>
                <a class="btn primary" href="<?= h(u('download_case_file.php?id=' . $fid . '&mode=download')) ?>">تحميل</a>
              </div>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

    <div class="box">
      <div class="boxHead">
        <div class="h">رفع ملفات</div>
        <div class="pill2">حتى 10MB</div>
      </div>

      <div class="uWrap">
        <div class="uRow">
          <input id="attachments" type="file" multiple accept=".pdf,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx">
          <button class="btn primary" type="button" id="uploadBtn">رفع</button>
        </div>

        <div class="status" id="filesInfo">لم يتم اختيار أي ملف</div>
        <div class="status" id="uploadStatus">لم يتم رفع أي ملف</div>
        <div class="hint">اختر أكثر من ملف ثم اضغط رفع.</div>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const caseId = <?= (int)$caseId ?>;
  const branchId = <?= (int)$branchId ?>;

  const input = document.getElementById('attachments');
  const filesInfo = document.getElementById('filesInfo');
  const uploadBtn = document.getElementById('uploadBtn');
  const uploadStatus = document.getElementById('uploadStatus');

  function listNames() {
    if (!input || !input.files || input.files.length === 0) return 'لم يتم اختيار أي ملف';
    return Array.from(input.files).map(f => f.name).join('، ');
  }

  if (input) {
    input.addEventListener('change', function(){
      filesInfo.textContent = listNames();
      uploadStatus.textContent = 'جاهز للرفع';
    });
  }

  if (uploadBtn) {
    uploadBtn.addEventListener('click', async function(){
      if (!input.files || input.files.length === 0) {
        uploadStatus.textContent = 'اختر ملفاً أولاً';
        return;
      }

      uploadBtn.disabled = true;
      uploadStatus.textContent = 'جاري الرفع...';

      try {
        const uploads = Array.from(input.files).map(async (f) => {
          const fd = new FormData();
          fd.append('file', f);
          fd.append('case_id', String(caseId));
          fd.append('branch_id', String(branchId));

          const res = await fetch('upload_case_file.php', { method:'POST', body: fd });
          return await res.json();
        });

        const results = await Promise.all(uploads);
        const ok = results.filter(r => r && r.success).length;
        const bad = results.length - ok;

        uploadStatus.textContent = bad === 0
          ? `تم رفع ${ok} ملف ✅`
          : `تم رفع ${ok} ملف ✅ و فشل ${bad} ملف ❌`;

        setTimeout(function(){ location.reload(); }, 700);
      } catch (e) {
        uploadStatus.textContent = 'فشل الاتصال أثناء الرفع ❌';
      } finally {
        uploadBtn.disabled = false;
      }
    });
  }

  const branchBtn  = document.getElementById('branchBtn');
  const branchMenu = document.getElementById('branchMenu');

  function closeMenu(){
    if (!branchMenu) return;
    branchMenu.style.display = 'none';
    if (branchBtn) branchBtn.setAttribute('aria-expanded', 'false');
  }

  function toggleMenu(){
    if (!branchMenu || !branchBtn) return;
    const isOpen = branchMenu.style.display === 'block';
    branchMenu.style.display = isOpen ? 'none' : 'block';
    branchBtn.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
  }

  if (branchBtn && branchMenu) {
    branchBtn.addEventListener('click', function(e){
      e.stopPropagation();
      toggleMenu();
    });
    document.addEventListener('click', closeMenu);
    document.addEventListener('keydown', function(e){
      if (e.key === 'Escape') closeMenu();
    });
  }
})();
</script>

<?php render_layout_end(); ?>