<?php
declare(strict_types=1);

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

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

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

/* ===== Get PDO ===== */
$pdo = null;
if (function_exists('db')) {
    $pdo = db();
} elseif (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
    $pdo = $GLOBALS['pdo'];
}

if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready: PDO not found. Check db.php (define db():PDO or $pdo).');
}

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

/* ===== Helpers ===== */
function fileUrl(string $path, string $baseUrl): string
{
    $p = trim(str_replace('\\', '/', $path));
    $p = ltrim($p, '/');
    if ($p === '') return '#';
    if (preg_match('~^https?://~i', $p)) return $p;
    return rtrim($baseUrl, '/') . '/' . $p;
}

function table_exists_local(PDO $pdo, string $table): bool
{
    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = ?
    ");
    $st->execute([$table]);
    return ((int)$st->fetchColumn()) > 0;
}

function column_exists_local(PDO $pdo, string $table, string $column): bool
{
    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = ?
          AND column_name = ?
    ");
    $st->execute([$table, $column]);
    return ((int)$st->fetchColumn()) > 0;
}

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

/* ===== Session ===== */
$name    = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$role    = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isOwner = ($role === 'OWNER');
$isAdmin = in_array($role, ['OWNER', 'ADMIN'], true);

/* ===== App Base URL ===== */
$scheme  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host    = (string)($_SERVER['HTTP_HOST'] ?? '');
$appBase = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
$baseUrl = rtrim($scheme . '://' . $host . ($appBase === '' ? '' : $appBase), '/');

/* ===== Case info ===== */
$hasSecretCol = table_exists_local($pdo, 'cases') && column_exists_local($pdo, 'cases', 'is_secret');
$selectSecret = $hasSecretCol ? ", COALESCE(is_secret,0) AS is_secret" : ", 0 AS is_secret";

$case = [];
try {
    $st = $pdo->prepare("
        SELECT id, case_no, title, branch_id
        $selectSecret
        FROM cases
        WHERE id = ?
        LIMIT 1
    ");
    $st->execute([$caseId]);
    $case = (array)$st->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $case = [];
}

if (empty($case)) {
    http_response_code(404);
    exit('القضية غير موجودة');
}

/* ===== Secret protection: OWNER only ===== */
if (!empty($case['is_secret']) && !$isOwner) {
    http_response_code(403);
    exit('هذه القضية سرية ولا يمكن فتحها.');
}

$branchId        = (int)($case['branch_id'] ?? ($_SESSION['branch_id'] ?? 1));
$sessionBranchId = (int)($_SESSION['branch_id'] ?? 1);

/* ===== Branch name ===== */
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 => 'الشارقة',
        4 => 'العين',
        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 = ?
        ORDER BY id DESC
    ");
    $st->execute([$caseId]);
    $files = $st->fetchAll();
} catch (Throwable $e) {
    $files = [];
}

/* ===== Delete permission ===== */
$canDelete = $isAdmin || ($branchId === $sessionBranchId);

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

<style>
  :root{
    --bg-main:#07171d;
    --bg-card:rgba(255,255,255,.05);
    --bg-card-2:rgba(255,255,255,.04);
    --line:rgba(255,255,255,.08);
    --line-soft:rgba(255,255,255,.05);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --gold-2:#ffd76a;
    --gold-soft:rgba(212,175,55,.14);
    --danger:#f87171;
    --danger-soft:rgba(248,113,113,.12);
    --success:#34d399;
    --success-soft:rgba(52,211,153,.12);
    --blue:#60a5fa;
    --blue-soft:rgba(96,165,250,.12);
    --shadow:0 18px 40px rgba(0,0,0,.16);
  }

  body{
    background:
      radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
      radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
      #021d23;
  }

  .case-files-page{
    color:var(--text);
    width:100%;
    max-width:100%;
  }

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

  .case-files-page .topbar-local{
    min-height:68px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:10px 12px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:18px;
    flex-wrap:wrap;
    backdrop-filter:blur(12px);
  }

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

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

  .case-files-page .branch-btn{
    display:flex;
    align-items:center;
    gap:8px;
    background:rgba(255,255,255,.05);
    border:1px solid var(--line);
    border-radius:999px;
    padding:10px 14px;
    font-family:inherit;
    box-shadow:0 8px 18px rgba(0,0,0,.10);
    color:#fff;
    backdrop-filter:blur(8px);
  }

  .case-files-page button.branch-btn{
    cursor:pointer;
  }

  .case-files-page .branch-btn-static{
    cursor:default;
    pointer-events:none;
  }

  .case-files-page .branch-dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:var(--gold);
    box-shadow:0 0 0 4px rgba(212,175,55,.14);
  }

  .case-files-page .branch-name{
    font-weight:800;
    color:#fff;
  }

  .case-files-page .branch-caret{
    opacity:.7;
    font-size:14px;
    color:#fff;
  }

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

  .case-files-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;
    color:#fff;
  }

  .case-files-page .branch-choice:hover{
    background:rgba(255,255,255,.06);
  }

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

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

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

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

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

  .case-files-page .btnLink{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    height:40px;
    padding:0 16px;
    border-radius:999px;
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    font-weight:900;
    color:#1d1600;
    text-decoration:none;
    position:relative;
    z-index:2;
    white-space:nowrap;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
    transition:.18s ease;
  }

  .case-files-page .btnLink:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 28px rgba(212,175,55,.24);
  }

  .case-files-page .grid{
    display:grid;
    grid-template-columns:1.25fr .75fr;
    gap:14px;
    align-items:start;
  }

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

  .case-files-page .box{
    border:1px solid var(--line);
    border-radius:16px;
    background:var(--bg-card);
    overflow:hidden;
    backdrop-filter:blur(12px);
    box-shadow:var(--shadow);
  }

  .case-files-page .boxHead{
    padding:12px 14px;
    border-bottom:1px solid var(--line);
    display:flex;
    justify-content:space-between;
    align-items:center;
    background:rgba(255,255,255,.04);
    gap:10px;
    flex-wrap:wrap;
  }

  .case-files-page .boxHead .h{
    font-weight:900;
    color:#fff;
  }

  .case-files-page .pill2{
    font-size:12px;
    color:#ffd76a;
    background:rgba(212,175,55,.10);
    border:1px solid rgba(212,175,55,.18);
    padding:4px 10px;
    border-radius:999px;
    font-weight:900;
  }

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

  .case-files-page .empty{
    padding:14px;
    color:var(--muted);
  }

  .case-files-page .fileRow{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
    padding:10px;
    border:1px solid transparent;
    border-radius:14px;
    flex-wrap:wrap;
    transition:.18s ease;
  }

  .case-files-page .fileRow:hover{
    background:rgba(255,255,255,.04);
    border-color:var(--line);
  }

  .case-files-page .fileInfo{
    min-width:0;
    flex:1 1 280px;
  }

  .case-files-page .fileName{
    font-weight:900;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    max-width:100%;
    color:#fff;
  }

  .case-files-page .fileMeta{
    color:var(--muted);
    font-size:12.5px;
    margin-top:3px;
  }

  .case-files-page .fileActions{
    display:flex;
    gap:10px;
    align-items:center;
    flex:0 0 auto;
    flex-wrap:wrap;
  }

  .case-files-page .btn{
    height:38px;
    min-width:74px;
    padding:0 14px;
    border-radius:999px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    cursor:pointer;
    font-weight:900;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:6px;
    font-family:inherit;
    white-space:nowrap;
    transition:.18s ease;
  }

  .case-files-page .btn:hover{
    background:rgba(255,255,255,.08);
    transform:translateY(-1px);
  }

  .case-files-page .btn.primary{
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    border-color:rgba(212,175,55,.25);
    color:#1d1600;
    box-shadow:0 10px 20px rgba(212,175,55,.16);
  }

  .case-files-page .btn.primary:hover{
    transform:translateY(-2px);
    box-shadow:0 14px 24px rgba(212,175,55,.22);
  }

  .case-files-page .btn.danger{
    background:rgba(248,113,113,.08);
    border-color:rgba(248,113,113,.22);
    color:#fca5a5;
  }

  .case-files-page .btn.danger:hover{
    background:rgba(248,113,113,.14);
  }

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

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

  .case-files-page input[type="file"]{
    flex:1 1 260px;
    height:44px;
    border-radius:12px;
    border:1px solid var(--line);
    padding:8px 10px;
    background:rgba(255,255,255,.05);
    color:#fff;
    font-family:inherit;
  }

  .case-files-page .status{
    color:var(--muted);
    font-size:13px;
    margin-top:10px;
  }

  .case-files-page .hint{
    color:var(--muted);
    font-size:12.5px;
    margin-top:8px;
    line-height:1.7;
  }

  .case-files-page .footerNote{
    margin-top:18px;
    padding:14px 18px;
    border-radius:16px;
    background:rgba(255,255,255,.04);
    border:1px solid rgba(255,255,255,.08);
    backdrop-filter:blur(8px);
    color:rgba(255,255,255,.75);
    font-size:13px;
  }

  .case-files-page .footer-inner{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:10px;
  }

  .case-files-page .footer-copy{
    color:#ffd76a !important;
    font-weight:700;
    letter-spacing:.3px;
  }

  .case-files-page .footer-system{
    font-weight:800;
    color:#d4af37;
    letter-spacing:.5px;
  }

  @media (max-width:700px){
    .case-files-page .footer-inner{
      flex-direction:column;
      text-align:center;
    }

    .case-files-page .pageTitle{
      font-size:24px;
    }
  }
</style>

<div class="case-files-page">

 <div class="topbar-local">
  <div class="top-left"></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);
              if ($fid <= 0) continue;

              $nameF = (string)($f['file_name'] ?? 'ملف');
              $dt    = (string)($f['created_at'] ?? '');
              $size  = (int)($f['file_size'] ?? 0);
              $kb    = $size > 0 ? round($size / 1024) : 0;
            ?>
            <div class="fileRow">
              <div class="fileInfo">
                <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('view_case_file.php?id=' . $fid)) ?>" target="_blank" rel="noopener">فتح</a>
                <a class="btn primary" href="<?= h(u('download_case_file.php?id=' . $fid)) ?>">تحميل</a>

                <?php if ($canDelete): ?>
                  <form action="<?= h(u('case_file_delete.php')) ?>" method="post" style="display:inline" onsubmit="return confirm('حذف الملف نهائياً؟');">
                    <input type="hidden" name="file_id" value="<?= $fid ?>">
                    <input type="hidden" name="case_id" value="<?= (int)$caseId ?>">
                    <button type="submit" class="btn danger">حذف</button>
                  </form>
                <?php endif; ?>
              </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 || !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(() => 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.preventDefault();
      e.stopPropagation();
      toggleMenu();
    });

    branchMenu.addEventListener('click', function(e){
      e.stopPropagation();
    });

    document.addEventListener('click', function(){
      closeMenu();
    });

    document.addEventListener('keydown', function(e){
      if (e.key === 'Escape') closeMenu();
    });
  }
})();
</script>

<?php render_layout_end(); ?>