<?php
declare(strict_types=1);

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

date_default_timezone_set('Asia/Dubai');
require_once dirname(__DIR__) . '/db.php';

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

function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function csrf_token(): string {
    if (empty($_SESSION['csrf_hearing_delete'])) {
        $_SESSION['csrf_hearing_delete'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_hearing_delete'];
}

function csrf_check(): bool {
    $token = (string)($_POST['csrf_token'] ?? '');
    return hash_equals((string)($_SESSION['csrf_hearing_delete'] ?? ''), $token);
}

$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);

/*
|--------------------------------------------------------------------------
| بيانات المستخدم
|--------------------------------------------------------------------------
*/
$currentUser   = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$currentBranch = (string)($_SESSION['branch_name'] ?? 'أبوظبي');
$role          = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$sessionBranchId = (int)($_SESSION['branch_id'] ?? 1);

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);

$msg = '';
$err = '';
$hearing = null;

if ($id <= 0) {
    $err = 'معرف الجلسة غير صالح.';
} else {
    try {
        if (in_array($role, ['OWNER', 'ADMIN'], true)) {
            $st = $pdo->prepare("
                SELECT
                    cs.id,
                    cs.case_id,
                    c.case_no AS case_number,
                    c.title AS case_title,
                    c.client_name,
                    cs.court_name,
                    cs.session_date AS hearing_date,
                    cs.session_time AS hearing_time,
                    c.lawyer_name
                FROM case_sessions cs
                INNER JOIN cases c ON c.id = cs.case_id
                WHERE cs.id = ?
                LIMIT 1
            ");
            $st->execute([$id]);
        } else {
            $st = $pdo->prepare("
                SELECT
                    cs.id,
                    cs.case_id,
                    c.case_no AS case_number,
                    c.title AS case_title,
                    c.client_name,
                    cs.court_name,
                    cs.session_date AS hearing_date,
                    cs.session_time AS hearing_time,
                    c.lawyer_name
                FROM case_sessions cs
                INNER JOIN cases c ON c.id = cs.case_id
                WHERE cs.id = ?
                  AND c.branch_id = ?
                LIMIT 1
            ");
            $st->execute([$id, $sessionBranchId]);
        }

        $hearing = $st->fetch();
        if (!$hearing) {
            $err = 'الجلسة المطلوبة غير موجودة أو تم حذفها مسبقًا.';
        }
    } catch (Throwable $e) {
        $err = 'تعذر جلب بيانات الجلسة.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $err === '' && $hearing) {
    if (!csrf_check()) {
        $err = 'رمز الحماية غير صالح، يرجى إعادة المحاولة.';
    } else {
        try {
            $pdo->beginTransaction();

            $caseId = (int)$hearing['case_id'];

            $del = $pdo->prepare("
                DELETE FROM case_sessions
                WHERE id = ?
                LIMIT 1
            ");
            $del->execute([(int)$hearing['id']]);

            $stNext = $pdo->prepare("
                SELECT session_date
                FROM case_sessions
                WHERE case_id = ?
                ORDER BY session_date ASC, session_time ASC, id ASC
                LIMIT 1
            ");
            $stNext->execute([$caseId]);
            $nextDate = $stNext->fetchColumn();

            $up = $pdo->prepare("
                UPDATE cases
                SET next_hearing_date = :next_hearing_date
                WHERE id = :id
                LIMIT 1
            ");
            $up->execute([
                'next_hearing_date' => ($nextDate !== false ? $nextDate : null),
                'id' => $caseId,
            ]);

            $pdo->commit();

            $_SESSION['flash_success'] = 'تم حذف الجلسة بنجاح.';
            header('Location: case_edit.php?id=' . $caseId . '#sessionsBox');
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $err = 'حدث خطأ أثناء حذف الجلسة.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>حذف جلسة | HLG Justice Hub</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
  <style>
    :root{
      --bg:#f4f7fb;
      --card:#ffffff;
      --line:#e6edf5;
      --text:#0f2740;
      --muted:#6f8094;
      --danger:#d64545;
      --danger-bg:#fff1f1;
      --danger-line:#ffd7d7;
      --shadow:0 10px 30px rgba(15,39,64,.07);
      --radius:20px;
    }

    *{box-sizing:border-box}
    html,body{
      margin:0;
      padding:0;
      background:var(--bg);
      color:var(--text);
      font-family:'Tajawal',sans-serif;
    }

    a{text-decoration:none;color:inherit}

    .page{
      display:grid;
      grid-template-columns:300px 1fr;
      min-height:100vh;
    }

    .sidebar{
      background:linear-gradient(180deg, #092237 0%, #0c2f4c 100%);
      color:#fff;
      padding:22px 18px;
      position:sticky;
      top:0;
      height:100vh;
      border-left:1px solid rgba(255,255,255,.08);
    }

    .brand{
      padding:16px 14px;
      border:1px solid rgba(255,255,255,.08);
      border-radius:20px;
      background:rgba(255,255,255,.03);
      margin-bottom:18px;
    }

    .brand h2{
      margin:0 0 6px;
      font-size:24px;
      font-weight:800;
    }

    .brand p{
      margin:0;
      color:rgba(255,255,255,.72);
      font-size:13px;
    }

    .side-nav{
      display:flex;
      flex-direction:column;
      gap:10px;
      margin-top:18px;
    }

    .side-link{
      display:flex;
      align-items:center;
      justify-content:space-between;
      padding:15px 16px;
      border-radius:16px;
      color:#e9f2fb;
      background:rgba(255,255,255,.02);
      border:1px solid rgba(255,255,255,.06);
      transition:.2s ease;
    }

    .side-link:hover,
    .side-link.active{
      background:rgba(255,255,255,.09);
      transform:translateX(-2px);
    }

    .side-link small{
      color:#b8d0e7;
      font-size:12px;
    }

    .main{
      padding:24px;
      display:flex;
      align-items:flex-start;
      justify-content:center;
    }

    .wrap{
      width:100%;
      max-width:900px;
    }

    .topbar{
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:16px;
      flex-wrap:wrap;
      margin-bottom:20px;
    }

    .topbar-right h1{
      margin:0 0 6px;
      font-size:30px;
      font-weight:800;
    }

    .topbar-right p{
      margin:0;
      color:var(--muted);
      font-size:14px;
    }

    .topbar-left{
      display:flex;
      align-items:center;
      gap:12px;
      flex-wrap:wrap;
    }

    .chip{
      background:#fff;
      border:1px solid var(--line);
      border-radius:999px;
      padding:10px 16px;
      box-shadow:var(--shadow);
      font-weight:700;
    }

    .card{
      background:var(--card);
      border:1px solid var(--line);
      border-radius:var(--radius);
      box-shadow:var(--shadow);
      overflow:hidden;
    }

    .card-head{
      padding:22px 22px 10px;
      border-bottom:1px solid #edf2f7;
      background:linear-gradient(180deg, #fff 0%, #fbfdff 100%);
    }

    .card-head h3{
      margin:0 0 8px;
      font-size:24px;
      font-weight:800;
    }

    .card-head p{
      margin:0;
      color:var(--muted);
      font-size:14px;
    }

    .card-body{
      padding:22px;
    }

    .alert{
      border-radius:16px;
      padding:16px 18px;
      margin-bottom:16px;
      font-size:14px;
      font-weight:700;
    }

    .alert.error{
      background:var(--danger-bg);
      color:var(--danger);
      border:1px solid var(--danger-line);
    }

    .warning-box{
      background:var(--danger-bg);
      border:1px solid var(--danger-line);
      color:var(--danger);
      border-radius:18px;
      padding:18px;
      margin-bottom:18px;
    }

    .warning-box h4{
      margin:0 0 8px;
      font-size:20px;
      font-weight:800;
    }

    .warning-box p{
      margin:0;
      line-height:1.9;
      font-size:14px;
    }

    .details{
      display:grid;
      grid-template-columns:repeat(2, minmax(0,1fr));
      gap:14px;
      margin-bottom:18px;
    }

    .detail{
      background:#fbfdff;
      border:1px solid #edf2f7;
      border-radius:16px;
      padding:14px 16px;
    }

    .detail-label{
      color:var(--muted);
      font-size:13px;
      margin-bottom:6px;
      font-weight:700;
    }

    .detail-value{
      color:var(--text);
      font-size:16px;
      font-weight:800;
      line-height:1.6;
    }

    .actions{
      display:flex;
      gap:10px;
      justify-content:flex-end;
      flex-wrap:wrap;
      margin-top:10px;
    }

    .btn{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      gap:8px;
      border:none;
      border-radius:14px;
      padding:12px 18px;
      font-family:inherit;
      font-size:14px;
      font-weight:700;
      cursor:pointer;
      transition:.2s ease;
    }

    .btn-light{
      background:#fff;
      color:var(--text);
      border:1px solid var(--line);
    }

    .btn-light:hover{
      background:#f8fbff;
    }

    .btn-danger{
      background:var(--danger);
      color:#fff;
      box-shadow:0 12px 24px rgba(214,69,69,.18);
    }

    .btn-danger:hover{
      opacity:.95;
    }

    @media (max-width: 980px){
      .page{grid-template-columns:1fr}
      .sidebar{
        position:relative;
        height:auto;
        border-left:none;
        border-bottom:1px solid rgba(255,255,255,.08);
      }
    }

    @media (max-width: 700px){
      .main{padding:14px}
      .details{grid-template-columns:1fr}
      .topbar-right h1{font-size:24px}
    }
  </style>
</head>
<body>
  <div class="page">

    <aside class="sidebar">
      <div class="brand">
        <h2>HLG Justice Hub</h2>
        <p>بوابة إدارة الأعمال القانونية</p>
      </div>

      <nav class="side-nav">
        <a class="side-link" href="../../dashboard.php">
          <span>لوحة التحكم</span>
          <small>الرئيسية</small>
        </a>

        <a class="side-link" href="../cases/cases.php">
          <span>القضايا</span>
          <small>إدارة</small>
        </a>

        <a class="side-link active" href="hearings.php">
          <span>الجلسات</span>
          <small>متابعة</small>
        </a>

        <a class="side-link" href="../tasks/tasks.php">
          <span>المهام</span>
          <small>تنفيذ</small>
        </a>

        <a class="side-link" href="../finance/finance.php">
          <span>الإدارة المالية</span>
          <small>النظام المالي</small>
        </a>

        <a class="side-link" href="../employees/employees.php">
          <span>شؤون الموظفين</span>
          <small>HR</small>
        </a>

        <a class="side-link" href="../notifications/notifications.php">
          <span>الإشعارات</span>
          <small>تنبيه</small>
        </a>
      </nav>
    </aside>

    <main class="main">
      <div class="wrap">
        <div class="topbar">
          <div class="topbar-right">
            <h1>حذف جلسة</h1>
            <p>تأكيد حذف الجلسة المحددة من النظام</p>
          </div>

          <div class="topbar-left">
            <div class="chip">الفرع: <?= h($currentBranch) ?></div>
            <div class="chip"><?= h($currentUser) ?></div>
          </div>
        </div>

        <section class="card">
          <div class="card-head">
            <h3>تأكيد الحذف</h3>
            <p>راجع بيانات الجلسة بدقة قبل تنفيذ الحذف النهائي</p>
          </div>

          <div class="card-body">
            <?php if ($err !== ''): ?>
              <div class="alert error"><?= h($err) ?></div>
              <div class="actions">
                <a href="hearings.php" class="btn btn-light">العودة إلى الجلسات</a>
              </div>
            <?php else: ?>

              <div class="warning-box">
                <h4>تنبيه مهم</h4>
                <p>
                  أنت على وشك حذف هذه الجلسة من النظام. هذا الإجراء يجب أن يكون مقصورًا على الحالات الضرورية فقط.
                  عند ربط الصفحة بقاعدة البيانات سيتم حذف السجل الفعلي وما يرتبط به حسب آلية النظام.
                </p>
              </div>

              <div class="details">
                <div class="detail">
                  <div class="detail-label">رقم القضية</div>
                  <div class="detail-value"><?= h($hearing['case_number']) ?></div>
                </div>

                <div class="detail">
                  <div class="detail-label">اسم القضية</div>
                  <div class="detail-value"><?= h($hearing['case_title']) ?></div>
                </div>

                <div class="detail">
                  <div class="detail-label">اسم العميل</div>
                  <div class="detail-value"><?= h($hearing['client_name']) ?></div>
                </div>

                <div class="detail">
                  <div class="detail-label">المحكمة</div>
                  <div class="detail-value"><?= h($hearing['court_name']) ?></div>
                </div>

                <div class="detail">
                  <div class="detail-label">تاريخ الجلسة</div>
                  <div class="detail-value"><?= h($hearing['hearing_date']) ?></div>
                </div>

                <div class="detail">
                  <div class="detail-label">وقت الجلسة</div>
                  <div class="detail-value"><?= h($hearing['hearing_time']) ?></div>
                </div>

                <div class="detail" style="grid-column:1 / -1;">
                  <div class="detail-label">المحامي المسؤول</div>
                  <div class="detail-value"><?= h($hearing['lawyer_name']) ?></div>
                </div>
              </div>

              <form method="post" action="">
                <input type="hidden" name="id" value="<?= (int)$hearing['id'] ?>">
                <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">

                <div class="actions">
                  <a href="hearings.php" class="btn btn-light">إلغاء</a>
                  <a href="hearing_view.php?id=<?= (int)$hearing['id'] ?>" class="btn btn-light">عرض الجلسة</a>
                  <button type="submit" class="btn btn-danger">تأكيد حذف الجلسة</button>
                </div>
              </form>

            <?php endif; ?>
          </div>
        </section>
      </div>
    </main>
  </div>
</body>
</html>