<?php
declare(strict_types=1);

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

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/layout.php';
require_once __DIR__ . '/inc/notifications_helper.php';
require_once __DIR__ . '/inc/activity_log.php';

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

$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');
ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
error_reporting(E_ALL);

/* ===== PDO ===== */
$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    die('DB not ready');
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/* ===== Session ===== */
$userId   = (int)($_SESSION['user_id'] ?? 0);
$branchId = (int)($_SESSION['branch_id'] ?? 1);
$name     = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

$isAdmin = in_array($role, ['OWNER', 'ADMIN'], true);
$isOwner = ($role === 'OWNER');
/* ===== Helpers ===== */
if (!function_exists('h')) {
    function h($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('queue_case_email')) {
    function queue_case_email(PDO $pdo, int $caseId, string $to, string $caseNo, string $clientCode): bool
    {
        try {
            $caseId     = (int)$caseId;
            $to         = trim($to);
            $caseNo     = trim($caseNo);
            $clientCode = trim($clientCode);

            if ($caseId <= 0) {
                return false;
            }

            if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
                return false;
            }

            if ($caseNo === '') {
                return false;
            }

            $check = $pdo->prepare("
                SELECT id
                FROM case_email_queue
                WHERE case_id = ?
                  AND to_email = ?
                  AND status IN ('PENDING', 'PROCESSING')
                LIMIT 1
            ");
            $check->execute([$caseId, $to]);

            if ($check->fetch()) {
                return true;
            }

            $st = $pdo->prepare("
                INSERT INTO case_email_queue
                    (case_id, to_email, case_no, client_code, status, attempts, next_attempt_at, created_at)
                VALUES
                    (?, ?, ?, ?, 'PENDING', 0, NOW(), NOW())
            ");

            return $st->execute([
                $caseId,
                $to,
                $caseNo,
                $clientCode
            ]);
        } catch (Throwable $e) {
            error_log('QUEUE CASE EMAIL ERROR: ' . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('generate_case_code')) {
    function generate_case_code(PDO $pdo, int $len = 10): string
    {
        $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';

        while (true) {
            $code = '';
            for ($i = 0; $i < $len; $i++) {
                $code .= $alphabet[random_int(0, strlen($alphabet) - 1)];
            }

            $st = $pdo->prepare("SELECT 1 FROM cases WHERE client_access_code = ? LIMIT 1");
            $st->execute([$code]);
            if (!$st->fetchColumn()) {
                return $code;
            }
        }
    }
}

if (!function_exists('mime_from_ext')) {
    function mime_from_ext(string $ext): string
    {
        $ext = strtolower($ext);

        return match ($ext) {
            'pdf'  => 'application/pdf',
            'png'  => 'image/png',
            'jpg', 'jpeg' => 'image/jpeg',
            'doc'  => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'xls'  => 'application/vnd.ms-excel',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            default => 'application/octet-stream',
        };
    }
}

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

if (!function_exists('notify_all_users_case_add_local')) {
    function notify_all_users_case_add_local(
        PDO $pdo,
        int $caseId,
        string $caseNo,
        string $caseTitle,
        string $addedByName
    ): void {
        if (!function_exists('notify_user_local')) {
            return;
        }

        $check = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = 'notifications'
        ");
        $check->execute();

        if ((int)$check->fetchColumn() <= 0) {
            return;
        }

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

        $title = 'إضافة قضية جديدة';
        $message = "تمت إضافة القضية رقم {$caseNo} - {$caseTitle} بواسطة {$addedByName}";

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

/* ===== Lock staff branch ===== */
if (!$isAdmin) {
    try {
        $st = $pdo->prepare("SELECT branch_id FROM employees WHERE user_id = ? ORDER BY id DESC LIMIT 1");
        $st->execute([$userId]);
        $realBranch = (int)($st->fetchColumn() ?: 0);

        if ($realBranch > 0) {
            $branchId = $realBranch;
            $_SESSION['branch_id'] = $realBranch;
        }
    } catch (Throwable $e) {
    }
}

$canSwitchBranch = $isAdmin;

/* ===== Branch name ===== */
$currentBranchName = '—';
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 => 'أبوظبي',
    };
}

/* ===== Prefill client from GET ===== */
$prefillClientId = (int)($_GET['client_id'] ?? 0);
$prefillClient   = null;

if ($prefillClientId > 0) {
    try {
        if ($isAdmin) {
            $stPrefill = $pdo->prepare("
                SELECT id, name, phone, email, notes, branch_id
                FROM clients
                WHERE id = ?
                LIMIT 1
            ");
            $stPrefill->execute([$prefillClientId]);
        } else {
            $stPrefill = $pdo->prepare("
                SELECT id, name, phone, email, notes, branch_id
                FROM clients
                WHERE id = ? AND branch_id = ?
                LIMIT 1
            ");
            $stPrefill->execute([$prefillClientId, $branchId]);
        }

        $prefillClient = $stPrefill->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (Throwable $e) {
        $prefillClient = null;
    }
}

/* ===== Clients list ===== */
$clients = [];
try {
    if ($isAdmin) {
        $stClients = $pdo->query("
            SELECT id, name, phone, email
            FROM clients
            ORDER BY name ASC, id DESC
        ");
    } else {
        $stClients = $pdo->prepare("
            SELECT id, name, phone, email
            FROM clients
            WHERE branch_id = ?
            ORDER BY name ASC, id DESC
        ");
        $stClients->execute([$branchId]);
    }
    $clients = $stClients->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $clients = [];
}

/* ===== UI vars ===== */
$errMsg = '';
$okMsg = '';
$clientCode = '';
$clientLink = '';
$eFlag = (string)($_GET['e'] ?? '');

/* ===== Old values ===== */
$oldCaseNo          = (string)($_POST['case_no'] ?? '');
$oldTitle           = (string)($_POST['title'] ?? '');
$oldClientId        = (int)($_POST['client_id'] ?? ($prefillClient['id'] ?? 0));
$oldClientSearch    = (string)($_POST['client_search'] ?? ($prefillClient['name'] ?? ''));
$oldClientPhone     = (string)($_POST['client_phone'] ?? ($prefillClient['phone'] ?? ''));
$oldClientEmail     = (string)($_POST['client_email'] ?? ($prefillClient['email'] ?? ''));
$oldClientNotes     = (string)($_POST['client_notes'] ?? ($prefillClient['notes'] ?? ''));
$oldLawyerName      = (string)($_POST['lawyer_name'] ?? '');
$oldStatus          = strtoupper((string)($_POST['status'] ?? 'NEW'));
$oldNextHearingDate = (string)($_POST['next_hearing_date'] ?? '');
$oldNotes           = (string)($_POST['notes'] ?? '');
$oldIsSecret        = !empty($_POST['is_secret']);

/* ===== POST ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $case_no      = trim((string)($_POST['case_no'] ?? ''));
    $title        = trim((string)($_POST['title'] ?? ''));
    $clientId     = (int)($_POST['client_id'] ?? 0);
$clientSearch = trim((string)($_POST['client_search'] ?? ''));
$clientSearch = preg_replace('/\s+/u', ' ', $clientSearch);
    $client_phone = trim((string)($_POST['client_phone'] ?? ''));
    $client_email = trim((string)($_POST['client_email'] ?? ''));
    $client_notes = trim((string)($_POST['client_notes'] ?? ''));
    $lawyer       = trim((string)($_POST['lawyer_name'] ?? ''));
    $status       = strtoupper(trim((string)($_POST['status'] ?? 'NEW')));
    $next_date    = trim((string)($_POST['next_hearing_date'] ?? ''));
    $notes        = trim((string)($_POST['notes'] ?? ''));
    $isSecret     = (isset($_POST['is_secret']) && (string)$_POST['is_secret'] === '1') ? 1 : 0;

    $case_no = preg_replace('/\s+/u', ' ', $case_no);
    $case_no = trim((string)$case_no);

    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 !== '' && !filter_var($client_email, FILTER_VALIDATE_EMAIL)) {
        $client_email = '';
    }

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

    $next = valid_ymd_or_null($next_date);

    if ($case_no === '' || $title === '' || trim((string)($_POST['client_search'] ?? '')) === '') {
    $errMsg = 'يرجى إدخال رقم القضية ونوع القضية واسم العميل.';
}
    elseif ($next_date !== '' && $next === null) {
        $errMsg = 'تاريخ الجلسة القادمة غير صحيح.';
    } else {
        try {
            $pdo->beginTransaction();

            $stDup = $pdo->prepare("
                SELECT id
                FROM cases
                WHERE case_no = ?
                LIMIT 1
            ");
            $stDup->execute([$case_no]);
            $dupId = (int)($stDup->fetchColumn() ?: 0);

            if ($dupId > 0) {
                $pdo->rollBack();
                $errMsg = 'لا يمكن إضافة القضية لأن رقم القضية مكرر مسبقًا.';
            } else {
                $clientName = $clientSearch !== '' ? $clientSearch : null;

                if ($clientId > 0) {
                    if ($isAdmin) {
                        $stClient = $pdo->prepare("
                            SELECT id, name, phone, email
                            FROM clients
                            WHERE id = ?
                            LIMIT 1
                        ");
                        $stClient->execute([$clientId]);
                    } else {
                        $stClient = $pdo->prepare("
                            SELECT id, name, phone, email
                            FROM clients
                            WHERE id = ? AND branch_id = ?
                            LIMIT 1
                        ");
                        $stClient->execute([$clientId, $branchId]);
                    }

                    $clientRow = $stClient->fetch();

                    if (!$clientRow) {
                        $pdo->rollBack();
                        $errMsg = 'العميل المختار غير صالح أو لا يتبع لفرعك.';
                    } else {
                        $clientName = trim((string)($clientRow['name'] ?? ''));
                        if ($client_phone === '') {
                            $client_phone = trim((string)($clientRow['phone'] ?? ''));
                        }
                        if ($client_email === '') {
                            $client_email = trim((string)($clientRow['email'] ?? ''));
                        }
                    }
                }

                if ($errMsg === '') {
                    $clientCode = generate_case_code($pdo, 10);

                    $ins = $pdo->prepare("
                        INSERT INTO cases
                        (
                            branch_id,
                            case_no,
                            title,
                            client_id,
                            client_name,
                            client_phone,
                            client_email,
                            lawyer_name,
                            status,
                            next_hearing_date,
                            notes,
                            client_notes,
                            client_access_code,
                            created_by,
                            is_secret
                        )
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    $ins->execute([
                        $branchId,
                        $case_no,
                        $title,
                        ($clientId > 0 ? $clientId : null),
                        ($clientName !== '' ? $clientName : null),
                        ($client_phone !== '' ? $client_phone : null),
                        ($client_email !== '' ? $client_email : null),
                        ($lawyer !== '' ? $lawyer : null),
                        $status,
                        $next,
                        ($notes !== '' ? $notes : null),
                        ($client_notes !== '' ? $client_notes : null),
                        $clientCode,
                        ($userId > 0 ? $userId : null),
                        $isSecret,
                    ]);

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

activity_log(
    $pdo,
    'create_case',
    'cases',
    'case',
    $caseId,
    'تمت إضافة القضية رقم ' . $case_no . ' - ' . $title,
    'إضافة قضية جديدة',
    '⚖️',
    '#22c55e'
);

if (!empty($_FILES['attachments']) && is_array($_FILES['attachments']['name'])) {
    $allowedExt = ['pdf', 'png', 'jpg', 'jpeg', 'doc', 'docx', 'xlsx', 'xls'];
    $uploadDir  = __DIR__ . '/uploads/cases/';

    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0755, true);
    }

    $names = $_FILES['attachments']['name'];
    $tmps  = $_FILES['attachments']['tmp_name'];
    $errs  = $_FILES['attachments']['error'];
    $sizes = $_FILES['attachments']['size'];

    $count = count($names);

    for ($i = 0; $i < $count; $i++) {
        if (($names[$i] ?? '') === '') {
            continue;
        }

        if (($errs[$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            continue;
        }

        $origName = (string)$names[$i];
        $tmp      = (string)($tmps[$i] ?? '');
        $size     = (int)($sizes[$i] ?? 0);

        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));

        if (!in_array($ext, $allowedExt, true)) {
            continue;
        }

        if ($size <= 0 || $size > 10 * 1024 * 1024) {
            continue;
        }

        if ($tmp === '' || !is_uploaded_file($tmp)) {
            continue;
        }

        $stored = "case{$caseId}_" . date('Ymd_His') . "_" . bin2hex(random_bytes(6)) . ".{$ext}";
        $fullPath = $uploadDir . $stored;

        if (!move_uploaded_file($tmp, $fullPath)) {
            continue;
        }

        $relPath = "uploads/cases/" . $stored;

        $stF = $pdo->prepare("
            INSERT INTO case_files
            (
                case_id,
                branch_id,
                file_name,
                file_path,
                file_type,
                file_size,
                uploaded_by
            )
            VALUES
            (
                :case_id,
                :branch_id,
                :file_name,
                :file_path,
                :file_type,
                :file_size,
                :uploaded_by
            )
        ");

        $stF->execute([
            'case_id'     => $caseId,
            'branch_id'   => $branchId,
            'file_name'   => $origName,
            'file_path'   => $relPath,
            'file_type'   => mime_from_ext($ext),
            'file_size'   => $size,
            'uploaded_by' => ($userId > 0 ? $userId : null),
        ]);
    }
}

                    /* تسجيل إنجاز الموظف تلقائياً */
                    try {
                        if (function_exists('log_employee_achievement')) {
                            log_employee_achievement(
                                $pdo,
                                'إضافة قضية جديدة',
                                'تمت إضافة القضية رقم ' . $case_no . ' - ' . $title
                            );
                        } else {
                            error_log('log_employee_achievement function not found');
                        }
                    } catch (Throwable $e) {
                        error_log('LOG EMPLOYEE ACHIEVEMENT ERROR: ' . $e->getMessage());
                    }

                    $pdo->commit();

                    $clientLink = rtrim(u('case_public.php'), '/') . '?code=' . urlencode($clientCode);

                    try {
                        notify_all_users_case_add_local($pdo, $caseId, $case_no, $title, $name);
                    } catch (Throwable $e) {
                        error_log('NOTIFY ALL USERS ERROR: ' . $e->getMessage());
                    }

                    if ($client_email !== '') {
                        $queued = queue_case_email($pdo, $caseId, $client_email, $case_no, $clientCode);
                        if (!$queued) {
                            $errMsg = $debug
                                ? 'تم حفظ القضية لكن فشل إدراج البريد في الطابور.'
                                : 'تم حفظ القضية، لكن تعذّر إدراج البريد في قائمة الإرسال.';
                        } else {
                            $okMsg = 'تم حفظ القضية وإضافة الإشعار وإدراج البريد في قائمة الإرسال.';
                        }
                    } else {
                        $okMsg = 'تم حفظ القضية وإضافة الإشعار بنجاح.';
                    }

                    $_POST = [];
                    $oldCaseNo = $oldTitle = $oldClientSearch = $oldClientPhone = $oldClientEmail = $oldClientNotes = $oldLawyerName = $oldNextHearingDate = $oldNotes = '';
                    $oldClientId = 0;
                    $oldStatus = 'NEW';
                    $oldIsSecret = false;
                }
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            if ((int)$e->getCode() === 23000 || str_contains($e->getMessage(), '1062')) {
                $errMsg = 'لا يمكن إضافة القضية لأن رقم القضية مكرر مسبقًا.';
            } else {
                $errMsg = $debug ? ('خطأ: ' . $e->getMessage()) : 'حدث خطأ أثناء حفظ القضية. حاول مرة أخرى.';
            }

            $clientCode = '';
            $clientLink = '';
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            $errMsg = $debug ? ('خطأ: ' . $e->getMessage()) : 'حدث خطأ أثناء حفظ القضية. حاول مرة أخرى.';
            $clientCode = '';
            $clientLink = '';
        }
    }
}

/* ===== Employees list حسب الفرع ===== */
$employees = [];

try {
    $stEmployees = $pdo->prepare("
        SELECT id, full_name, name
        FROM employees
        WHERE branch_id = ?
        ORDER BY COALESCE(full_name, name) ASC, id DESC
    ");
    $stEmployees->execute([$branchId]);
    $employees = $stEmployees->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $employees = [];
}

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);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --danger:#f87171;
    --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-add-page{
    color:var(--text);
    padding-bottom:30px;
    width:100%;
    max-width:100%;
  }

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

  .case-add-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;
    backdrop-filter:blur(12px);
  }

  .case-add-page .page-head{
    max-width:1100px;
    margin:18px auto 14px;
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
    padding:0 8px;
  }

  .case-add-page .titleWrap{
    display:flex;
    flex-direction:column;
    gap:4px;
  }

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

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

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

  .case-add-page .btnLink{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    height:42px;
    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;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
  }

  .case-add-page .box{
    width:100%;
    max-width:1100px;
    margin:0 auto;
    padding:0 8px;
  }

  .case-add-page .formGrid{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:24px;
    box-shadow:var(--shadow);
    padding:24px;
    backdrop-filter:blur(10px);
  }

  .case-add-page .err{
    margin-bottom:12px;
    color:#fecaca;
    font-size:13px;
    background:rgba(127,29,29,.18);
    border:1px solid rgba(248,113,113,.26);
    border-radius:12px;
    padding:10px 12px;
  }

  .case-add-page .okBox{
    margin-bottom:14px;
    border:1px solid rgba(52,211,153,.24);
    background:rgba(6,95,70,.18);
    color:#d1fae5;
    border-radius:14px;
    padding:12px;
    line-height:1.9;
  }

  .case-add-page .code{
    display:inline-block;
    padding:6px 10px;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    font-weight:900;
    letter-spacing:1px;
  }

  .case-add-page .link{
    color:#ffd76a;
    font-weight:900;
    word-break:break-all;
    text-decoration:none;
  }

  .case-add-page .btnMini{
    height:38px;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    cursor:pointer;
    font-weight:900;
    padding:0 12px;
    margin-right:8px;
    font-family:inherit;
    color:#fff;
  }

  .form3{
    display:grid;
    grid-template-columns:repeat(3, minmax(0, 1fr));
    gap:22px 18px;
    align-items:start;
  }

  .row{
    display:flex;
    flex-direction:column;
    gap:10px;
    min-width:0;
  }

  .row label{
    font-size:18px;
    font-weight:800;
    color:#fff;
    line-height:1.2;
  }

  .row input,
  .row select,
  .row textarea{
    width:100%;
    min-height:56px;
    border-radius:18px;
    border:1px solid rgba(255,255,255,.10);
    background:rgba(255,255,255,.06);
    padding:14px 18px;
    color:#fff;
    font:inherit;
    outline:none;
    box-sizing:border-box;
    transition:all .2s ease;
  }

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

  .row input::placeholder,
  .row textarea::placeholder{
    color:rgba(255,255,255,.45);
  }

  .row select option{
    background:#0b1f26;
    color:#fff;
  }

  .row input:focus,
  .row select:focus,
  .row textarea:focus{
    border-color:rgba(212,175,55,.75);
    box-shadow:0 0 0 3px rgba(212,175,55,.12);
    background:rgba(255,255,255,.08);
  }

  .span-2{
    grid-column:span 2;
  }

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

  .muted{
    color:var(--muted);
    font-size:14px;
    line-height:1.7;
  }

  .secretBox{
    display:flex;
    flex-direction:column;
    gap:8px;
    padding:16px 18px;
    border:1px solid rgba(248,113,113,.22);
    background:rgba(127,29,29,.14);
    border-radius:18px;
  }

  .secretBox input[type="checkbox"]{
    width:18px;
    height:18px;
    margin:0 0 6px 0;
    accent-color:#b91c1c;
  }

  .secretTitle{
    font-size:18px;
    font-weight:800;
    color:#fecaca;
  }

  .secretHint{
    font-size:14px;
    line-height:1.7;
    color:#fecaca;
  }

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

  .fileRow input[type="file"]{
    flex:1;
    min-width:240px;
    min-height:56px;
    border:1px dashed rgba(255,255,255,.18);
    border-radius:18px;
    background:rgba(255,255,255,.04);
    color:#fff;
    padding:12px 14px;
  }

  .pickBtn{
    height:52px;
    min-width:130px;
    border:none;
    border-radius:14px;
    padding:0 18px;
    font:inherit;
    font-weight:700;
    cursor:pointer;
    background:rgba(255,255,255,.10);
    color:#fff;
  }

  .saveBtn{
    width:100%;
    min-width:190px;
    height:54px;
    border:none;
    border-radius:16px;
    background:linear-gradient(135deg,#d4af37,#b8932f);
    color:#08343c;
    font-weight:800;
    font-family:inherit;
    cursor:pointer;
    padding:0 24px;
    box-shadow:0 12px 28px rgba(212,175,55,.28);
  }

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

    .span-2,
    .span-3{
      grid-column:1 / -1;
    }
  }

  @media (max-width:700px){
    .case-add-page .pageTitle{
      font-size:24px;
    }

    .case-add-page .formGrid{
      padding:16px;
      border-radius:18px;
    }

    .form3{
      grid-template-columns:1fr;
      gap:14px;
    }

    .span-2,
    .span-3{
      grid-column:auto;
    }

    .row label{
      font-size:16px;
    }

    .fileRow{
      flex-direction:column;
      align-items:stretch;
    }

    .fileRow input[type="file"],
    .pickBtn,
    .saveBtn{
      width:100%;
      min-width:0;
    }
  }

  .btn-save{
    width:100%;
    height:72px;
    font-size:32px;
    font-weight:800;
    color:#08383d;
    cursor:pointer;
    background:linear-gradient(180deg,#e2bf4d,#c8a32f);
    border:none;
    display:flex;
    align-items:center;
    justify-content:center;
    letter-spacing:.5px;
    box-shadow:
      0 18px 35px rgba(0,0,0,.25),
      inset 0 2px 0 rgba(255,255,255,.4);
    transition:all .25s ease;
    clip-path:polygon(
      3% 0%,
      97% 0%,
      100% 30%,
      100% 70%,
      97% 100%,
      3% 100%,
      0% 70%,
      0% 30%
    );
  }

  .btn-save:hover{
    transform:translateY(-3px) scale(1.01);
    box-shadow:
      0 25px 45px rgba(0,0,0,.35),
      0 0 25px rgba(212,175,55,.35);
  }

  .btn-save:active{
    transform:scale(.98);
  }
  /* =========================
   LEGEND CASE PAGE BUTTONS
========================= */

/* زر الرجوع + الحفظ */
.case-add-page .btnLink,
.case-add-page .btn-save{
  position:relative;
  overflow:hidden;

  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:10px;

  height:52px;
  padding:0 22px;

  border-radius:999px;
  border:1px solid rgba(212,175,55,.55);

  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1a1400 !important;

  font-weight:900;
  font-size:14px;
  letter-spacing:.3px;

  text-decoration:none;
  cursor:pointer;

  box-shadow:
    0 15px 32px rgba(212,175,55,.35),
    0 0 25px rgba(212,175,55,.25),
    inset 0 2px 6px rgba(255,255,255,.35);

  transition:all .25s ease;
}

/* زر الحفظ يكون أعرض */
.case-add-page .btn-save{
  width:100%;
  height:58px;
  font-size:18px;
}

/* ✨ لمعة متحركة */
.case-add-page .btnLink::after,
.case-add-page .btn-save::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;

  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.65),
    transparent
  );

  transform:skewX(-20deg);
  animation:casePageBtnShine 3.5s infinite;
}

@keyframes casePageBtnShine{
  0%{ left:-70%; opacity:0 }
  40%{ opacity:.9 }
  100%{ left:130%; opacity:0 }
}

/* hover 🔥 */
.case-add-page .btnLink:hover,
.case-add-page .btn-save:hover{
  transform:translateY(-3px) scale(1.03);

  box-shadow:
    0 22px 45px rgba(212,175,55,.45),
    0 0 35px rgba(212,175,55,.35),
    inset 0 2px 6px rgba(255,255,255,.45);
}

/* ضغط */
.case-add-page .btnLink:active,
.case-add-page .btn-save:active{
  transform:scale(.96);
}
 /* إصلاح انكماش صفحة تعديل القضية */
.layout-content,
.layout-main,
.main-content,
.page-content,
.app-content,
.content,
.content-area{
  width:100% !important;
  max-width:none !important;
}
</style>

<div class="case-add-page">
  <div class="topbar-local">
    <div></div>
  </div>

  <div class="page-head">
    <div class="titleWrap">
      <h1 class="pageTitle">إضافة قضية</h1>
      <div class="pageSub">
        <?= $canSwitchBranch ? 'سيتم حفظ القضية داخل الفرع الحالي.' : 'سيتم حفظ القضية داخل فرعك تلقائيًا ولا يمكن تغيير الفرع.' ?>
      </div>
    </div>

    <div class="actions">
      <a class="btnLink" href="<?= h(u('cases.php')) ?>">رجوع</a>
    </div>
  </div>

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

      <?php if ($eFlag === '1'): ?>
        <div class="err">تحقق من رقم القضية ونوع القضية.</div>
      <?php endif; ?>

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

      <?php if ($clientCode !== ''): ?>
        <div class="okBox">
          <div><?= h($okMsg !== '' ? $okMsg : 'تمت إضافة القضية بنجاح.') ?></div>
          <div>
            كود العميل:
            <span class="code" id="clientCode"><?= h($clientCode) ?></span>
            <button type="button" class="btnMini" onclick="copyClientCode()">نسخ</button>
          </div>
          <div>
            رابط العميل:
            <a class="link" href="<?= h($clientLink) ?>" target="_blank" rel="noopener"><?= h($clientLink) ?></a>
          </div>
          <div class="muted">سيظهر إشعار في الجرس لجميع المستخدمين.</div>
        </div>
      <?php endif; ?>

      <form method="post" enctype="multipart/form-data" class="form3" autocomplete="off">
        <input type="hidden" name="client_id" id="client_id" value="<?= (int)$oldClientId ?>">

        <div class="row">
          <label for="case_no">رقم القضية</label>
          <input
            id="case_no"
            name="case_no"
            type="text"
            required
            placeholder="1972/2026"
            value="<?= h($oldCaseNo) ?>"
          >
        </div>

        <div class="row">
          <label for="title">نوع القضية</label>
          <input
            id="title"
            name="title"
            type="text"
            required
            placeholder="قضية تجارية - ..."
            value="<?= h($oldTitle) ?>"
          >
        </div>

        <div class="row">
          <label for="client_search">اختيار العميل</label>
         <input
  type="text"
  id="client_search"
  name="client_search"
  list="clients_list"
  placeholder="اكتب اسم العميل أو رقمه أو هاتفه"
  value="<?= h($oldClientSearch) ?>"
  required
>

          <datalist id="clients_list">
            <?php foreach ($clients as $c): ?>
              <option
                value="<?= h((string)$c['name']) ?>"
                data-id="<?= (int)$c['id'] ?>"
                data-phone="<?= h((string)($c['phone'] ?? '')) ?>"
                data-email="<?= h((string)($c['email'] ?? '')) ?>"
              >
                <?= h((string)$c['name']) ?><?= !empty($c['phone']) ? ' - ' . h((string)$c['phone']) : '' ?>
              </option>
            <?php endforeach; ?>
          </datalist>

          <div class="muted">ابدأ بكتابة اسم العميل ثم اختره من القائمة.</div>
        </div>

        <div class="row">
          <label for="client_phone">رقم الهاتف</label>
          <input
            id="client_phone"
            name="client_phone"
            type="text"
            placeholder="+9715XXXXXXXX"
            value="<?= h($oldClientPhone) ?>"
          >
        </div>

        <div class="row">
          <label for="client_email">البريد الإلكتروني للعميل</label>
          <input
            id="client_email"
            type="email"
            name="client_email"
            placeholder="example@email.com"
            value="<?= h($oldClientEmail) ?>"
          >
          <div class="muted">يرجى كتابة البريد الإلكتروني الصحيح للعميل لتسهيل التواصل وإرسال التحديثات.</div>
        </div>

        <div class="row">
          <label for="lawyer_name">الموظف المسؤول</label>
          <select id="lawyer_name" name="lawyer_name">
            <option value="">اختر الموظف المسؤول</option>
            <?php foreach ($employees as $emp): ?>
              <?php
                $empName = trim((string)($emp['full_name'] ?? $emp['name'] ?? ''));
                if ($empName === '') continue;
              ?>
              <option value="<?= h($empName) ?>" <?= $oldLawyerName === $empName ? 'selected' : '' ?>>
                <?= h($empName) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="muted">يتم عرض موظفي الفرع الحالي فقط.</div>
        </div>

        <div class="row">
          <label for="status">الحالة</label>
          <select id="status" name="status">
            <option value="NEW" <?= $oldStatus === 'NEW' ? 'selected' : '' ?>>جديدة</option>
            <option value="WORK" <?= $oldStatus === 'WORK' ? 'selected' : '' ?>>قيد العمل</option>
            <option value="COURT" <?= $oldStatus === 'COURT' ? 'selected' : '' ?>>في المحكمة</option>
            <option value="CLOSED" <?= $oldStatus === 'CLOSED' ? 'selected' : '' ?>>مغلقة</option>
          </select>
        </div>

        <div class="row">
          <label for="next_hearing_date">تاريخ الجلسة القادمة</label>
          <input
            id="next_hearing_date"
            type="date"
            name="next_hearing_date"
            value="<?= h($oldNextHearingDate) ?>"
          >
        </div>

        <div class="row span-3">
          <label for="notes">ملاحظات داخلية</label>
          <textarea
            id="notes"
            name="notes"
            placeholder="اكتب ملاحظات داخلية عن القضية..."
          ><?= h($oldNotes ?? '') ?></textarea>
          <div class="muted">هذه الملاحظات داخلية للموظفين فقط.</div>
        </div>

        <div class="row span-3">
          <label for="client_notes">ملاحظات للعميل</label>
          <textarea
            id="client_notes"
            name="client_notes"
            placeholder="اكتب هنا ما تريد إيصاله فقط للعميل..."
          ><?= h($oldClientNotes ?? '') ?></textarea>
          <div class="muted">هذه الملاحظات تظهر للعميل فقط وليست ملاحظات داخلية للموظفين.</div>
        </div>

        <div class="row span-3">
          <label for="is_secret">إعدادات السرية</label>
          <label class="secretBox" for="is_secret">
            <input
              id="is_secret"
              type="checkbox"
              name="is_secret"
              value="1"
              <?= !empty($oldIsSecret) ? 'checked' : '' ?>
            >
            <span class="secretTitle">قضية سرية</span>
            <div class="secretHint">
              هذه القضية ستظهر للـ OWNER فقط، ولن تظهر لباقي المستخدمين.
            </div>
          </label>
        </div>

        <div class="row span-3">
          <label for="attachments">مرفقات القضية</label>
          <div class="fileRow">
            <input
              id="attachments"
              type="file"
              name="attachments[]"
              multiple
              accept=".pdf,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx"
            >
            <button type="button" class="pickBtn" id="pickBtn">اختيار الملفات</button>
          </div>
          <div id="filesInfo" class="muted">لم يتم اختيار أي ملف</div>
          <div class="muted">سيتم رفع الملفات عند الضغط على زر حفظ القضية.</div>
        </div>

        <div class="row span-3">
          <button type="submit" class="btn-save">حفظ القضية</button>
        </div>
      </form>

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

<script>
(function(){
  const form  = document.querySelector('form.form3');
  const input = document.getElementById('attachments');
  const info  = document.getElementById('filesInfo');
  const pick  = document.getElementById('pickBtn');

  function listNames() {
    if (!input || !input.files || input.files.length === 0) {
      return 'لم يتم اختيار أي ملف';
    }
    return Array.from(input.files).map(f => f.name).join('، ');
  }

  if (pick && input) {
    pick.addEventListener('click', function(){
      input.click();
    });
  }

  if (input && info) {
    input.addEventListener('change', function(){
      info.textContent = listNames();
    });
  }

  window.copyClientCode = function(){
    const el = document.getElementById('clientCode');
    if (!el) return;

    const text = el.textContent.trim();
    if (!text) return;

    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text).then(function(){
        alert('تم نسخ الكود');
      }).catch(function(){
        alert('تعذر نسخ الكود');
      });
      return;
    }

    const temp = document.createElement('textarea');
    temp.value = text;
    document.body.appendChild(temp);
    temp.select();

    try {
      document.execCommand('copy');
      alert('تم نسخ الكود');
    } catch (e) {
      alert('تعذر نسخ الكود');
    }

    document.body.removeChild(temp);
  };

  const clientSearch = document.getElementById('client_search');
  const clientId     = document.getElementById('client_id');
  const clientPhone  = document.getElementById('client_phone');
  const clientEmail  = document.getElementById('client_email');
  const options      = document.querySelectorAll('#clients_list option');

  function syncClientByName() {
    if (!clientSearch || !clientId) return;

    const typed = clientSearch.value.trim();
    let matched = null;

    options.forEach(function(opt){
      if (opt.value.trim() === typed) {
        matched = opt;
      }
    });

    if (matched) {
      clientId.value = matched.dataset.id || '';
      if (clientPhone && !clientPhone.value.trim()) {
        clientPhone.value = matched.dataset.phone || '';
      }
      if (clientEmail && !clientEmail.value.trim()) {
        clientEmail.value = matched.dataset.email || '';
      }
    } else {
      clientId.value = '';
    }
  }

  if (clientSearch) {
    clientSearch.addEventListener('change', syncClientByName);
    clientSearch.addEventListener('blur', syncClientByName);
  }

  if (form && clientSearch) {
    form.addEventListener('submit', function(e){
      syncClientByName();

      if (clientSearch.value.trim() === '') {
        e.preventDefault();
        alert('يرجى تعبئة اسم العميل قبل حفظ القضية.');
        clientSearch.focus();
        return false;
      }
    });
  }
})();
</script>
<?php render_layout_end(); ?>