<?php

declare(strict_types=1);

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

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

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

/* =========================
   Helpers
========================= */
if (!function_exists('h')) {
    function h($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('status_ar')) {
    function status_ar(string $s): string
    {
        $s = strtoupper(trim($s));
        return match ($s) {
            'NEW'    => 'جديدة',
            'WORK'   => 'قيد العمل',
            'COURT'  => 'في المحكمة',
            'CLOSED' => 'مغلقة',
            default  => 'قيد العمل',
        };
    }
}
if (!function_exists('session_status_ar')) {
    function session_status_ar(string $s): string
    {
        $s = strtoupper(trim($s));

        return match ($s) {
            'SCHEDULED'        => 'مجدولة',
            'DONE'             => 'تمت',
            'POSTPONED'        => 'مؤجلة',
            'CANCELLED'        => 'ملغاة',

            // 👇 الحالة الجديدة
            'PENDING_RESULT',
            'PENDING',
            'WAITING_RESULT'   => 'بانتظار النتيجة',

            // 👇 في حال كانت محفوظة بالعربي أصلاً
            'بانتظار النتيجة' => 'بانتظار النتيجة',

            default            => 'مجدولة',
        };
    }
}

if (!function_exists('session_status_class')) {
    function session_status_class(string $s): string
    {
        $s = strtoupper(trim($s));

        return match ($s) {
            'DONE'            => 'done',
            'POSTPONED'       => 'postponed',
            'CANCELLED'       => 'cancelled',
            'PENDING_RESULT',
            'PENDING',
            'WAITING_RESULT'  => 'pending',
            default           => 'scheduled',
        };
    }
}

if (!function_exists('table_exists_local')) {
    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;
    }
}

if (!function_exists('column_exists_local')) {
    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;
    }
}

if (!function_exists('notifications_table_exists_local')) {
    function notifications_table_exists_local(PDO $pdo): bool
    {
        return table_exists_local($pdo, 'notifications');
    }
}

if (!function_exists('notify_user_local')) {
    function notify_user_local(
        PDO $pdo,
        int $userId,
        string $title,
        string $message,
        string $type = 'case_update',
        ?int $relatedId = null
    ): bool {
        if ($userId <= 0 || !notifications_table_exists_local($pdo)) {
            return false;
        }

        $st = $pdo->prepare("
            INSERT INTO notifications (
                user_id,
                title,
                message,
                type,
                related_id,
                is_read,
                created_at
            ) VALUES (?, ?, ?, ?, ?, 0, NOW())
        ");

        return $st->execute([
            $userId,
            $title,
            $message,
            $type,
            $relatedId,
        ]);
    }
}

if (!function_exists('notify_all_users_case_update_local')) {
    
    function notify_all_users_case_update_local(
        PDO $pdo,
        int $caseId,
        string $caseNo,
        string $caseTitle,
        string $editedByName
    ): void {
        if (!notifications_table_exists_local($pdo)) {
            return;
        }

        if (!table_exists_local($pdo, 'users')) {
            return;
        }

        $title = 'تعديل على قضية';
        $message = "تم تعديل القضية رقم {$caseNo} - {$caseTitle} بواسطة {$editedByName}";

        $st = $pdo->query("SELECT id FROM users WHERE id IS NOT NULL");
        $users = $st->fetchAll(PDO::FETCH_ASSOC);

        foreach ($users as $user) {
            $uid = (int)($user['id'] ?? 0);
            if ($uid > 0) {
                notify_user_local($pdo, $uid, $title, $message, 'case_update', $caseId);
            }
        }
    }
}

if (!function_exists('valid_ymd_or_null')) {
    function valid_ymd_or_null(?string $date): ?string
    {
        $date = trim((string)$date);
        if ($date === '') {
            return null;
        }

        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return null;
        }

        [$y, $m, $d] = array_map('intval', explode('-', $date));
        if (!checkdate($m, $d, $y)) {
            return null;
        }

        return $date;
    }
}

/* =========================
   Inputs / Session
========================= */
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    header("Location: " . u('cases.php?e=missing_id'));
    exit;
}

$role        = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$branchId    = (int)($_SESSION['branch_id'] ?? 1);
$currentUid  = (int)($_SESSION['user_id'] ?? 0);
$currentName = trim((string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم النظام'));

if ($branchId <= 0) {
    $branchId = 1;
}

$isOwner = ($role === 'OWNER');
$isAdmin = in_array($role, ['OWNER', 'ADMIN'], true);

if (!table_exists_local($pdo, 'cases')) {
    http_response_code(500);
    exit('جدول القضايا غير موجود.');
}

$hasSecretCol = column_exists_local($pdo, 'cases', 'is_secret');

/* =========================
   Employees list
========================= */
$employees = [];
if (table_exists_local($pdo, 'employees')) {
    try {
        $nameExpr = column_exists_local($pdo, 'employees', 'full_name')
            ? 'full_name'
            : (column_exists_local($pdo, 'employees', 'name') ? 'name' : "''");

        if ($isAdmin) {
            $stEmp = $pdo->prepare("
                SELECT id, {$nameExpr} AS emp_name
                FROM employees
                WHERE branch_id = ?
                ORDER BY {$nameExpr} ASC, id DESC
            ");
            $stEmp->execute([$branchId]);
        } else {
            $stEmp = $pdo->prepare("
                SELECT id, {$nameExpr} AS emp_name
                FROM employees
                WHERE branch_id = ?
                ORDER BY {$nameExpr} ASC, id DESC
            ");
            $stEmp->execute([$branchId]);
        }

        $employees = $stEmp->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $employees = [];
    }
}

/* =========================
   Get case
========================= */
$selectSecret = $hasSecretCol ? ", COALESCE(is_secret,0) AS is_secret" : ", 0 AS is_secret";

if ($isAdmin) {
    $st = $pdo->prepare("
        SELECT
            id,
            branch_id,
            case_no,
            title,
            category,
            client_name,
            client_phone,
            client_email,
            lawyer_name,
            status,
            next_hearing_date,
            notes
            {$selectSecret}
        FROM cases
        WHERE id = ?
        LIMIT 1
    ");
    $st->execute([$id]);
} else {
    $st = $pdo->prepare("
        SELECT
            id,
            branch_id,
            case_no,
            title,
            category,
            client_name,
            client_phone,
            client_email,
            lawyer_name,
            status,
            next_hearing_date,
            notes
            {$selectSecret}
        FROM cases
        WHERE id = ?
          AND branch_id = ?
        LIMIT 1
    ");
    $st->execute([$id, $branchId]);
}

$case = $st->fetch(PDO::FETCH_ASSOC);

if (!$case) {
    header("Location: " . u('cases.php?e=not_found'));
    exit;
}

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

$hearingStatuses = [
    'SCHEDULED'      => 'مجدولة',
    'DONE'           => 'تمت',
    'POSTPONED'      => 'مؤجلة',
    'CANCELLED'      => 'ملغاة',
    'PENDING_RESULT' => 'بانتظار النتيجة',
];

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

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

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

$hearingForm = [
    'branch_id'           => (string)$branchId,
    'responsible_user_id' => '',
    'court_name'          => '',
    'session_type'        => '',
    'session_date'        => date('Y-m-d'),
    'session_time'        => '',
    'status'              => 'SCHEDULED',
    'notes'               => '',
];
/* =========================
   Save hearing from case edit
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['form_type'] ?? '') === 'add_case_session') {

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

    if (
        (int)$hearingForm['branch_id'] <= 0 ||
        (int)$hearingForm['responsible_user_id'] <= 0 ||
        $hearingForm['court_name'] === '' ||
        $hearingForm['session_date'] === ''
    ) {
        $hearingErr = 'يرجى إدخال الفرع والموظف المسؤول والمحكمة وتاريخ الجلسة.';
    } else {
        try {
            $status = strtoupper($hearingForm['status']);

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

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

$st->execute([
    ':case_id'             => (int)$case['id'],
    ':branch_id'           => (int)$hearingForm['branch_id'],
    ':client_name'         => trim((string)($hearingForm['client_name'] ?? ($case['client_name'] ?? ''))),
    ':session_date'        => $hearingForm['session_date'],
    ':session_time'        => $hearingForm['session_time'] !== '' ? $hearingForm['session_time'] : null,
    ':session_type'        => $hearingForm['session_type'] !== '' ? $hearingForm['session_type'] : null,
    ':court_name'          => $hearingForm['court_name'],
    ':status'              => $status,
    ':client_name' => trim((string)($hearingForm['client_name'] ?? ($case['client_name'] ?? ''))),
    ':notes'               => $hearingForm['notes'] !== '' ? $hearingForm['notes'] : null,
    ':added_by_user_id'    => $currentUid > 0 ? $currentUid : null,
    ':responsible_user_id' => (int)$hearingForm['responsible_user_id'],
]);
            $sessionId = (int)$pdo->lastInsertId();

            activity_log(
                $pdo,
                'create_hearing',
                'hearings',
                'hearing',
                $sessionId,
                'تم إضافة جلسة للقضية رقم: ' . (string)$case['case_no'],
                'إضافة جلسة',
                '⚖️',
                '#06b6d4'
            );

            if (function_exists('log_employee_achievement')) {
                log_employee_achievement(
                    $pdo,
                    'إضافة جلسة',
                    'تم إضافة جلسة للقضية رقم: ' . (string)$case['case_no'] . ' | المحكمة: ' . $hearingForm['court_name']
                );
            }

            header("Location: " . u('case_edit.php?id=' . (int)$case['id'] . '&session_added=1#sessionsBox'));
            exit;

        } catch (Throwable $e) {
            $hearingErr = 'فشل حفظ الجلسة: ' . $e->getMessage();
        }
    }
}
/* =========================
   Save case only
========================= */
$err = '';
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['form_type'] ?? '') === 'case_edit') {
    $oldCaseNo      = trim((string)($case['case_no'] ?? ''));
    $oldTitle       = trim((string)($case['title'] ?? ''));
    $oldClientName  = trim((string)($case['client_name'] ?? ''));
    $oldClientPhone = trim((string)($case['client_phone'] ?? ''));
    $oldClientEmail = trim((string)($case['client_email'] ?? ''));
    $oldLawyerName  = trim((string)($case['lawyer_name'] ?? ''));
    $oldStatus      = strtoupper(trim((string)($case['status'] ?? 'WORK')));
    $oldNextDate    = trim((string)($case['next_hearing_date'] ?? ''));
    $oldNotes       = trim((string)($case['notes'] ?? ''));
    $oldIsSecret    = !empty($case['is_secret']) ? 1 : 0;

    $case_no      = trim((string)($_POST['case_no'] ?? ''));
    $title        = trim((string)($_POST['title'] ?? ''));
    $client_name  = trim((string)($_POST['client_name'] ?? ''));
    $client_phone = trim((string)($_POST['client_phone'] ?? ''));
    $client_email = trim((string)($_POST['client_email'] ?? ''));
    $lawyer_name  = trim((string)($_POST['lawyer_name'] ?? ''));
    $status       = strtoupper(trim((string)($_POST['status'] ?? 'WORK')));
    $next_date_in = trim((string)($_POST['next_hearing_date'] ?? ''));
    $notes        = trim((string)($_POST['notes'] ?? ''));
    $is_secret    = ($hasSecretCol && $isOwner && isset($_POST['is_secret']) && (string)$_POST['is_secret'] === '1') ? 1 : 0;

    if ($client_phone !== '') {
        $client_phone = preg_replace('~[^0-9+\s()\-\x{0660}-\x{0669}]~u', '', $client_phone) ?: '';
        $client_phone = trim($client_phone);
    }

    if ($client_email !== '') {
        $client_email = filter_var($client_email, FILTER_VALIDATE_EMAIL) ? $client_email : '';
    }

    $allowedStatus = ['NEW', 'WORK', 'COURT', 'CLOSED'];
    if (!in_array($status, $allowedStatus, true)) {
        $status = 'WORK';
    }

    $next = valid_ymd_or_null($next_date_in);

    if ($next_date_in !== '' && $next === null) {
        $err = 'تاريخ الجلسة القادمة غير صحيح.';
    } elseif ($case_no === '' || $title === '') {
        $err = 'رقم القضية ونوع القضية مطلوبان.';
    } else {
        $hasChanges =
            $oldCaseNo      !== $case_no ||
            $oldTitle       !== $title ||
            $oldClientName  !== $client_name ||
            $oldClientPhone !== $client_phone ||
            $oldClientEmail !== $client_email ||
            $oldLawyerName  !== $lawyer_name ||
            $oldStatus      !== $status ||
            $oldNextDate    !== (string)($next ?? '') ||
            $oldNotes       !== $notes ||
            $oldIsSecret    !== $is_secret;

        if (!$hasChanges) {
            $msg = 'لم يتم العثور على أي تغييرات جديدة للحفظ.';
        } else {
            try {
                if ($hasSecretCol && $isOwner) {
                    $upd = $pdo->prepare("
                        UPDATE cases
                        SET case_no = ?,
                            title = ?,
                            client_name = ?,
                            client_phone = ?,
                            client_email = ?,
                            lawyer_name = ?,
                            status = ?,
                            next_hearing_date = ?,
                            notes = ?,
                            is_secret = ?
                        WHERE id = ?
                        LIMIT 1
                    ");

                    $upd->execute([
                        $case_no,
                        $title,
                        ($client_name !== '' ? $client_name : null),
                        ($client_phone !== '' ? $client_phone : null),
                        ($client_email !== '' ? $client_email : null),
                        ($lawyer_name !== '' ? $lawyer_name : null),
                        $status,
                        $next,
                        ($notes !== '' ? $notes : null),
                        $is_secret,
                        (int)$case['id'],
                    ]);
                } else {
                    $upd = $pdo->prepare("
                        UPDATE cases
                        SET case_no = ?,
                            title = ?,
                            client_name = ?,
                            client_phone = ?,
                            client_email = ?,
                            lawyer_name = ?,
                            status = ?,
                            next_hearing_date = ?,
                            notes = ?
                        WHERE id = ?
                        LIMIT 1
                    ");

                    $upd->execute([
                        $case_no,
                        $title,
                        ($client_name !== '' ? $client_name : null),
                        ($client_phone !== '' ? $client_phone : null),
                        ($client_email !== '' ? $client_email : null),
                        ($lawyer_name !== '' ? $lawyer_name : null),
                        $status,
                        $next,
                        ($notes !== '' ? $notes : null),
                        (int)$case['id'],
                    ]);
                }

                notify_all_users_case_update_local(
                    $pdo,
                    (int)$case['id'],
                    $case_no,
                    $title,
                    $currentName
                );

                if (function_exists('log_employee_achievement')) {
                    log_employee_achievement(
                        $pdo,
                        'تعديل قضية',
                        'تم تعديل القضية رقم: ' . $case_no . ' | نوع القضية: ' . $title
                    );
                }

                $msg = 'تم حفظ التعديلات بنجاح.';
            } catch (Throwable $e) {
                $err = 'حدث خطأ أثناء حفظ التعديلات.';
            }
        }
    }
activity_log(
    $pdo,
    'update_case',
    'cases',
    'case',
    (int)$case['id'],
    'تم تعديل القضية رقم: ' . $case_no . ' | نوع القضية: ' . $title,
    'تعديل قضية',
    '⚖️',
    '#f59e0b'
);
    $selectSecret2 = $hasSecretCol ? ", COALESCE(is_secret,0) AS is_secret" : ", 0 AS is_secret";
    $st2 = $pdo->prepare("
        SELECT
            id,
            branch_id,
            case_no,
            title,
            category,
            client_name,
            client_phone,
            client_email,
            lawyer_name,
            status,
            next_hearing_date,
            notes
            {$selectSecret2}
        FROM cases
        WHERE id = ?
        LIMIT 1
    ");
    $st2->execute([(int)$case['id']]);
    $case = $st2->fetch(PDO::FETCH_ASSOC) ?: $case;

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

/* =========================
   Get sessions
========================= */
$hasSessionsTable = table_exists_local($pdo, 'case_sessions');
$caseSessions = [];

if ($hasSessionsTable) {
    try {
        $stSessions = $pdo->prepare("
            SELECT
                id,
                session_date,
                session_time,
                session_type,
                court_name,
                location,
                status,
                notes,
                created_at
            FROM case_sessions
            WHERE case_id = ?
            ORDER BY session_date DESC, session_time DESC, id DESC
        ");
        $stSessions->execute([(int)$case['id']]);
        $caseSessions = $stSessions->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $caseSessions = [];
    }
}

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);
    --warning:#fbbf24;
    --warning-soft:rgba(251,191,36,.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-edit-page{ color:var(--text); }
  .case-edit-page *{ box-sizing:border-box; }

 .case-edit-page .wrap{
  width:100%;
  max-width:100%;
  margin:0;
  padding:18px 24px;
}
  .case-edit-page .page-head{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:14px;
  }

  .case-edit-page .pageTitle{
    margin:0;
    font-size:28px;
    font-weight:900;
    color:#ffffff;
    line-height:1.1;
  }

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

  .case-edit-page .actions{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
  }

  .case-edit-page .btn,
  .case-edit-page .btnPrimary{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:42px;
    padding:0 14px;
    border-radius:999px;
    font-weight:900;
    text-decoration:none;
    cursor:pointer;
    font-family:inherit;
    transition:.18s ease;
  }

  .case-edit-page .btn{
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
  }

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

  .case-edit-page .btnPrimary{
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#0b1b1f;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
  }

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

  .case-edit-page .card,
  .case-edit-page .sessionsBox{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    padding:14px;
    box-shadow:var(--shadow);
    backdrop-filter:blur(12px);
  }

  .case-edit-page .sessionsBox{ margin-top:16px; }

  .case-edit-page .sectionTitle{
    margin:0 0 12px;
    font-size:20px;
    font-weight:900;
    color:#fff;
  }

  .case-edit-page .grid,
  .case-edit-page .sessionsGrid{
    display:grid;
    grid-template-columns:repeat(3,minmax(0,1fr));
    gap:12px;
  }

  .case-edit-page .span-3{ grid-column:1 / -1; }

  .case-edit-page label{
    display:block;
    font-weight:900;
    margin-bottom:6px;
    color:#ffffff;
  }

  .case-edit-page input,
  .case-edit-page select,
  .case-edit-page textarea{
    width:100%;
    border:1px solid var(--line);
    border-radius:14px;
    padding:12px;
    font-family:inherit;
    font-size:14px;
    color:#fff;
    background:rgba(255,255,255,.05);
    transition:all .2s ease;
    -webkit-text-fill-color:#fff;
    box-shadow:none;
  }

  .case-edit-page input::placeholder,
  .case-edit-page textarea::placeholder{
    color:rgba(255,255,255,.45);
  }

  .case-edit-page select option{
    background:#0b1f26;
    color:#fff;
  }

  .case-edit-page input,
  .case-edit-page select{
    height:44px;
  }

  .case-edit-page textarea{
    min-height:140px;
    resize:vertical;
    line-height:1.8;
    caret-color:#fff;
  }

  .case-edit-page input:focus,
  .case-edit-page select:focus,
  .case-edit-page textarea:focus{
    outline:none;
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
    background:rgba(255,255,255,.06);
  }

  .case-edit-page .msg{
    margin:10px 0;
    padding:10px 12px;
    border-radius:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
  }

  .case-edit-page .msg.ok{
    border-color:rgba(52,211,153,.24);
    background:rgba(6,95,70,.18);
    color:#d1fae5;
  }

  .case-edit-page .msg.err{
    border-color:rgba(248,113,113,.24);
    background:rgba(127,29,29,.18);
    color:#fecaca;
  }

  .case-edit-page .secretBox{
    display:flex;
    align-items:center;
    gap:10px;
    flex-wrap:wrap;
    padding:14px 16px;
    border:1px solid rgba(248,113,113,.22);
    background:rgba(127,29,29,.14);
    border-radius:16px;
  }

  .case-edit-page .secretBox input[type="checkbox"]{
    width:18px;
    height:18px;
    accent-color:#b91c1c;
  }

  .case-edit-page .secretTitle{
    font-weight:900;
    color:#fecaca;
  }

  .case-edit-page .secretHint{
    width:100%;
    color:#fecaca;
    font-size:13px;
    line-height:1.8;
  }

  .case-edit-page .sessionTableWrap{
    margin-top:14px;
    overflow:auto;
    border:1px solid var(--line);
    border-radius:14px;
    background:rgba(255,255,255,.03);
  }

  .case-edit-page .sessionTable{
    width:100%;
    border-collapse:collapse;
    min-width:900px;
  }

  .case-edit-page .sessionTable th,
  .case-edit-page .sessionTable td{
    padding:12px 10px;
    border-bottom:1px solid var(--line);
    text-align:right;
    white-space:nowrap;
  }

  .case-edit-page .sessionTable th{
    background:rgba(255,255,255,.04);
    font-weight:900;
    color:rgba(255,255,255,.72);
    font-size:13px;
  }

  .case-edit-page .sessionTable td{
    font-size:13px;
    color:#fff;
  }

  .case-edit-page .pill{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 10px;
    border-radius:999px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    font-weight:900;
    font-size:12px;
  }

  .case-edit-page .pill.scheduled{
    background:var(--blue-soft);
    border-color:rgba(96,165,250,.18);
    color:var(--blue);
  }

  .case-edit-page .pill.done{
    background:var(--success-soft);
    border-color:rgba(52,211,153,.18);
    color:var(--success);
  }

  .case-edit-page .pill.postponed{
    background:var(--warning-soft);
    border-color:rgba(251,191,36,.20);
    color:var(--warning);
  }

  .case-edit-page .pill.cancelled{
    background:var(--danger-soft);
    border-color:rgba(248,113,113,.20);
    color:var(--danger);
  }

  .case-edit-page .emptyBox{
    padding:16px;
    text-align:center;
    color:var(--muted);
    border:1px dashed rgba(255,255,255,.16);
    border-radius:14px;
    background:rgba(255,255,255,.03);
  }

  @media (max-width:980px){
    .case-edit-page .grid,
    .case-edit-page .sessionsGrid{
      grid-template-columns:repeat(2,1fr);
    }
    .case-edit-page .span-3{ grid-column:1/-1; }
  }

  @media (max-width:640px){
    .case-edit-page .grid,
    .case-edit-page .sessionsGrid{
      grid-template-columns:1fr;
    }
    .case-edit-page .span-3{ grid-column:1/-1; }
    .case-edit-page .pageTitle{ font-size:24px; }
    .case-edit-page .wrap{ padding:14px; }
  }
  /* إصلاح انكماش صفحة تعديل القضية */
.layout-content,
.layout-main,
.main-content,
.page-content,
.app-content,
.content,
.content-area{
  width:100% !important;
  max-width:none !important;
}

.case-edit-page{
  width:100% !important;
  max-width:none !important;
}

.case-edit-page .wrap{
  width:100% !important;
  max-width:none !important;
  margin:0 !important;
  padding:18px 24px !important;
}

.case-edit-page .card,
.case-edit-page .sessionsBox{
  width:100% !important;
  max-width:none !important;
}

.case-edit-page .grid{
  grid-template-columns:repeat(4,minmax(0,1fr)) !important;
}

.case-edit-page .span-3{
  grid-column:1 / -1 !important;
}

@media(max-width:1100px){
  .case-edit-page .grid{
    grid-template-columns:repeat(2,minmax(0,1fr)) !important;
  }
}

@media(max-width:700px){
  .case-edit-page .grid{
    grid-template-columns:1fr !important;
  }
}
.case-edit-page .btn,
.case-edit-page .btnPrimary{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  height:42px;
  padding:0 14px;
}
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}}
.case-edit-page input[name="client_name"]{
  background:rgba(255,255,255,.08) !important;
  color:#fff !important;
  -webkit-text-fill-color:#fff !important;
  border:1px solid rgba(212,175,55,.35) !important;
}

.case-edit-page input[name="client_name"]::placeholder{
  color:rgba(255,255,255,.55) !important;
}

.case-edit-page input[name="client_name"]:focus{
  background:rgba(255,255,255,.12) !important;
  color:#fff !important;
  -webkit-text-fill-color:#000 !important;
}
.case-edit-page input[name="court_name"]{
  background:rgba(255,255,255,.08) !important;
  color:#fff !important;
  -webkit-text-fill-color:#000 !important;
  border:1px solid rgba(212,175,55,.35) !important;
}

.case-edit-page input[name="court_name"]::placeholder{
  color:rgba(255,255,255,.55) !important;
}

.case-edit-page input[name="court_name"]:focus{
  background:rgba(255,255,255,.12) !important;
  color:#fff !important;
}
#sessionsBox input,
#sessionsBox select,
#sessionsBox textarea,
#sessionsBox .hlg-session-input{
  background:#07171d !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
  opacity:1 !important;
  caret-color:#ffffff !important;
  border:1px solid rgba(212,175,55,.55) !important;
  box-shadow:none !important;
}

#sessionsBox input:focus,
#sessionsBox select:focus,
#sessionsBox textarea:focus,
#sessionsBox .hlg-session-input:focus{
  background:#07171d !important;
  color:#ffffff !important;
  -webkit-text-fill-color:#ffffff !important;
  border-color:#d4af37 !important;
  box-shadow:0 0 0 2px rgba(212,175,55,.35) !important;
}

#sessionsBox input::placeholder,
#sessionsBox textarea::placeholder{
  color:rgba(255,255,255,.65) !important;
  -webkit-text-fill-color:rgba(255,255,255,.65) !important;
}

/* حل مشكلة Chrome autofill */
#sessionsBox input:-webkit-autofill,
#sessionsBox input:-webkit-autofill:hover,
#sessionsBox input:-webkit-autofill:focus,
#sessionsBox textarea:-webkit-autofill,
#sessionsBox select:-webkit-autofill{
  -webkit-box-shadow:0 0 0 1000px #07171d inset !important;
  -webkit-text-fill-color:#ffffff !important;
  caret-color:#ffffff !important;
}
.case-edit-page .pill.pending{
  background:rgba(212,175,55,.14);
  border-color:rgba(212,175,55,.35);
  color:#ffd76a;
}
</style>

<div class="case-edit-page">
  <div class="wrap">

    <div class="page-head">
      <div>
        <h1 class="pageTitle">تعديل قضية</h1>
        <div class="pageSub">
          رقم القضية: <?= h((string)($case['case_no'] ?? '')) ?> • الحالة الحالية: <?= h(status_ar((string)($case['status'] ?? 'WORK'))) ?>
        </div>
      </div>

      <div class="actions">
        <a class="btn" href="<?= h(u('cases.php')) ?>">رجوع</a>
        <a class="btn" href="<?= h(u('case_files.php?case_id=' . (int)($case['id'] ?? 0))) ?>">المستندات</a>
        <?php if ($hasSessionsTable): ?>
          <a class="btn" href="#sessionsBox">الجلسات</a>
        <?php endif; ?>
      </div>
    </div>

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

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

    <form id="caseEditForm" class="card" method="post" action="<?= h(u('case_edit.php?id=' . (int)$case['id'])) ?>">
      <input type="hidden" name="form_type" value="case_edit">

      <div class="grid">
        <div>
          <label>رقم القضية</label>
          <input name="case_no" value="<?= h((string)($case['case_no'] ?? '')) ?>" required>
        </div>

        <div>
          <label>نوع القضية</label>
          <input name="title" value="<?= h((string)($case['title'] ?? '')) ?>" required>
        </div>

        <div>
          <label>اسم العميل</label>
          <input name="client_name" value="<?= h((string)($case['client_name'] ?? '')) ?>">
        </div>

        <div>
          <label>رقم هاتف العميل</label>
          <input name="client_phone" value="<?= h((string)($case['client_phone'] ?? '')) ?>" placeholder="مثال: 05xxxxxxxx">
        </div>

        <div>
          <label>بريد العميل</label>
          <input type="email" name="client_email" value="<?= h((string)($case['client_email'] ?? '')) ?>" placeholder="example@domain.com">
        </div>

        <div>
          <label>الموظف المسؤول</label>
          <select name="lawyer_name">
            <option value="">اختر الموظف المسؤول</option>
            <?php foreach ($employees as $emp): ?>
              <?php $empName = trim((string)($emp['emp_name'] ?? '')); ?>
              <?php if ($empName === '') continue; ?>
              <option value="<?= h($empName) ?>" <?= ((string)($case['lawyer_name'] ?? '') === $empName) ? 'selected' : '' ?>>
                <?= h($empName) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>الحالة</label>
          <?php $cur = strtoupper((string)($case['status'] ?? 'WORK')); ?>
          <select name="status">
            <?php
              $opts = [
                'NEW'    => 'جديدة',
                'WORK'   => 'قيد العمل',
                'COURT'  => 'في المحكمة',
                'CLOSED' => 'مغلقة'
              ];
              foreach ($opts as $k => $v):
            ?>
              <option value="<?= h($k) ?>" <?= $cur === $k ? 'selected' : '' ?>><?= h($v) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>الجلسة القادمة (اختياري)</label>
          <input type="date" name="next_hearing_date" value="<?= h((string)($case['next_hearing_date'] ?? '')) ?>">
        </div>

        <?php if ($hasSecretCol && $isOwner): ?>
          <div class="span-3">
            <label>إعدادات السرية</label>
            <label class="secretBox">
              <input type="checkbox" name="is_secret" value="1" <?= !empty($case['is_secret']) ? 'checked' : '' ?>>
              <span class="secretTitle">قضية سرية</span>
              <div class="secretHint">هذه القضية لا يمكن فتحها أو مشاهدتها إلا من حساب الـ OWNER فقط.</div>
            </label>
          </div>
        <?php endif; ?>

        <div class="span-3">
          <label for="case_notes">الملاحظات (داخلية)</label>
          <textarea id="case_notes" name="notes" placeholder="اكتب الملاحظات هنا..."><?= h((string)($case['notes'] ?? '')) ?></textarea>
        </div>
      </div>

      <div style="margin-top:14px;display:flex;gap:8px;flex-wrap:wrap">
        <button class="btnPrimary" type="submit" form="caseEditForm">حفظ التعديلات</button>
      </div>
    </form>

 <?php if ($hasSessionsTable): ?>
  <div id="sessionsBox" class="sessionsBox">
    <h2 class="sectionTitle">جلسات القضية</h2>

    <form method="post" action="<?= h(u('case_edit.php?id=' . (int)$case['id'] . '#sessionsBox')) ?>">
      <input type="hidden" name="form_type" value="add_case_session">

      <?php if (!empty($hearingErr)): ?>
        <div class="msg err"><?= h($hearingErr) ?></div>
      <?php endif; ?>

      <?php if (isset($_GET['session_added'])): ?>
        <div class="msg ok">تمت إضافة الجلسة بنجاح</div>
      <?php endif; ?>

      <div class="sessionsGrid">

        <div>
          <label>الفرع</label>
          <select name="branch_id" required>
            <option value="">اختر الفرع</option>
            <?php foreach ($branches as $b): ?>
              <option value="<?= (int)$b['id'] ?>" <?= (int)$hearingForm['branch_id'] === (int)$b['id'] ? 'selected' : '' ?>>
                <?= h($b['name_ar']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
<div>
  <label>العميل</label>
  <input
  class="hlg-session-input"
  name="client_name"
  value="<?= h($hearingForm['client_name'] ?? ($case['client_name'] ?? '')) ?>"
  placeholder="اسم العميل"
>
</div>
        <div>
          <label>الموظف المسؤول</label>
          <select name="responsible_user_id" required>
            <option value="">اختر الموظف</option>
            <?php foreach ($responsibleUsers as $u): ?>
              <option value="<?= (int)$u['id'] ?>" <?= (int)$hearingForm['responsible_user_id'] === (int)$u['id'] ? 'selected' : '' ?>>
                <?= h($u['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>المحكمة</label>
          <input
  class="hlg-session-input"
  name="court_name"
  required
  value="<?= h($hearingForm['court_name']) ?>"
  placeholder="اسم المحكمة"
>
        </div>

        <div>
          <label>نوع الجلسة</label>
          <select name="session_type">
            <option value="">اختر نوع الجلسة</option>
            <?php foreach ($hearingTypes as $t): ?>
              <option value="<?= h($t) ?>" <?= $hearingForm['session_type'] === $t ? 'selected' : '' ?>>
                <?= h($t) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>التاريخ</label>
          <input type="date" name="session_date" required value="<?= h($hearingForm['session_date']) ?>">
        </div>

        <div>
          <label>الوقت</label>
          <input type="time" name="session_time" value="<?= h($hearingForm['session_time']) ?>">
        </div>

        <div>
          <label>الحالة</label>
          <select name="status">
            <?php foreach ($hearingStatuses as $k => $v): ?>
              <option value="<?= h($k) ?>" <?= $hearingForm['status'] === $k ? 'selected' : '' ?>>
                <?= h($v) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="span-3">
          <label>ملاحظات</label>
          <textarea name="notes"><?= h($hearingForm['notes']) ?></textarea>
        </div>

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

      </div>
    </form>

    <div class="sessionTableWrap">
      <?php if (empty($caseSessions)): ?>
        <div class="emptyBox">لا توجد جلسات بعد</div>
      <?php else: ?>
        <table class="sessionTable">
          <thead>
            <tr>
              <th>التاريخ</th>
              <th>الوقت</th>
              <th>النوع</th>
              <th>المحكمة</th>
              <th>الموقع</th>
              <th>الحالة</th>
              <th>ملاحظات</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($caseSessions as $s): ?>
              <tr>
                <td><?= h((string)($s['session_date'] ?? '')) ?></td>
                <td><?= h((string)($s['session_time'] ?? '-')) ?></td>
                <td><?= h((string)($s['session_type'] ?? '-')) ?></td>
                <td><?= h((string)($s['court_name'] ?? '-')) ?></td>
                <td><?= h((string)($s['location'] ?? '-')) ?></td>
                <td>
                  <span class="pill <?= h(session_status_class((string)($s['status'] ?? 'SCHEDULED'))) ?>">
                    <?= h(session_status_ar((string)($s['status'] ?? 'SCHEDULED'))) ?>
                  </span>
                </td>
                <td><?= h((string)($s['notes'] ?? '-')) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  </div>
<?php else: ?>
  <div class="sessionsBox">
    <h2 class="sectionTitle">جلسات القضية</h2>
    <div class="emptyBox">جدول الجلسات غير موجود بعد. أنشئ جدول case_sessions أولاً ثم ستظهر هنا واجهة الجلسات.</div>
  </div>
<?php endif; ?>

  </div>
</div>

<?php render_layout_end(); ?>