<?php
// finance/_layout.php
declare(strict_types=1);

/* ===== DEBUG ===== */
$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 catcher ===== */
register_shutdown_function(function () use ($debug) {
    $e = error_get_last();
    if (!$e) return;

    if (!headers_sent()) 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/SHUTDOWN\n";
    echo "Type: {$e['type']}\n";
    echo "Message: {$e['message']}\n";
    echo "File: {$e['file']}\n";
    echo "Line: {$e['line']}\n";
    echo "</pre>";
});

/* ===== Exception catcher ===== */
set_exception_handler(function (Throwable $e) use ($debug) {
    if (!headers_sent()) 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;
});

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

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/auth.php';

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

if (!function_exists('require_login')) {
    function require_login(): void {
        if (empty($_SESSION['user_id'])) {
            header("Location: /HLG-Justice-Hub/index.html?e=1");
            exit;
        }
    }
}

if (!function_exists('finance_can_manage')) {
    function finance_can_manage(): bool {
        return function_exists('can_finance')
            ? (bool)can_finance()
            : (function_exists('can_finance_fallback') ? can_finance_fallback() : false);
    }
}

if (!function_exists('can_finance_fallback')) {
    function can_finance_fallback(): bool {
        $role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
        return in_array($role, ['OWNER', 'ADMIN'], true) || !empty($_SESSION['can_finance']);
    }
}

if (!function_exists('table_cols')) {
    function table_cols(PDO $pdo, string $table): array {
        $st = $pdo->query("SHOW COLUMNS FROM `$table`");
        return $st->fetchAll(PDO::FETCH_COLUMN, 0) ?: [];
    }
}

if (!function_exists('first_existing')) {
    function first_existing(array $cols, array $candidates): ?string {
        foreach ($candidates as $c) {
            if (in_array($c, $cols, true)) return $c;
        }
        return null;
    }
}

if (!function_exists('finance_current_employee_id')) {
    function finance_current_employee_id(PDO $pdo): int {
        $empCols = table_cols($pdo, 'employees');
        $userLinkCol = first_existing($empCols, ['user_id', 'userId', 'uid']);
        if (!$userLinkCol) return 0;

        $userId = (int)($_SESSION['user_id'] ?? 0);
        $st = $pdo->prepare("SELECT id FROM employees WHERE `$userLinkCol` = ? LIMIT 1");
        $st->execute([$userId]);
        return (int)($st->fetchColumn() ?: 0);
    }
}

if (!function_exists('finance_emp_name_expr')) {
    function finance_emp_name_expr(PDO $pdo, string $alias = 'e'): string {
        $cols = table_cols($pdo, 'employees');
        $nameCol = first_existing($cols, ['full_name', 'name', 'emp_name', 'employee', 'arabic_name', 'first_name']);
        $lastCol = first_existing($cols, ['last_name', 'family_name']);

        if ($nameCol && $nameCol !== 'first_name') {
            return "NULLIF(TRIM($alias.`$nameCol`),'')";
        }
        if ($nameCol === 'first_name' && $lastCol) {
            return "NULLIF(TRIM(CONCAT(COALESCE($alias.`first_name`,''),' ',COALESCE($alias.`$lastCol`,''))),'')";
        }
        return "CONCAT('EMP#', $alias.id)";
    }
}

if (!function_exists('finance_can_print')) {
    function finance_can_print(): bool {
        return function_exists('finance_can_manage') ? finance_can_manage() : false;
    }
}

require_login();

$pdo = db();
if (!$pdo instanceof PDO) {
    if (!headers_sent()) 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);

/* ===== UI Helpers ===== */
if (!function_exists('page_header')) {
    function page_header(string $title): void {
        $who  = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
        $role = (string)($_SESSION['role'] ?? 'STAFF');

        echo "<div class='page-topbar'>";
        echo "  <div>";
        echo "    <div class='page-title'>" . h($title) . "</div>";
        echo "    <div class='page-sub'>" . h($who) . " · " . h($role) . "</div>";
        echo "  </div>";
        echo "</div>";
    }
}

if (!function_exists('finance_shell_start')) {
    function finance_shell_start(string $active = 'dashboard'): void {
        $role        = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
        $canManage   = finance_can_manage();
        $currentName = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
        $logo        = (string)($_SESSION['logo'] ?? 'https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/logomail.png');

        $is = static fn(string $k): string => $active === $k ? 'active' : '';

?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>HLG Finance</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800;900&display=swap" rel="stylesheet">

 <style>
  :root{
    --bg1:#07171d;
    --bg2:#0b2633;
    --bg3:#021d23;

    --card:rgba(255,255,255,.05);
    --card-2:rgba(255,255,255,.04);
    --line:rgba(255,255,255,.08);
    --line-soft:rgba(255,255,255,.05);

    --text:rgba(255,255,255,.94);
    --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);

    --sidebar-w:290px;
    --shadow:0 18px 40px rgba(0,0,0,.16);

    --page-bg:transparent;
    --page-card:rgba(255,255,255,.05);
    --page-line:rgba(255,255,255,.08);
    --page-ink:#ffffff;
    --page-muted:rgba(255,255,255,.68);
  }

  *,
  *::before,
  *::after{
    box-sizing:border-box;
  }

  html,
  body{
    margin:0;
    padding:0;
    width:100%;
    max-width:100%;
    overflow-x:hidden;
    font-family:Tajawal,system-ui,-apple-system,Segoe UI,Arial,sans-serif;
  }

  body{
    min-height:100vh;
    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%),
      var(--bg3);
    color:var(--page-ink);
  }

  a{
    color:inherit;
    text-decoration:none;
  }

  .app{
    display:flex;
    min-height:100vh;
    width:100%;
    max-width:100%;
    overflow-x:hidden;
  }

  .sidebar{
    width:var(--sidebar-w);
    flex:0 0 var(--sidebar-w);
    min-width:var(--sidebar-w);
    padding:18px 14px;
    border-left:1px solid var(--line);
    background:
      radial-gradient(1200px 700px at 85% 10%, #103847 0%, var(--bg1) 55%, #031018 100%);
    color:var(--text);
    position:sticky;
    top:0;
    min-height:100vh;
    overflow:visible;
    backdrop-filter:blur(10px);
  }

  .brand{
    display:flex;
    align-items:center;
    justify-content:space-between;
    padding:12px;
    border:1px solid var(--line);
    border-radius:16px;
    background:rgba(255,255,255,.04);
    margin-bottom:14px;
    gap:10px;
    box-shadow:0 12px 24px rgba(0,0,0,.12);
  }

  .brand-left{
    display:flex;
    align-items:center;
    gap:10px;
    min-width:0;
  }

  .brand-logo{
    width:44px;
    height:44px;
    border-radius:12px;
    background:rgba(255,255,255,.06);
    display:flex;
    align-items:center;
    justify-content:center;
    overflow:hidden;
    flex:0 0 44px;
    border:1px solid rgba(255,255,255,.08);
  }

  .brand-logo img{
    width:100%;
    height:100%;
    object-fit:contain;
  }

  .brand-title{
    min-width:0;
  }

  .brand-title .name{
    font-weight:700;
    letter-spacing:.2px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    color:#fff;
  }

  .brand-title .sub{
    font-size:10px;
    color:var(--muted);
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }

  .sbToggle{
    display:none;
    border:1px solid rgba(255,255,255,.18);
    background:rgba(255,255,255,.10);
    color:#fff;
    border-radius:12px;
    padding:8px 10px;
    cursor:pointer;
    font-family:inherit;
    flex:0 0 auto;
  }

  .nav{
    display:flex;
    flex-direction:column;
    gap:10px;
    margin-top:10px;
  }

  .nav a{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    padding:12px 12px;
    border-radius:16px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.03);
    transition:.15s ease;
    min-width:0;
    color:#fff;
  }

  .nav a:hover{
    transform:translateY(-1px);
    background:rgba(255,255,255,.06);
  }

  .nav a.active{
    background:linear-gradient(180deg, rgba(212,175,55,.18), rgba(212,175,55,.08));
    border-color:rgba(212,175,55,.35);
    box-shadow:0 12px 24px rgba(0,0,0,.12);
  }

  .nav a .label{
    font-weight:700;
    min-width:0;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }

  .pill{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:4px 9px;
    border-radius:10px;
    border:1px solid rgba(212,175,55,.20);
    background:rgba(212,175,55,.10);
    color:#ffd76a;
    font-size:10px;
    font-weight:700;
    white-space:nowrap;
    flex:0 0 auto;
  }

  .footerBox{
    margin-top:14px;
    padding:12px;
    border-radius:16px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.04);
  }

  .who{
    display:flex;
    justify-content:space-between;
    gap:10px;
    align-items:center;
    color:var(--muted);
    font-size:13px;
    flex-wrap:wrap;
  }

  .logout{
    margin-top:10px;
    display:block;
    text-align:center;
    padding:11px 12px;
    border-radius:16px;
    border:1px solid rgba(255,255,255,.10);
    background:rgba(255,255,255,.04);
    font-weight:800;
    color:#fff;
    transition:.16s ease;
  }

  .logout:hover{
    background:rgba(255,255,255,.07);
    transform:translateY(-1px);
  }

  .content{
    flex:1 1 auto;
    min-width:0;
    width:100%;
    max-width:100%;
    padding:18px 18px 26px;
    overflow-x:hidden;
    color:var(--page-ink);
  }

  .content > *{
    max-width:100%;
    min-width:0;
  }

  .page-topbar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    padding:14px 16px;
    border:1px solid var(--page-line);
    border-radius:18px;
    background:var(--page-card);
    box-shadow:var(--shadow);
    margin-bottom:14px;
    flex-wrap:wrap;
    backdrop-filter:blur(12px);
  }

  .page-title{
    color:#fff;
    font-weight:800;
    font-size:18px;
  }

  .page-sub{
    color:var(--page-muted);
    font-size:13px;
    margin-top:4px;
  }

  .card{
    background:var(--page-card);
    border:1px solid var(--page-line);
    border-radius:18px;
    box-shadow:var(--shadow);
    padding:16px;
    backdrop-filter:blur(12px);
  }

  .grid{
    display:grid;
    grid-template-columns:repeat(12,1fr);
    gap:14px;
  }

  .kpi{
    grid-column:span 6;
  }

  .kpi .k{
    color:var(--page-muted);
    font-size:12px;
  }

  .kpi .v{
    font-size:22px;
    font-weight:800;
    margin-top:8px;
    color:var(--gold-2);
  }

  .kpi .s{
    font-size:12px;
    color:var(--page-muted);
    margin-top:8px;
  }

  .row{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    align-items:center;
    min-width:0;
  }

  .input,
  .select{
    padding:10px 12px;
    border-radius:12px;
    border:1px solid var(--page-line);
    background:rgba(255,255,255,.05);
    outline:none;
    font-family:inherit;
    color:#fff;
  }

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

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

  .input:focus,
  .select:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
  }

  .btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    padding:10px 14px;
    border-radius:12px;
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    cursor:pointer;
    font-family:inherit;
    font-weight:700;
    box-shadow:0 12px 24px rgba(212,175,55,.16);
    transition:.18s ease;
  }

  .btn:hover{
    transform:translateY(-1px);
    box-shadow:0 16px 28px rgba(212,175,55,.22);
  }

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

  .btn.secondary:hover{
    background:rgba(255,255,255,.08);
  }

  .btn.print{
    background:#0f172a;
    color:#fff;
    border-color:#0f172a;
    box-shadow:none;
  }

  .btn.print:hover{
    opacity:.92;
    transform:none;
  }

  .print-bar{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:12px;
  }

  @media (max-width:1100px){
    .app{
      display:block;
    }

    .sidebar{
      width:100%;
      min-width:0;
      position:relative;
      min-height:auto;
      padding:14px;
    }

    .sbToggle{
      display:inline-flex;
    }

    .nav{
      display:none;
      margin-top:12px;
    }

    .sidebar.open .nav{
      display:flex;
    }

    .content{
      padding:14px;
    }
  }

  @media (max-width:680px){
    .grid{
      grid-template-columns:1fr;
    }

    .kpi{
      grid-column:span 1;
    }

    .card{
      padding:14px;
    }
  }

  @media print{
    .sidebar,
    .print-bar,
    .btn,
    form,
    .sbToggle{
      display:none !important;
    }

    .app{
      display:block !important;
    }

    .content{
      padding:0 !important;
    }

    body{
      background:#fff !important;
      color:#000 !important;
    }

    .card{
      box-shadow:none !important;
      border:1px solid #ddd !important;
      background:#fff !important;
      color:#000 !important;
      break-inside:avoid;
    }

    .page-title,
    .kpi .v{
      color:#000 !important;
    }
  }
</style>
</head>
<body>
<div class="app">
  <aside class="sidebar" id="financeSide">
    <div class="brand">
      <div class="brand-left">
        <div class="brand-logo">
          <img src="<?= h($logo) ?>" alt="HLG">
        </div>
        <div class="brand-title">
          <div class="name">مجموعة حمدان القانونية</div>
          <div class="sub">الرواتب والمكافآت والخصومات</div>
        </div>
      </div>

      <button class="sbToggle" type="button" onclick="document.getElementById('financeSide').classList.toggle('open')">
        القائمة
      </button>
    </div>

    <nav class="nav">
      <?php if (in_array($role, ['OWNER','ADMIN'], true)): ?>
        <a class="<?= $is('index') ?>" href="index.php">
          <span class="label">لوحة المالية</span>
          <span class="pill">الإجمالي</span>
        </a>
      <?php endif; ?>

      <a class="<?= $is('salaries') ?>" href="salaries.php">
        <span class="label">الرواتب والبدلات</span>
        <span class="pill"><?= $canManage ? 'إدارة' : 'عرض' ?></span>
      </a>

      <a class="<?= $is('bonuses') ?>" href="bonuses.php">
        <span class="label">المكافآت</span>
        <span class="pill"><?= $canManage ? 'إضافة' : 'عرض' ?></span>
      </a>

      <a class="<?= $is('deductions') ?>" href="deductions.php">
        <span class="label">الخصومات</span>
        <span class="pill"><?= $canManage ? 'إضافة' : 'عرض' ?></span>
      </a>

      <a class="<?= $is('payroll') ?>" href="payroll.php">
        <span class="label">كشف الرواتب</span>
        <span class="pill"><?= $canManage ? 'شهري' : 'مستحقاتي' ?></span>
      </a>

      <a class="<?= $is('advances') ?>" href="advances.php">
        <span class="label">السلف</span>
        <span class="pill"><?= $canManage ? 'إدارة' : 'عرض' ?></span>
      </a>

      <a class="<?= $is('my') ?>" href="my_pay.php">
        <span class="label">راتبي</span>
        <span class="pill">خصوصي</span>
      </a>

      <a href="../dashboard.php">
        <span class="label">العودة الى الرئيسية</span>
        <span class="pill">الرئيسية</span>
      </a>
    </nav>

    <div class="footerBox">
      <div class="who">
        <div><?= h($currentName) ?></div>
        <div><?= h($role) ?></div>
      </div>

      <a class="logout" href="../logout.php">خروج</a>
    </div>
  </aside>

  <main class="content">
<?php
    }
}

if (!function_exists('finance_shell_end')) {
    function finance_shell_end(): void { ?>
  </main>
</div>
</body>
</html>
<?php
    }
}