<?php
// hr_leaves.php (FULL FIXED)
declare(strict_types=1);

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

/* Debug: hr_leaves.php?debug=1 */
$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);

/* Fatal */
register_shutdown_function(function() use ($debug){
  $e = error_get_last();
  if (!$e) return;
  http_response_code(500);
  if (!$debug) { echo "HTTP ERROR 500"; return; }
  echo "<pre style='direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap'>";
  echo "FATAL ERROR\n";
  echo "Type: {$e['type']}\nMessage: {$e['message']}\nFile: {$e['file']}\nLine: {$e['line']}\n";
  echo "</pre>";
});

set_exception_handler(function(Throwable $e) use ($debug){
  http_response_code(500);
  if (!$debug) { echo "HTTP ERROR 500"; exit; }
  echo "<pre style='direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap'>";
  echo "UNCAUGHT EXCEPTION\n";
  echo "Message: " . $e->getMessage() . "\n";
  echo "File:    " . $e->getFile() . "\n";
  echo "Line:    " . $e->getLine() . "\n\n";
  echo $e->getTraceAsString();
  echo "</pre>";
  exit;
});

require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/layout.php';
require_once __DIR__ . '/inc/hr_leave_notifications.php';

/* optional mailer */
$maybeMailer = __DIR__ . '/inc/mailer.php';
if (is_file($maybeMailer)) require_once $maybeMailer;

/* Helpers */
if (!function_exists('h')) {
  function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('has_col')) {
  function has_col(PDO $pdo, string $table, string $col): bool {
    static $cache = [];
    $key = spl_object_id($pdo) . ':' . $table;
    if (!isset($cache[$key])) {
      $st = $pdo->query("SHOW COLUMNS FROM `$table`");
      $cache[$key] = $st->fetchAll(PDO::FETCH_COLUMN, 0);
    }
    return in_array($col, $cache[$key], true);
  }
}

/* CSRF fields */
if (!function_exists('csrf_value')) {
  function csrf_value(): string {
    foreach (['csrf', 'csrf_token', '_token', 'token'] as $k) {
      if (!empty($_SESSION[$k]) && is_string($_SESSION[$k])) return (string)$_SESSION[$k];
    }
    $t = bin2hex(random_bytes(16));
    $_SESSION['csrf'] = $t;
    $_SESSION['csrf_token'] = $t;
    $_SESSION['_token'] = $t;
    $_SESSION['token'] = $t;
    return $t;
  }
}
if (!function_exists('csrf_hidden_fields')) {
  function csrf_hidden_fields(): string {
    if (function_exists('csrf_field')) {
      ob_start();
      csrf_field();
      return (string)ob_get_clean();
    }
    $t = h(csrf_value());
    return
      '<input type="hidden" name="csrf" value="'.$t.'">'.
      '<input type="hidden" name="csrf_token" value="'.$t.'">'.
      '<input type="hidden" name="_token" value="'.$t.'">'.
      '<input type="hidden" name="token" value="'.$t.'">';
  }
}
if (!function_exists('csrf_verify')) {
  function csrf_verify(): bool {
    $session = '';
    foreach (['csrf','csrf_token','_token','token'] as $k) {
      if (!empty($_SESSION[$k]) && is_string($_SESSION[$k])) { $session = (string)$_SESSION[$k]; break; }
    }
    if ($session === '') return true;
    $posted = '';
    foreach (['csrf','csrf_token','_token','token'] as $k) {
      if (isset($_POST[$k]) && is_string($_POST[$k]) && $_POST[$k] !== '') { $posted = (string)$_POST[$k]; break; }
    }
    return $posted !== '' && hash_equals($session, $posted);
  }
}

if (!function_exists('redirect_self')) {
  function redirect_self(array $qs = []) {
    $base = strtok($_SERVER['REQUEST_URI'], '?') ?: 'hr_leaves.php';
    $keepDebug = (isset($_GET['debug']) && $_GET['debug'] === '1');
    if ($keepDebug && !isset($qs['debug'])) $qs['debug'] = '1';
    $q = $qs ? ('?' . http_build_query($qs)) : '';
    header("Location: {$base}{$q}");
    exit;
  }
}

/* =========================
   AJAX guard
========================= */
$isAjaxLookup = (isset($_GET['ajax']) && $_GET['ajax'] === 'emp_lookup');
if ($isAjaxLookup) {
  header('Content-Type: application/json; charset=utf-8');
  if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['ok'=>0,'msg'=>'انتهت الجلسة. سجل دخول ثم أعد المحاولة.'], JSON_UNESCAPED_UNICODE);
    exit;
  }
}

/* login (page) */
if (!$isAjaxLookup && function_exists('require_login')) require_login();

/* PDO */
$pdo = null;
if (function_exists('dbx')) $pdo = dbx();
elseif (function_exists('db')) $pdo = db();

if (!$pdo instanceof PDO) {
  if ($isAjaxLookup) {
    http_response_code(500);
    echo json_encode(['ok'=>0,'msg'=> $debug ? 'PDO not ready' : 'خطأ بالخادم'], JSON_UNESCAPED_UNICODE);
    exit;
  }
  http_response_code(500);
  echo $debug ? "DB ERROR: PDO not ready" : "HTTP ERROR 500";
  exit;
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$role     = function_exists('current_role') ? current_role() : strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isOwner  = ($role === 'OWNER');
$isAdmin  = ($role === 'ADMIN');
$userId   = function_exists('current_user_id') ? (int)current_user_id() : (int)($_SESSION['user_id'] ?? 0);
$branchId = function_exists('current_branch_id') ? (int)current_branch_id() : (int)($_SESSION['branch_id'] ?? 1);

$canManageLeaves = ($isOwner || $isAdmin);
$msg = '';
$err = '';

/* Labels */
$leaveTypeLabel = [
  'ANNUAL'    => 'سنوية',
  'SICK'      => 'مرضية',
  'EMERGENCY' => 'طارئة',
  'OTHER'     => 'أخرى',
];

/* schema */
$lr_has_branch = $lr_has_status = $lr_has_reason = $lr_has_created_by = $lr_has_decided_by = $lr_has_decided_at = $lr_has_created_at = false;
$lr_has_last_notified_status = $lr_has_last_notified_at = false;
$lr_has_rejection_note = has_col($pdo,'leave_requests','rejection_note');
$emp_has_branch = $emp_has_user = $emp_has_qr = false;
$empSelectName = "CONCAT('EMP#', e.id)";
$myQr = '';

try {
  $pdo->query("SELECT 1 FROM employees LIMIT 1");
  $pdo->query("SELECT 1 FROM leave_requests LIMIT 1");

  $lr_has_branch               = has_col($pdo,'leave_requests','branch_id');
  $lr_has_status               = has_col($pdo,'leave_requests','status');
  $lr_has_reason               = has_col($pdo,'leave_requests','reason');
  $lr_has_created_by           = has_col($pdo,'leave_requests','created_by');
  $lr_has_decided_by           = has_col($pdo,'leave_requests','decided_by');
  $lr_has_decided_at           = has_col($pdo,'leave_requests','decided_at');
  $lr_has_created_at           = has_col($pdo,'leave_requests','created_at');
  $lr_has_last_notified_status = has_col($pdo,'leave_requests','last_notified_status');
  $lr_has_last_notified_at     = has_col($pdo,'leave_requests','last_notified_at');
  $emp_has_branch = has_col($pdo,'employees','branch_id');
  $emp_has_user   = has_col($pdo,'employees','user_id');
  $emp_has_qr     = has_col($pdo,'employees','qr_token2');

  $empNameCol = has_col($pdo,'employees','full_name') ? 'full_name'
             : (has_col($pdo,'employees','name') ? 'name'
             : (has_col($pdo,'employees','employee_name') ? 'employee_name'
             : (has_col($pdo,'employees','email') ? 'email' : '')));

  $empSelectName = $empNameCol !== '' ? "e.`$empNameCol`" : "CONCAT('EMP#', e.id)";

} catch (Throwable $e) {
  if ($isAjaxLookup) {
    http_response_code(500);
    echo json_encode(['ok'=>0,'msg'=> $debug ? $e->getMessage() : 'تعذر تحميل البيانات'], JSON_UNESCAPED_UNICODE);
    exit;
  }
  $err = $debug ? ("DB INIT ERROR: ".$e->getMessage()) : 'تعذر تحميل البيانات.';
}

/* =========================
   Auto link STAFF -> employee_id
========================= */
$sessionEmpId = (int)($_SESSION['employee_id'] ?? 0);

try {
  if (!$isOwner && $emp_has_user && $userId > 0) {
    if ($sessionEmpId <= 0) {
      $sql = "SELECT e.id".($emp_has_qr ? ", e.qr_token2" : "")."
              FROM employees e
              WHERE e.user_id=?
              ORDER BY e.id DESC
              LIMIT 1";
      $st = $pdo->prepare($sql);
      $st->execute([$userId]);
      $row = $st->fetch();

      $sessionEmpId = (int)($row['id'] ?? 0);
      if ($sessionEmpId > 0) {
        $_SESSION['employee_id'] = $sessionEmpId;
        if ($emp_has_qr) $myQr = (string)($row['qr_token2'] ?? '');
      }
    } else {
      if ($emp_has_qr) {
        $st = $pdo->prepare("SELECT qr_token2 FROM employees WHERE id=? LIMIT 1");
        $st->execute([$sessionEmpId]);
        $myQr = (string)($st->fetchColumn() ?: '');
      }
    }
  }
} catch (Throwable $e) {
  if (!$err && $debug) $err = "EMP AUTO LINK ERROR: ".$e->getMessage();
}

/* =========================
   AJAX lookup
========================= */
if ($isAjaxLookup) {
  $qr = preg_replace('/\s+/', '', trim((string)($_GET['qr'] ?? '')));

  if (!$emp_has_qr) {
    echo json_encode(['ok'=>0,'msg'=>'عمود qr_token2 غير موجود في employees'], JSON_UNESCAPED_UNICODE);
    exit;
  }
  if (!preg_match('/^\d{1,4}$/', $qr)) {
    echo json_encode(['ok'=>0,'msg'=>'أدخل 1 إلى 4 أرقام'], JSON_UNESCAPED_UNICODE);
    exit;
  }
  $qr = str_pad($qr, 4, '0', STR_PAD_LEFT);

  try {
if ($isOwner) {
  $st = $pdo->prepare("
    SELECT e.id, ($empSelectName) AS full_name
    FROM employees e
    WHERE e.qr_token2 = ?
    LIMIT 1
  ");
  $st->execute([$qr]);
  $emp = $st->fetch();

  if (!$emp) {
    echo json_encode(['ok'=>0,'msg'=>'لا يوجد موظف بهذا الباركود'], JSON_UNESCAPED_UNICODE);
    exit;
  }

  echo json_encode([
    'ok'   => 1,
    'id'   => (int)$emp['id'],
    'name' => (string)$emp['full_name'],
    'qr'   => $qr
  ], JSON_UNESCAPED_UNICODE);
  exit;
}

if ($isAdmin) {
  $st = $pdo->prepare("
    SELECT e.id, ($empSelectName) AS full_name
    FROM employees e
    WHERE e.qr_token2 = ?
      AND e.branch_id = ?
    LIMIT 1
  ");
  $st->execute([$qr, $branchId]);
  $emp = $st->fetch();

  if (!$emp) {
    echo json_encode(['ok'=>0,'msg'=>'لا يوجد موظف بهذا الباركود في فرعك'], JSON_UNESCAPED_UNICODE);
    exit;
  }

  echo json_encode([
    'ok'   => 1,
    'id'   => (int)$emp['id'],
    'name' => (string)$emp['full_name'],
    'qr'   => $qr
  ], JSON_UNESCAPED_UNICODE);
  exit;
}

    if (!$emp_has_user) {
      echo json_encode(['ok'=>0,'msg'=>'لا يوجد عمود user_id في employees للربط'], JSON_UNESCAPED_UNICODE);
      exit;
    }
    if ($userId <= 0) {
      echo json_encode(['ok'=>0,'msg'=>'انتهت الجلسة'], JSON_UNESCAPED_UNICODE);
      exit;
    }

    $st = $pdo->prepare("
      SELECT e.id, ($empSelectName) AS full_name
      FROM employees e
      WHERE e.user_id=?
        AND e.qr_token2=?
      LIMIT 1
    ");
    $st->execute([$userId, $qr]);
    $emp = $st->fetch();

    if (!$emp) {
      echo json_encode(['ok'=>0,'msg'=>'هذا الباركود لا يطابق حسابك'], JSON_UNESCAPED_UNICODE);
      exit;
    }

    echo json_encode(['ok'=>1,'id'=>(int)$emp['id'],'name'=>(string)$emp['full_name'],'qr'=>$qr], JSON_UNESCAPED_UNICODE);
    exit;

  } catch (Throwable $e) {
    @file_put_contents(__DIR__ . '/cron_mail_error.log',
      date('Y-m-d H:i:s')." hr_leaves ajax_lookup err=".$e->getMessage()."\n", FILE_APPEND);

    echo json_encode(['ok'=>0,'msg'=> $debug ? $e->getMessage() : 'خطأ أثناء التحقق'], JSON_UNESCAPED_UNICODE);
    exit;
  }
}

/* =========================
   POST actions
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = (string)($_POST['action'] ?? '');

  if (!csrf_verify()) {
    $err = 'انتهت الجلسة أو رمز الحماية غير صحيح. حدّث الصفحة وحاول مرة أخرى.';
  }

  try {

    if (!$err && $action === 'create') {

      if (!$emp_has_qr) {
        $err = 'نظام الباركود غير مفعل: عمود qr_token2 غير موجود في جدول الموظفين.';
      }

      $qr_token2  = preg_replace('/\s+/', '', trim((string)($_POST['qr_token2'] ?? '')));
      $leave_type = (string)($_POST['leave_type'] ?? 'ANNUAL');
      $date_from  = (string)($_POST['date_from'] ?? '');
      $date_to    = (string)($_POST['date_to'] ?? '');
      $reason     = trim((string)($_POST['reason'] ?? ''));

      if (!$err) {
        if (!preg_match('/^\d{1,4}$/', $qr_token2)) {
          $err = 'أدخل رقم الباركود (1 إلى 4 أرقام). مثال: 0012';
        } else {
          $qr_token2 = str_pad($qr_token2, 4, '0', STR_PAD_LEFT);
        }
      }

      $employee_id = 0;
      $emp_branch_id = $branchId;

      if (!$err) {
        if ($isAdmin) {
          $st = $pdo->prepare("SELECT id, branch_id FROM employees WHERE qr_token2=? LIMIT 1");
          $st->execute([$qr_token2]);
          $emp = $st->fetch(PDO::FETCH_ASSOC);

          if (!$emp) $err = 'باركود غير موجود.';
          else {
            $employee_id   = (int)$emp['id'];
            $emp_branch_id = (int)($emp['branch_id'] ?? $branchId);
          }

        } else {
          if (!$emp_has_user) {
            $err = 'لا يمكن التحقق: عمود user_id غير موجود في employees.';
          } elseif ($userId <= 0) {
            $err = 'لم يتم التعرف على حسابك. أعد تسجيل الدخول.';
          } else {
            $st = $pdo->prepare("
              SELECT id, branch_id
              FROM employees
              WHERE user_id=?
                AND qr_token2=?
              LIMIT 1
            ");
            $st->execute([$userId, $qr_token2]);
            $emp = $st->fetch(PDO::FETCH_ASSOC);

            if (!$emp) $err = 'هذا الباركود لا يطابق حسابك.';
            else {
              $employee_id   = (int)$emp['id'];
              $emp_branch_id = (int)($emp['branch_id'] ?? $branchId);
            }
          }
        }
      }

      if (!$err && (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_to))) {
        $err = 'تواريخ غير صحيحة';
      }
      if (!$err && $date_to < $date_from) $err = 'تاريخ النهاية يجب أن يكون بعد البداية';

      if (!$err) {
        $allowed = ['ANNUAL','SICK','EMERGENCY','OTHER'];
        if (!in_array($leave_type, $allowed, true)) $leave_type = 'ANNUAL';

        $fields = ['employee_id','leave_type','date_from','date_to'];
        $vals   = [$employee_id,$leave_type,$date_from,$date_to];

        if ($lr_has_branch)     { $fields[]='branch_id';  $vals[]=$emp_branch_id; }
        if ($lr_has_reason)     { $fields[]='reason';     $vals[] = ($reason !== '' ? $reason : null); }
        if ($lr_has_status)     { $fields[]='status';     $vals[]='PENDING'; }
        if ($lr_has_created_by) { $fields[]='created_by'; $vals[]=$userId; }

        $ph  = implode(',', array_fill(0, count($fields), '?'));
        $sql = "INSERT INTO leave_requests (".implode(',', $fields).") VALUES ($ph)";
        $st  = $pdo->prepare($sql);
        $st->execute($vals);

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

     if (function_exists('send_leave_request_email') && $newId > 0 && has_col($pdo, 'leave_requests', 'admin_notified_at')) {

    $stLock = $pdo->prepare("
        UPDATE leave_requests
        SET admin_notified_at = NOW()
        WHERE id = ?
          AND admin_notified_at IS NULL
        LIMIT 1
    ");
    $stLock->execute([$newId]);

    if ($stLock->rowCount() > 0) {
        try {
            @send_leave_request_email($newId);
        } catch (Throwable $e) {}
    }
}
   

        redirect_self(['ok'=>1]);
      }
    }
   if (!$err && $action === 'edit') {

  $id         = (int)($_POST['id'] ?? 0);
  $leave_type = (string)($_POST['leave_type'] ?? 'ANNUAL');
  $date_from  = (string)($_POST['date_from'] ?? '');
  $date_to    = (string)($_POST['date_to'] ?? '');
  $reason     = trim((string)($_POST['reason'] ?? ''));

  if ($id <= 0) {
    $err = 'طلب غير صحيح';
  }

  if (!$err && !$canManageLeaves && $sessionEmpId <= 0) {
    $err = 'غير مصرح';
  }

  if (!$err && (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_to))) {
    $err = 'تواريخ غير صحيحة';
  }

  if (!$err && $date_to < $date_from) {
    $err = 'تاريخ النهاية يجب أن يكون بعد البداية';
  }

  if (!$err) {

    $allowed = ['ANNUAL','SICK','EMERGENCY','OTHER'];
    if (!in_array($leave_type, $allowed, true)) {
      $leave_type = 'ANNUAL';
    }

    $set = [
      "leave_type=?",
      "date_from=?",
      "date_to=?"
    ];

    $vals = [
      $leave_type,
      $date_from,
      $date_to
    ];

    if ($lr_has_reason) {
      $set[] = "reason=?";
      $vals[] = ($reason !== '') ? $reason : null;
    }

    // عند تعديل الموظف لطلب مرفوض يرجع الطلب قيد المراجعة
    if ($lr_has_status) {
      $set[] = "status=?";
      $vals[] = "PENDING";
    }

    // مسح سبب الرفض القديم بعد التعديل
    if ($lr_has_rejection_note) {
      $set[] = "rejection_note=?";
      $vals[] = null;
    }

    $where = " WHERE id=? ";
    $vals[] = $id;

    // الموظف يعدل طلبه فقط
    if (!$canManageLeaves) {
      $where .= " AND employee_id=? ";
      $vals[] = $sessionEmpId;
    }

    $sql = "UPDATE leave_requests SET " . implode(',', $set) . $where . " LIMIT 1";
    $st = $pdo->prepare($sql);
    $st->execute($vals);

    redirect_self(['ok'=>6]);
  }
}

    if (!$err && $action === 'decide') {
        $rejection_note = trim((string)($_POST['rejection_note'] ?? ''));
      if (!$canManageLeaves) $err = 'غير مصرح';
      else {
        $id = (int)($_POST['id'] ?? 0);
        $decision = (string)($_POST['decision'] ?? '');
        if ($id <= 0) $err = 'طلب غير صحيح';

        $new = ($decision === 'APPROVE') ? 'APPROVED' : (($decision === 'REJECT') ? 'REJECTED' : '');
        if (!$err && $new === '') $err = 'قرار غير صحيح';

        if (!$err) {
          $lastNotified = '';

          if ($lr_has_last_notified_status) {
            try {
              $st0 = $pdo->prepare("SELECT COALESCE(last_notified_status,'') FROM leave_requests WHERE id=? LIMIT 1");
              $st0->execute([$id]);
              $lastNotified = strtoupper((string)($st0->fetchColumn() ?: ''));
            } catch (Throwable $e) {
              $lastNotified = '';
            }
          }

          $set  = [];
          $vals = [];

        $rejection_note = trim((string)($_POST['rejection_note'] ?? ''));

if ($lr_has_status) {
    $set[] = "status=?";
    $vals[] = $new;
}

if ($lr_has_rejection_note) {

    $rejection_note = trim((string)($_POST['rejection_note'] ?? ''));

    $set[] = "rejection_note=?";

    if ($new === 'REJECTED') {

        $vals[] = ($rejection_note !== '')
            ? $rejection_note
            : 'تم رفض الطلب من الإدارة';

    } else {

        $vals[] = null;
    }
}
          if ($lr_has_decided_by) { $set[]="decided_by=?"; $vals[]=$userId; }
          if ($lr_has_decided_at) { $set[]="decided_at=NOW()"; }

          if (!$set) {
            $err = 'لا توجد أعمدة لتسجيل القرار';
          } else {
            $sql = "UPDATE leave_requests SET ".implode(',', $set)." WHERE id=?";
            $vals[] = $id;

            if ($lr_has_status) $sql .= " AND status='PENDING'";

            $st = $pdo->prepare($sql);
            $st->execute($vals);

            if ($st->rowCount() > 0) {
              if (function_exists('send_leave_status_to_employee')) {
                if (!$lr_has_last_notified_status || strtoupper($new) !== $lastNotified) {
                    $stCheckNotify = $pdo->prepare("
    SELECT COALESCE(last_notified_status,'')
    FROM leave_requests
    WHERE id=?
    LIMIT 1
");
$stCheckNotify->execute([$id]);

if (strtoupper((string)$stCheckNotify->fetchColumn()) === strtoupper($new)) {
    redirect_self(['ok'=>2]);
}
                  try {
                    $mailRes = send_leave_status_to_employee($pdo, $id);

                    if (!empty($mailRes['ok']) && $lr_has_last_notified_status) {
                      if ($lr_has_last_notified_at) {
                        $stN = $pdo->prepare("UPDATE leave_requests SET last_notified_status=?, last_notified_at=NOW() WHERE id=? LIMIT 1");
                        $stN->execute([$new, $id]);
                      } else {
                        $stN = $pdo->prepare("UPDATE leave_requests SET last_notified_status=? WHERE id=? LIMIT 1");
                        $stN->execute([$new, $id]);
                      }
                    } elseif (empty($mailRes['ok'])) {
                      @file_put_contents(__DIR__ . '/cron_mail_error.log',
                        date('Y-m-d H:i:s')." leave_notify FAIL id={$id} new={$new} res=".json_encode($mailRes, JSON_UNESCAPED_UNICODE)."\n",
                        FILE_APPEND
                      );
                    }

                  } catch (Throwable $e) {
                    @file_put_contents(__DIR__ . '/cron_mail_error.log',
                      date('Y-m-d H:i:s')." leave_notify EXCEPTION id={$id} new={$new} err=".$e->getMessage()."\n",
                      FILE_APPEND
                    );
                  }
                }
              }

            }

            redirect_self(['ok'=>2]);
          }
        }
      }
    }

    if (!$err && $action === 'reopen') {
      if (!$canManageLeaves) $err = 'غير مصرح';
      else {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) $err = 'طلب غير صحيح';
        if (!$err && !$lr_has_status) $err = 'لا يوجد عمود status لإعادة فتح الطلب';
        if (!$err) {
          $st = $pdo->prepare("UPDATE leave_requests SET status='PENDING' WHERE id=?");
          $st->execute([$id]);
          redirect_self(['ok'=>5]);
        }
      }
    }

    if (!$err && $action === 'delete') {
      if (!$canManageLeaves) $err = 'غير مصرح';
      else {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) $err = 'طلب غير صحيح';
        if (!$err) {
          $st = $pdo->prepare("DELETE FROM leave_requests WHERE id=?");
          $st->execute([$id]);
          redirect_self(['ok'=>4]);
        }
      }
    }

    if (!$err && $action === 'cancel') {
      if ($isAdmin) $err = 'غير مصرح';
      else {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) $err = 'طلب غير صحيح';
        if ($sessionEmpId <= 0) $err = 'حسابك غير مربوط بموظف';

        if (!$err) {
          $sqlChk = "SELECT r.id
                     FROM leave_requests r
                     WHERE r.id=? AND r.employee_id=? ";
          $argsChk = [$id, $sessionEmpId];
          if ($lr_has_status) $sqlChk .= " AND r.status='PENDING'";
          $st = $pdo->prepare($sqlChk);
          $st->execute($argsChk);
          if (!$st->fetchColumn()) $err = 'لا يمكن إلغاء هذا الطلب';
        }

        if (!$err) {
          if ($lr_has_status) {
            $st = $pdo->prepare("UPDATE leave_requests SET status='CANCELLED' WHERE id=? AND employee_id=?");
            $st->execute([$id, $sessionEmpId]);
          } else {
            $st = $pdo->prepare("DELETE FROM leave_requests WHERE id=? AND employee_id=?");
            $st->execute([$id, $sessionEmpId]);
          }
          redirect_self(['ok'=>3]);
        }
      }
    }

  } catch (Throwable $e) {
    $err = $debug ? ("POST ERROR: ".$e->getMessage()) : 'حدث خطأ أثناء تنفيذ العملية.';
  }
}

/* Flash */
if (!$msg && isset($_GET['ok'])) {
  $ok = (int)$_GET['ok'];
  if ($ok === 1) $msg = 'تم إرسال طلب الإجازة';
  if ($ok === 2) $msg = 'تم تحديث الحالة';
  if ($ok === 3) $msg = 'تم إلغاء الطلب';
  if ($ok === 4) $msg = 'تم حذف الطلب';
  if ($ok === 5) $msg = 'تمت إعادة فتح الطلب';
  if ($ok === 6) $msg = 'تم تعديل طلب الإجازة';
}
/* Requests list */
$rows = [];
try {
  $selects = [
    "r.id",
    "($empSelectName) AS full_name",
    "r.leave_type",
    "r.date_from",
    "r.date_to"
  ];

  if ($lr_has_reason)     $selects[] = "r.reason";
  if ($lr_has_rejection_note) $selects[] = "r.rejection_note";
  if ($lr_has_status)     $selects[] = "r.status";
  if ($lr_has_created_at) $selects[] = "r.created_at";

  $sql = "SELECT ".implode(", ", $selects)."
          FROM leave_requests r
          JOIN employees e ON e.id = r.employee_id";

  $args = [];
  $w = [];

  if ($isOwner) {
    // الأونر يرى الجميع
  } elseif ($isAdmin) {
    // الأدمن يرى طلبات موظفي فرعه فقط
    $w[] = "e.branch_id = ?";
    $args[] = $branchId;
  } else {
    // الموظف يرى طلباته فقط
    if ($sessionEmpId > 0) {
      $w[] = "r.employee_id = ?";
      $args[] = $sessionEmpId;
    } else {
      $w[] = "1=0";
    }
  }

  if ($w) {
    $sql .= " WHERE " . implode(" AND ", $w);
  }

  $sql .= " ORDER BY r.id DESC LIMIT 500";

  $st = $pdo->prepare($sql);
  $st->execute($args);
  $rows = $st->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
  $rows = [];
  if (!$err) $err = $debug ? ("REQ LOAD ERROR: ".$e->getMessage()) : 'تعذر تحميل الطلبات.';
}


render_layout_start('شؤون الموظفين - الإجازات');
?>

<style>
.grid {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.card {
  width: 100%;
}

.leaveShell {
  width: 100%;
}
.leaveShell{border:1px solid rgba(255,255,255,.10);background:rgba(255,255,255,.03);border-radius:20px;padding:14px}
.leaveHeader{display:flex;align-items:flex-end;justify-content:space-between;gap:12px;margin-bottom:12px}
.leaveHeader .title{font-size:16px;font-weight:900}
.leaveHeader .sub{font-size:13px;color:rgba(255,255,255,.70)}
.formGrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:12px}
.field{display:flex;flex-direction:column;gap:7px;min-width:0}
.field label{font-size:12.5px;color:rgba(255,255,255,.75)}
.input, select{width:100%;padding:12px;border-radius:14px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.22);color:rgba(255,255,255,.92);outline:none;transition:.15s ease}
.input:focus, select:focus{border-color:rgba(0,106,122,.55);box-shadow:0 0 0 4px rgba(0,106,122,.14)}
select option{background:#0b2633;color:#fff}
.qrHelp{font-size:12px;color:rgba(255,255,255,.65);margin-top:6px}
.hintOk{color:rgba(76,217,100,.95)}
.hintBad{color:rgba(255,107,107,.95)}
.empBadge{display:flex;align-items:center;gap:10px;padding:12px;border-radius:16px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.16);min-height:50px}
.empBadge .dot{width:10px;height:10px;border-radius:50%;background:rgba(255,107,107,.95);box-shadow:0 0 0 4px rgba(255,107,107,.12);flex:0 0 auto}
.empBadge.ok .dot{background:rgba(76,217,100,.95);box-shadow:0 0 0 4px rgba(76,217,100,.12)}
.empBadge .t{font-weight:900}
.empBadge .s{font-size:12px;color:rgba(255,255,255,.70);margin-top:2px}
.actionsBar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:2px}
.btn[disabled]{opacity:.55;cursor:not-allowed}
.tableWrap{margin-top:14px;border:1px solid rgba(255,255,255,.10);border-radius:18px;overflow:auto;background:rgba(0,0,0,.10)}
.tableWrap th,.tableWrap td{padding:12px 10px;border-bottom:1px solid rgba(255,255,255,.08);text-align:right;vertical-align:middle;}
.tableWrap th{font-size:12.5px;color:rgba(255,255,255,.78)}
.tableWrap tr:hover td{background:rgba(255,255,255,.03)}
.tag{display:inline-block;padding:6px 10px;border-radius:999px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.12);font-size:12px;color:rgba(255,255,255,.78)}
.tag.ok{border-color:rgba(76,217,100,.35);background:rgba(76,217,100,.10);color:rgba(255,255,255,.92)}
.tag.bad{border-color:rgba(255,107,107,.35);background:rgba(255,107,107,.10);color:rgba(255,255,255,.92)}
@media (max-width: 820px){.leaveHeader{flex-direction:column;align-items:flex-start}.formGrid{grid-template-columns:repeat(6,minmax(0,1fr))}}
@media (max-width: 520px){.formGrid{grid-template-columns:repeat(1,minmax(0,1fr))}}
.flatpickr-input { cursor: pointer; }
.flatpickr-calendar {
  border-radius: 14px;
  border: 1px solid rgba(255,255,255,.15);
  box-shadow: 0 10px 25px rgba(0,0,0,.3);
}
.formGrid{
  display:grid;
  grid-template-columns:repeat(auto-fit, minmax(250px, 1fr));
}
</style>

<div class="grid">
  <?php if ($debug): ?>
    <div class="msg" style="opacity:.9">
      DEBUG: userId=<?= (int)$userId ?> | branchId=<?= (int)$branchId ?> | isAdmin=<?= $isAdmin ? '1' : '0' ?> | sessionEmpId=<?= (int)$sessionEmpId ?> | myQr=<?= h($myQr) ?>
    </div>
  <?php endif; ?>

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

  <div class="card">
    <div class="cardHead">
      <div>
        <div style="font-weight:900">طلبات الإجازة</div>
        <div class="muted" style="font-size:13px"><?= $isAdmin ? 'يمكنك اعتماد/رفض/إدارة الطلبات' : 'طلباتك تظهر تلقائيًا، والباركود فقط لإرسال طلب جديد' ?></div>
      </div>
      <div class="muted" style="font-size:13px"><?= $isAdmin ? 'الباركود فقط عند إرسال طلب بالنيابة' : 'الباركود للتحقق قبل الإرسال فقط' ?></div>
    </div>

    <div class="leaveShell" style="margin-bottom:12px">
      <div class="leaveHeader">
        <div>
          <div class="title">إرسال طلب إجازة</div>
          <div class="sub"><?= $isAdmin ? 'أدخل باركود أي موظف لإرسال طلب بالنيابة' : 'أدخل باركودك (4 أرقام) للتحقق ثم إرسال الطلب' ?></div>
        </div>
        <div class="sub"><?= $isAdmin ? 'وضع الإدارة' : 'مطابقة الباركود مع حسابك' ?></div>
      </div>

      <form method="post" id="leaveForm">
        <?= csrf_hidden_fields() ?>
        <input type="hidden" name="action" value="create">

        <div class="formGrid">
          <div class="field" style="grid-column: span 3;">
            <label>باركود الموظف (4 أرقام)</label>
            <input class="input" inputmode="numeric" maxlength="4" name="qr_token2" id="qr_token2"
              value="<?= h((string)($_SESSION['qr_token2'] ?? '')) ?>" placeholder="مثال: 0012" required>
            <div class="qrHelp" id="qrHint"></div>
          </div>

          <div class="field" style="grid-column: span 5;">
            <label>تأكيد الموظف</label>
            <div class="empBadge" id="empBadge">
              <span class="dot"></span>
              <div style="min-width:0">
                <div class="t" id="empName">لم يتم التحقق بعد</div>
                <div class="s" id="empSub">أدخل الباركود ليظهر الاسم</div>
              </div>
            </div>
          </div>

          <div class="field" style="grid-column: span 4;">
            <label>نوع الإجازة</label>
            <select name="leave_type">
              <option value="ANNUAL">سنوية</option>
              <option value="SICK">مرضية</option>
              <option value="EMERGENCY">طارئة</option>
              <option value="OTHER">أخرى</option>
            </select>
          </div>

          <div class="field" style="grid-column: span 3;">
            <label>من</label>
            <div style="display:flex; gap:8px; align-items:center;">
              <input class="input date-ui" id="date_from_ui" inputmode="numeric" maxlength="10"
                     placeholder="dd/mm/yyyy" autocomplete="off" required>
              <button type="button" class="btn" id="pick_from" style="padding:10px 12px;">📅</button>
            </div>
            <input type="hidden" name="date_from" id="date_from">
          </div>

          <div class="field" style="grid-column: span 3;">
            <label>إلى</label>
            <div style="display:flex; gap:8px; align-items:center;">
              <input class="input date-ui" id="date_to_ui" inputmode="numeric" maxlength="10"
                     placeholder="dd/mm/yyyy" autocomplete="off" required>
              <button type="button" class="btn" id="pick_to" style="padding:10px 12px;">📅</button>
            </div>
            <input type="hidden" name="date_to" id="date_to">
          </div>

          <div id="topErrorBox" class="msg err" style="display:none; margin-bottom:12px;"></div>

          <div class="field" style="grid-column: span 6;">
            <label>السبب (اختياري)</label>
            <input class="input" name="reason" placeholder="سبب مختصر">
          </div>

          <div class="actionsBar" style="grid-column: 1 / -1;">
            <button class="btn" type="submit" id="submitBtn" disabled>إرسال الطلب</button>
            <span class="sub" style="opacity:.75">لن يتم الإرسال إلا بعد التحقق من الباركود</span>
          </div>
        </div>
      </form>
    </div>

    <script>
    (function(){
      const qr = document.getElementById('qr_token2');
      const hint = document.getElementById('qrHint');
      const submitBtn = document.getElementById('submitBtn');
      const badge = document.getElementById('empBadge');
      const empName = document.getElementById('empName');
      const empSub = document.getElementById('empSub');

      let t = null;

      function setState(ok, msg){
        submitBtn.disabled = !ok;
        hint.textContent = msg || '';
        hint.className = 'qrHelp ' + (ok ? 'hintOk' : 'hintBad');
        badge.classList.toggle('ok', !!ok);
      }

      async function lookup(){
        const v0 = (qr.value || '').replace(/\s+/g,'').trim();

        empName.textContent = 'جاري التحقق...';
        empSub.textContent = '';
        setState(false, 'جاري التحقق...');

        if (!/^\d{1,4}$/.test(v0)){
          empName.textContent = 'لم يتم التحقق بعد';
          empSub.textContent = 'أدخل أرقام فقط';
          setState(false, 'أدخل أرقام فقط مثل 0012');
          return;
        }

        const v = v0.padStart(4,'0');

        try{
          const url = new URL(window.location.href);
          url.searchParams.set('ajax','emp_lookup');
          url.searchParams.set('qr', v);

          const res = await fetch(url.toString(), {
            headers:{'Accept':'application/json'},
            credentials:'same-origin'
          });

          const ct = (res.headers.get('content-type') || '').toLowerCase();
          const raw = await res.text();

          if (!res.ok){
            let msg = 'تعذر التحقق';
            if (res.status === 401) msg = 'انتهت الجلسة. سجل دخول ثم أعد المحاولة.';
            empName.textContent = 'تعذر التحقق';
            empSub.textContent = msg;
            setState(false, msg);
            return;
          }

          if (!ct.includes('application/json')){
            empName.textContent = 'تعذر التحقق';
            empSub.textContent = 'الرد ليس JSON';
            setState(false, 'تحقق من الجلسة أو من تحويل تسجيل الدخول');
            return;
          }

          const data = JSON.parse(raw);

          if (!data.ok){
            empName.textContent = 'غير مطابق';
            empSub.textContent = data.msg || 'غير موجود';
            setState(false, data.msg || 'غير موجود');
            return;
          }

          empName.textContent = data.name || 'تم التحقق';
          empSub.textContent = 'تم التعرف على الموظف';
          setState(true, 'تم التحقق بنجاح');

        }catch(e){
          empName.textContent = 'تعذر التحقق';
          empSub.textContent = 'حاول مرة أخرى';
          setState(false, 'تعذر الاتصال للتحقق');
        }
      }

      qr.addEventListener('input', function(){
        clearTimeout(t);
        t = setTimeout(lookup, 250);
      });

      if ((qr.value || '').trim() !== '') lookup();
    })();
    </script>

    <div class="tableWrap">
      <table>
        <thead>
          <tr>
            <th>الموظف</th>
            <th>النوع</th>
            <th>من</th>
            <th>إلى</th>
            <th>السبب</th>
            <th>ملاحظة الرفض</th>
            <th>الحالة</th>
            <th style="width:320px">إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $r): ?>
            <?php
              $type = (string)($r['leave_type'] ?? 'ANNUAL');
              $typeAr = $leaveTypeLabel[$type] ?? $type;
              $stt = (string)($r['status'] ?? 'PENDING');
            ?>
            <tr>
              <td><?= h($r['full_name'] ?? '') ?></td>
              <td><?= h($typeAr) ?></td>
              <td><?= h($r['date_from'] ?? '') ?></td>
              <td><?= h($r['date_to'] ?? '') ?></td>
              <td><?= h($r['reason'] ?? '') ?></td>
              <td>
  <?php if (($r['status'] ?? '') === 'REJECTED'): ?>
    <?= h($r['rejection_note'] ?? '—') ?>
  <?php else: ?>
    —
  <?php endif; ?>
</td>
              <td>
                <?php
                  if ($stt === 'APPROVED') echo '<span class="tag ok">معتمد</span>';
                  elseif ($stt === 'REJECTED') echo '<span class="tag bad">مرفوض</span>';
                  elseif ($stt === 'CANCELLED') echo '<span class="tag" style="opacity:.85">ملغي</span>';
                  else echo '<span class="tag">قيد المراجعة</span>';
                ?>
              </td>
              <td>
                <div class="row" style="gap:8px;flex-wrap:wrap">
                  <?php if ($canManageLeaves): ?>
                    <?php if ($stt === 'PENDING'): ?>
                      <form method="post" style="display:inline">
                        <?= csrf_hidden_fields() ?>
                        <input type="hidden" name="action" value="decide">
                        <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                        <input type="hidden" name="decision" value="APPROVE">
                        <button class="btn" type="submit">اعتماد</button>
                      </form>

                      <form method="post" style="display:inline" onsubmit="return openRejectModal(this);">
  <?= csrf_hidden_fields() ?>

  <input type="hidden" name="action" value="decide">
  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
  <input type="hidden" name="decision" value="REJECT">
  <input type="hidden" name="rejection_note" value="">

  <button class="btn danger" type="submit">رفض</button>
</form>

 
                    <?php else: ?>
                      <?php if ($lr_has_status): ?>
                        <form method="post" style="display:inline" onsubmit="return confirm('إعادة فتح الطلب إلى قيد المراجعة؟');">
                          <?= csrf_hidden_fields() ?>
                          <input type="hidden" name="action" value="reopen">
                          <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                          <button class="btn" type="submit">إعادة فتح</button>
                        </form>
                      <?php endif; ?>
                    <?php endif; ?>

                    <form method="post" style="display:inline" onsubmit="return confirm('حذف الطلب نهائياً؟');">
                      <?= csrf_hidden_fields() ?>
                      <input type="hidden" name="action" value="delete">
                      <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                      <button class="btn danger" type="submit">حذف</button>
                    </form>
                    <button
  type="button"
  class="btn"
  onclick="openEditModal(
    <?= (int)$r['id'] ?>,
    '<?= h($r['leave_type'] ?? 'ANNUAL') ?>',
    '<?= h($r['date_from'] ?? '') ?>',
    '<?= h($r['date_to'] ?? '') ?>',
    '<?= h($r['reason'] ?? '') ?>'
  )">
  تعديل
</button>

                 <?php else: ?>

  <button
    type="button"
    class="btn"
    onclick="openEditModal(
      <?= (int)$r['id'] ?>,
      '<?= h($r['leave_type'] ?? 'ANNUAL') ?>',
      '<?= h($r['date_from'] ?? '') ?>',
      '<?= h($r['date_to'] ?? '') ?>',
      '<?= h($r['reason'] ?? '') ?>'
    )">
    تعديل
  </button>

  <?php if ($stt === 'PENDING'): ?>
                      <form method="post" style="display:inline" onsubmit="return confirm('إلغاء الطلب؟');">
                        <?= csrf_hidden_fields() ?>
                        <input type="hidden" name="action" value="cancel">
                        <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                        <button class="btn danger" type="submit">إلغاء</button>
                      </form>
                    <?php else: ?>
                      <span class="muted">—</span>
                    <?php endif; ?>
                  <?php endif; ?>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>

          <?php if (!$rows): ?>
            <tr><td colspan="7" class="muted">لا توجد طلبات</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

  </div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/ar.js"></script>
<script>
(function(){
  function pad2(n){ return String(n).padStart(2,'0'); }

  function fmtDDMMYYYY(d){
    return `${pad2(d.getDate())}/${pad2(d.getMonth()+1)}/${d.getFullYear()}`;
  }

  function ddmmyyyy_to_ymd(s){
    s = (s||'').trim();
    const m = s.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
    if(!m) return '';
    const dd = +m[1], mm = +m[2], yy = +m[3];
    const d = new Date(yy, mm-1, dd);
    if(d.getFullYear()!==yy || (d.getMonth()+1)!==mm || d.getDate()!==dd) return '';
    return `${yy}-${pad2(mm)}-${pad2(dd)}`;
  }

  function attachAutoSlash(el){
    el.addEventListener('input', function(){
      const nums = el.value.replace(/[^\d]/g,'').slice(0,8);
      let out = '';
      if(nums.length <= 2) out = nums;
      else if(nums.length <= 4) out = nums.slice(0,2) + '/' + nums.slice(2);
      else out = nums.slice(0,2) + '/' + nums.slice(2,4) + '/' + nums.slice(4);
      el.value = out;
    });
  }

  function syncHidden(ui, hidden){
    const ymd = ddmmyyyy_to_ymd(ui.value);
    hidden.value = ymd;
  }

  const fromUI = document.getElementById('date_from_ui');
  const toUI   = document.getElementById('date_to_ui');
  const fromH  = document.getElementById('date_from');
  const toH    = document.getElementById('date_to');
  const btnFrom= document.getElementById('pick_from');
  const btnTo  = document.getElementById('pick_to');

  if(!fromUI || !toUI || !fromH || !toH || !btnFrom || !btnTo) return;

  attachAutoSlash(fromUI);
  attachAutoSlash(toUI);

  fromUI.addEventListener('blur', () => syncHidden(fromUI, fromH));
  toUI.addEventListener('blur', () => syncHidden(toUI, toH));

  const fpFrom = flatpickr(btnFrom, {
    locale: 'ar',
    disableMobile: true,
    clickOpens: true,
    dateFormat: 'Y-m-d',
    onOpen: function(_, __, inst){
      const cur = ddmmyyyy_to_ymd(fromUI.value);
      if(cur) inst.setDate(cur, false, 'Y-m-d');
    },
    onChange: function(selectedDates){
      if(selectedDates && selectedDates[0]){
        const d = selectedDates[0];
        fromUI.value = fmtDDMMYYYY(d);
        fromH.value  = `${d.getFullYear()}-${pad2(d.getMonth()+1)}-${pad2(d.getDate())}`;

        fpTo.set('minDate', d);
        const td = fpTo.selectedDates && fpTo.selectedDates[0];
        if(td && td < d){
          fpTo.clear();
          toUI.value = '';
          toH.value = '';
        }
      }
    }
  });

  const fpTo = flatpickr(btnTo, {
    locale: 'ar',
    disableMobile: true,
    clickOpens: true,
    dateFormat: 'Y-m-d',
    onOpen: function(_, __, inst){
      const cur = ddmmyyyy_to_ymd(toUI.value);
      if(cur) inst.setDate(cur, false, 'Y-m-d');
      if(fpFrom.selectedDates[0]) inst.set('minDate', fpFrom.selectedDates[0]);
    },
    onChange: function(selectedDates){
      if(selectedDates && selectedDates[0]){
        const d = selectedDates[0];
        toUI.value = fmtDDMMYYYY(d);
        toH.value  = `${d.getFullYear()}-${pad2(d.getMonth()+1)}-${pad2(d.getDate())}`;
      }
    }
  });

})();
</script>
<div id="rejectModal" class="rejectModal">
  <div class="rejectBox">

    <div class="rejectTitle">
      سبب رفض الإجازة
    </div>

    <textarea
      id="rejectReason"
      class="rejectTextarea"
      placeholder="اكتب سبب الرفض هنا..."
    ></textarea>

    <div class="rejectActions">
      <button type="button" class="btn" onclick="submitReject()">
        حفظ الرفض
      </button>

      <button type="button" class="btn danger" onclick="closeRejectModal()">
        إلغاء
      </button>
    </div>

  </div>
</div>

<style>
.rejectModal{
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.65);
  display:none;
  align-items:center;
  justify-content:center;
  z-index:99999;
  backdrop-filter:blur(8px);
}

.rejectModal.show{
  display:flex;
}

.rejectBox{
  width:min(500px,95%);
  background:#07141d;
  border:1px solid rgba(255,255,255,.1);
  border-radius:24px;
  padding:24px;
  box-shadow:0 20px 60px rgba(0,0,0,.5);
}

.rejectTitle{
  font-size:22px;
  font-weight:900;
  margin-bottom:18px;
  color:#fff;
}

.rejectTextarea{
  width:100%;
  min-height:140px;
  resize:none;
  border-radius:18px;
  border:1px solid rgba(255,255,255,.12);
  background:rgba(255,255,255,.04);
  color:#fff;
  padding:16px;
  outline:none;
  font-family:inherit;
  font-size:15px;
}

.rejectTextarea:focus{
  border-color:#00bcd4;
  box-shadow:0 0 0 4px rgba(0,188,212,.15);
}

.rejectActions{
  display:flex;
  gap:10px;
  margin-top:18px;
}
</style>

<script>
let rejectForm = null;

function openRejectModal(form){
  rejectForm = form;

  document
    .getElementById('rejectModal')
    .classList.add('show');

  return false;
}

function closeRejectModal(){
  document
    .getElementById('rejectModal')
    .classList.remove('show');

  document.getElementById('rejectReason').value = '';
}

function submitReject(){

  const reason = document
    .getElementById('rejectReason')
    .value
    .trim();

  if(!reason){
    alert('يرجى كتابة سبب الرفض');
    return;
  }

  rejectForm.querySelector(
    'input[name="rejection_note"]'
  ).value = reason;

  rejectForm.submit();
}
</script>
<div id="editModal" class="rejectModal">
  <div class="rejectBox">
    <div class="rejectTitle">تعديل طلب الإجازة</div>

    <form method="post" id="editLeaveForm">
      <?= csrf_hidden_fields() ?>

      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" id="edit_id">

      <div class="field" style="margin-bottom:12px">
        <label>نوع الإجازة</label>
        <select name="leave_type" id="edit_leave_type" class="input">
          <option value="ANNUAL">سنوية</option>
          <option value="SICK">مرضية</option>
          <option value="EMERGENCY">طارئة</option>
          <option value="OTHER">أخرى</option>
        </select>
      </div>

      <div class="field" style="margin-bottom:12px">
        <label>من</label>
        <input type="date" name="date_from" id="edit_date_from" class="input" required>
      </div>

      <div class="field" style="margin-bottom:12px">
        <label>إلى</label>
        <input type="date" name="date_to" id="edit_date_to" class="input" required>
      </div>

      <div class="field">
        <label>السبب</label>
        <textarea name="reason" id="edit_reason" class="rejectTextarea"></textarea>
      </div>

      <div class="rejectActions">
        <button type="submit" class="btn">حفظ التعديل</button>
        <button type="button" class="btn danger" onclick="closeEditModal()">إلغاء</button>
      </div>
    </form>
  </div>
</div>

<script>
function openEditModal(id, type, from, to, reason){
  document.getElementById('edit_id').value = id;
  document.getElementById('edit_leave_type').value = type || 'ANNUAL';
  document.getElementById('edit_date_from').value = from || '';
  document.getElementById('edit_date_to').value = to || '';
  document.getElementById('edit_reason').value = reason || '';

  document.getElementById('editModal').classList.add('show');
}

function closeEditModal(){
  document.getElementById('editModal').classList.remove('show');
}
</script>
<?php render_layout_end(); ?>