<?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/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 Error');
}

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

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

if ($id <= 0) {
    exit('جلسة غير صالحة');
}

/* =========================
   جلب بيانات الجلسة
========================= */

$st = $pdo->prepare("
    SELECT *
    FROM case_sessions
    WHERE id = ?
    LIMIT 1
");

$st->execute([$id]);

$session = $st->fetch();

if (!$session) {
    exit('الجلسة غير موجودة');
}

/* =========================
   حفظ التعديلات
========================= */

$success = '';
$error   = '';

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

    $court_name   = trim((string)($_POST['court_name'] ?? ''));
    $session_type = trim((string)($_POST['session_type'] ?? ''));
    $session_date = trim((string)($_POST['session_date'] ?? ''));
    $session_time = trim((string)($_POST['session_time'] ?? ''));
    $status       = trim((string)($_POST['status'] ?? ''));
    $notes        = trim((string)($_POST['notes'] ?? ''));

    if ($court_name === '' || $session_date === '') {

        $error = 'يرجى تعبئة الحقول المطلوبة';

    } else {

        $up = $pdo->prepare("
            UPDATE case_sessions
            SET
                court_name   = ?,
                session_type = ?,
                session_date = ?,
                session_time = ?,
                status        = ?,
                notes         = ?
            WHERE id = ?
        ");

        $up->execute([
            $court_name,
            $session_type,
            $session_date,
            $session_time,
            $status,
            $notes,
            $id
        ]);

        $_SESSION['flash_success'] = 'تم تحديث الجلسة بنجاح';

        header("Location: hearings.php");
        exit;
    }
}

render_layout_start('تعديل الجلسة');
?>

<style>
.edit-page{
    max-width:900px;
    margin:20px auto;
    color:#fff;
}

.edit-card{
    background:rgba(255,255,255,.05);
    border:1px solid rgba(255,255,255,.08);
    border-radius:24px;
    padding:24px;
    backdrop-filter:blur(12px);
    box-shadow:0 20px 40px rgba(0,0,0,.25);
}

.edit-title{
    font-size:28px;
    font-weight:800;
    margin-bottom:20px;
}

.form-grid{
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:16px;
}

.field{
    display:flex;
    flex-direction:column;
    gap:8px;
}

.field-full{
    grid-column:1/-1;
}

label{
    font-size:13px;
    color:rgba(255,255,255,.70);
    font-weight:700;
}

.input,
.select,
textarea{
    width:100%;
    background:rgba(255,255,255,.05);
    border:1px solid rgba(255,255,255,.08);
    border-radius:14px;
    padding:14px;
    color:#fff;
    outline:none;
}

textarea{
    min-height:140px;
    resize:vertical;
}

.input:focus,
.select:focus,
textarea:focus{
    border-color:#d4af37;
    box-shadow:0 0 0 4px rgba(212,175,55,.15);
}

.actions{
    margin-top:24px;
    display:flex;
    gap:12px;
    flex-wrap:wrap;
}

.btn-save{
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1a1400;
    border:none;
    border-radius:14px;
    padding:14px 22px;
    font-weight:800;
    cursor:pointer;
}

.btn-back{
    background:rgba(255,255,255,.06);
    color:#fff;
    border:1px solid rgba(255,255,255,.08);
    border-radius:14px;
    padding:14px 22px;
    text-decoration:none;
    font-weight:700;
}

.alert-error{
    margin-bottom:16px;
    padding:14px;
    border-radius:14px;
    background:rgba(239,68,68,.14);
    border:1px solid rgba(239,68,68,.25);
}

@media(max-width:768px){

    .form-grid{
        grid-template-columns:1fr;
    }

}
</style>

<div class="edit-page">

    <div class="edit-card">

        <div class="edit-title">
            ✏️ تعديل الجلسة
        </div>

        <?php if ($error): ?>
            <div class="alert-error">
                <?= h($error) ?>
            </div>
        <?php endif; ?>

        <form method="post">

            <div class="form-grid">

                <div class="field">
                    <label>المحكمة</label>
                    <input
                        type="text"
                        name="court_name"
                        class="input"
                        value="<?= h($session['court_name']) ?>"
                    >
                </div>

                <div class="field">
                    <label>نوع الجلسة</label>
                    <input
                        type="text"
                        name="session_type"
                        class="input"
                        value="<?= h($session['session_type']) ?>"
                    >
                </div>

                <div class="field">
                    <label>تاريخ الجلسة</label>
                    <input
                        type="date"
                        name="session_date"
                        class="input"
                        value="<?= h($session['session_date']) ?>"
                    >
                </div>

                <div class="field">
                    <label>وقت الجلسة</label>
                    <input
                        type="time"
                        name="session_time"
                        class="input"
                        value="<?= h($session['session_time']) ?>"
                    >
                </div>

                <div class="field">
                    <label>الحالة</label>

                    <select name="status" class="select">

                        <option value="SCHEDULED" <?= $session['status'] === 'SCHEDULED' ? 'selected' : '' ?>>
                            مجدولة
                        </option>

                        <option value="DONE" <?= $session['status'] === 'DONE' ? 'selected' : '' ?>>
                            تمت
                        </option>

                        <option value="POSTPONED" <?= $session['status'] === 'POSTPONED' ? 'selected' : '' ?>>
                            مؤجلة
                        </option>

                        <option value="CANCELLED" <?= $session['status'] === 'CANCELLED' ? 'selected' : '' ?>>
                            ألغيت
                        </option>

                        <option value="PENDING_RESULT" <?= $session['status'] === 'PENDING_RESULT' ? 'selected' : '' ?>>
                            بانتظار النتيجة
                        </option>

                    </select>
                </div>

                <div class="field field-full">
                    <label>ملاحظات الجلسة</label>

                    <textarea name="notes"><?= h($session['notes']) ?></textarea>
                </div>

            </div>

            <div class="actions">

                <button type="submit" class="btn-save">
                    💾 حفظ التعديلات
                </button>

                <a href="hearings.php" class="btn-back">
                    رجوع
                </a>

            </div>

        </form>

    </div>

</div>

<?php render_layout_end(); ?>