<?php
declare(strict_types=1);

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

date_default_timezone_set('Asia/Dubai');

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/auth.php';
require_once __DIR__ . '/../inc/layout.php';
require_once __DIR__ . '/../inc/activity_log.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($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

$userId   = (int)($_SESSION['user_id'] ?? 0);
$branchId = (int)($_SESSION['branch_id'] ?? 1);

$errMsg = '';



$form = [
    'case_id'             => '',
    'case_number'         => '',
    'case_title'          => '',
    'client_name'         => '',
    'branch_id'           => (string)$branchId,
    'responsible_user_id' => '',
    'court_name'          => '',
    'hearing_type'        => '',
    'hearing_date'        => date('Y-m-d'),
    'hearing_time'        => '',
    'status'              => 'SCHEDULED',
    'notes'               => '',
];

$statuses = [
    'SCHEDULED' => 'مجدولة',
    'DONE'      => 'تمت',
    'POSTPONED' => 'مؤجلة',
    'CANCELLED' => 'ملغاة',
];

$hearingTypes = [
    'جلسة أولى',
    'جلسة مرافعة',
    'جلسة متابعة',
    'جلسة مستندات',
    'جلسة نطق بالحكم',
    'جلسة خبرة',
    'جلسة صلح',
];

$employees = $pdo->query("
    SELECT id, COALESCE(NULLIF(name,''), username) AS name
    FROM users
    ORDER BY name ASC
")->fetchAll();

$branches = $pdo->query("
    SELECT id, name_ar
    FROM branches
    ORDER BY id ASC
")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    foreach ($form as $key => $value) {
        $form[$key] = trim((string)($_POST[$key] ?? ''));
    }

    if (
        $form['court_name'] === '' ||
        $form['hearing_date'] === '' ||
        (int)$form['branch_id'] <= 0 ||
        (int)$form['responsible_user_id'] <= 0
    ) {
        $errMsg = 'يرجى إدخال المحكمة وتاريخ الجلسة والفرع والموظف المسؤول.';
    } else {
        try {
            $pdo->beginTransaction();

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

            if ($caseId <= 0 && $form['case_number'] !== '') {
                $stCase = $pdo->prepare("
                    SELECT id
                    FROM cases
                    WHERE case_no = ?
                    LIMIT 1
                ");
                $stCase->execute([$form['case_number']]);
                $caseId = (int)($stCase->fetchColumn() ?: 0);
            }

            if ($caseId <= 0) {
                $stCase = $pdo->query("SELECT id FROM cases ORDER BY id DESC LIMIT 1");
                $caseId = (int)($stCase->fetchColumn() ?: 0);
            }

            if ($caseId <= 0) {
                throw new RuntimeException('لا توجد قضية في النظام لربط الجلسة بها.');
            }

            $status = strtoupper($form['status'] ?: 'SCHEDULED');

            if (!array_key_exists($status, $statuses)) {
                $status = 'SCHEDULED';
            }

 $st = $pdo->prepare("
    INSERT INTO case_sessions
    (
        case_id,
        branch_id,
        session_date,
        session_time,
        session_type,
        court_name,
        status,
        notes,
        added_by_user_id,
        responsible_user_id,
        created_at
    )
    VALUES
    (
        :case_id,
        :branch_id,
        :session_date,
        :session_time,
        :session_type,
        :court_name,
        :status,
        :notes,
        :added_by_user_id,
        :responsible_user_id,
        NOW()
    )
");

$st->execute([
    ':case_id'             => $caseId,
    ':branch_id'           => (int)$form['branch_id'],
    ':session_date'        => $form['hearing_date'],
    ':session_time'        => $form['hearing_time'] !== '' ? $form['hearing_time'] : null,
    ':session_type'        => $form['hearing_type'] !== '' ? $form['hearing_type'] : null,
    ':court_name'          => $form['court_name'],
    ':status'              => $status,
    ':notes'               => $form['notes'] !== '' ? $form['notes'] : null,
    ':added_by_user_id'    => $userId > 0 ? $userId : null,
    ':responsible_user_id' => (int)$form['responsible_user_id'],
]);


            $hearingId = (int)$pdo->lastInsertId();

            $pdo->commit();

            activity_log(
                $pdo,
                'create_hearing',
                'hearings',
                'hearing',
                $hearingId,
                'تم إضافة جلسة جديدة | المحكمة: ' . $form['court_name'],
                'إضافة جلسة',
                '⚖️',
                '#06b6d4'
            );

            $_SESSION['flash_success'] = 'تم حفظ الجلسة بنجاح.';
            header("Location: hearings.php");
            exit;

        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            $errMsg = 'فشل حفظ الجلسة: ' . $e->getMessage();
        }
    }
}

render_layout_start('إضافة جلسة');
?>

<style>
.hearing-add-page{color:#fff;width:100%;padding-bottom:30px}
.hearing-add-page *{box-sizing:border-box}
.hearing-add-page .page-head{max-width:1100px;margin:20px auto;display:flex;justify-content:space-between;align-items:center;gap:15px}
.hearing-add-page .pageTitle{font-size:30px;font-weight:900;margin:0}
.hearing-add-page .pageSub{color:rgba(255,255,255,.75);margin-top:6px}
.hearing-add-page .btnLink{display:inline-flex;align-items:center;justify-content:center;height:48px;padding:0 22px;border-radius:999px;background:linear-gradient(135deg,#ffd76a,#d4af37);color:#1a1400!important;font-weight:900;text-decoration:none}
.hearing-add-page .box{max-width:1100px;margin:auto}
.hearing-add-page .formGrid{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:22px;padding:24px;box-shadow:0 18px 40px rgba(0,0,0,.16)}
.hearing-form{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
.hearing-row{display:flex;flex-direction:column;gap:8px}
.hearing-row label{font-weight:900;color:#fff}
.hearing-row input,.hearing-row select,.hearing-row textarea{width:100%;min-height:52px;border-radius:14px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.25);color:#fff;padding:12px;font-family:inherit}
.hearing-row select option{background:#0b1f26;color:#fff}
.hearing-row textarea{min-height:130px;resize:vertical}
.span-3{grid-column:1/-1}
.btn-save{width:100%;height:56px;border:none;border-radius:999px;background:linear-gradient(135deg,#ffd76a,#d4af37);color:#1a1400;font-weight:900;cursor:pointer;font-family:inherit}
.err{background:rgba(127,29,29,.8);border:1px solid rgba(248,113,113,.4);padding:12px;border-radius:12px;margin-bottom:14px;color:#fff}
@media(max-width:900px){.hearing-form{grid-template-columns:1fr}.span-3{grid-column:auto}.hearing-add-page .page-head{flex-direction:column;align-items:flex-start}}
</style>

<div class="hearing-add-page">

  <div class="page-head">
    <div>
      <h1 class="pageTitle">إضافة جلسة</h1>
      <div class="pageSub">سيتم حفظ الجلسة ثم عرضها مباشرة في صفحة الجلسات.</div>
    </div>
    <a class="btnLink" href="<?= h(u('hearings/hearings.php')) ?>">رجوع</a>
  </div>

  <div class="box">
    <div class="formGrid">

      <?php if ($errMsg !== ''): ?>
        <div class="err"><?= h($errMsg) ?></div>
      <?php endif; ?>

      <form method="post" class="hearing-form" autocomplete="off">

        <div class="hearing-row">
          <label>معرف القضية</label>
          <input name="case_id" placeholder="اختياري" value="<?= h($form['case_id']) ?>">
        </div>

        <div class="hearing-row">
          <label>رقم القضية</label>
          <input name="case_number" placeholder="اختياري" value="<?= h($form['case_number']) ?>">
        </div>

        <div class="hearing-row">
          <label>اسم القضية</label>
          <input name="case_title" placeholder="اختياري" value="<?= h($form['case_title']) ?>">
        </div>

        <div class="hearing-row">
          <label>اسم العميل</label>
          <input name="client_name" placeholder="اختياري" value="<?= h($form['client_name']) ?>">
        </div>

        <div class="hearing-row">
          <label>الفرع</label>
          <select name="branch_id" required>
            <option value="">اختر الفرع</option>
            <?php foreach ($branches as $b): ?>
              <option value="<?= (int)$b['id'] ?>" <?= (int)$form['branch_id'] === (int)$b['id'] ? 'selected' : '' ?>>
                <?= h($b['name_ar']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="hearing-row">
          <label>الموظف المسؤول</label>
          <select name="responsible_user_id" required>
            <option value="">اختر الموظف المسؤول</option>
            <?php foreach ($employees as $emp): ?>
              <option value="<?= (int)$emp['id'] ?>" <?= (int)$form['responsible_user_id'] === (int)$emp['id'] ? 'selected' : '' ?>>
                <?= h($emp['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="hearing-row">
          <label>المحكمة</label>
          <input name="court_name" required placeholder="محكمة أبوظبي الابتدائية" value="<?= h($form['court_name']) ?>">
        </div>

        <div class="hearing-row">
          <label>نوع الجلسة</label>
          <select name="hearing_type">
            <option value="">اختر نوع الجلسة</option>
            <?php foreach ($hearingTypes as $type): ?>
              <option value="<?= h($type) ?>" <?= $form['hearing_type'] === $type ? 'selected' : '' ?>>
                <?= h($type) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="hearing-row">
          <label>تاريخ الجلسة</label>
          <input type="date" name="hearing_date" required value="<?= h($form['hearing_date']) ?>">
        </div>

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

        <div class="hearing-row">
          <label>حالة الجلسة</label>
          <select name="status">
            <?php foreach ($statuses as $key => $label): ?>
              <option value="<?= h($key) ?>" <?= $form['status'] === $key ? 'selected' : '' ?>>
                <?= h($label) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="hearing-row span-3">
          <label>ملاحظات الجلسة</label>
          <textarea name="notes" placeholder="اكتب ملاحظات الجلسة..."><?= h($form['notes']) ?></textarea>
        </div>

        <div class="hearing-row span-3">
          <button type="submit" class="btn-save">حفظ الجلسة</button>
        </div>

      </form>
    </div>
  </div>
</div>

<?php render_layout_end(); ?>