<?php
// includes/header.php
requireLogin();
$user  = currentUser();
if (isset($_GET['dismiss_update'])) { $_SESSION['dismissed_update_id'] = (int)$_GET['dismiss_update']; }
$flash = flashHtml();
$page  = $page ?? 'Dashboard';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page ?> – <?= APP_NAME ?></title>
<link rel="icon" type="image/x-icon" href="<?= BASE_URL ?>/assets/img/favicon.ico">
<link rel="icon" type="image/png" sizes="32x32" href="<?= BASE_URL ?>/assets/img/logo-mark-32.png">
<link rel="apple-touch-icon" sizes="180x180" href="<?= BASE_URL ?>/assets/img/apple-touch-icon.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@2.44.0/tabler-icons.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css?v=<?= @filemtime(__DIR__ . '/../assets/css/style.css') ?: time() ?>">
</head>
<body>

<!-- Global loading overlay: shown while any create/edit/delete action is in flight -->
<div class="pc-loading-overlay" id="pcLoadingOverlay" style="display:none">
  <div class="pc-loading-box">
    <div class="pc-loading-spinner"></div>
    <div class="pc-loading-text" id="pcLoadingText">Please wait…</div>
  </div>
</div>

<!-- TOP NAVBAR -->
<nav class="navbar navbar-dark pc-topbar px-3 d-flex align-items-center">
  <div class="d-flex align-items-center gap-2">
    <button class="btn btn-link text-white p-0 me-2" id="sidebarToggle">
      <i class="ti ti-menu-2 fs-5"></i>
    </button>
    <div class="pc-logo-badge"><img src="<?= BASE_URL ?>/assets/img/logo-mark-64.png" alt="<?= APP_NAME ?>"></div>
    <span class="pc-brand-word text-white">
      Seyalix <span style="font-weight:400">HRMS</span>
      <small class="d-none d-md-block">Empowering People. Simplifying HR.</small>
    </span>
  </div>
  <div class="ms-auto d-flex align-items-center gap-3">
    <span class="text-white-50 small d-none d-md-block"><?= date('D, d M Y') ?></span>

    <?php if ($user['role'] !== 'vendor'): ?>
    <!-- Bell #1: pending approvals needing action (leave/permission/late) -->
    <div class="dropdown">
      <button class="btn btn-link text-white position-relative p-0" data-bs-toggle="dropdown" id="pcBellBtn" title="Pending approvals">
        <i class="ti ti-bell fs-5"></i>
        <span id="pcBellBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger d-none" style="font-size:9px"></span>
      </button>
      <ul class="dropdown-menu dropdown-menu-end shadow" style="min-width:300px;max-height:360px;overflow-y:auto" id="pcBellMenu">
        <li class="dropdown-header fw-bold">Pending Approvals</li>
        <li id="pcBellEmpty" class="dropdown-item small text-muted py-2">No pending approvals</li>
      </ul>
    </div>

    <!-- Bell #2: personal notifications (apply/approve/reject alerts etc) -->
    <!-- Always shown. Logins with no linked employee record (some
         admin/superadmin accounts) can't have personal notification rows
         (the table is keyed on employee_id), so the JS below checks
         HAS_EMP_LINK and shows a plain explanatory message for them
         instead of trying to fetch/mark and erroring. -->
    <div class="dropdown">
      <button class="btn btn-link text-white position-relative p-0" data-bs-toggle="dropdown" id="notifBellBtn" title="Notifications">
        <i class="ti ti-message-circle-2 fs-5"></i>
        <span id="notifBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger d-none" style="font-size:9px"></span>
      </button>
      <div class="dropdown-menu dropdown-menu-end shadow p-0" style="min-width:320px;max-height:420px;overflow-y:auto" id="notifDropdown">
        <div class="d-flex align-items-center justify-content-between px-3 py-2 border-bottom sticky-top bg-white">
          <span class="fw-bold">Notifications</span>
          <div class="d-flex gap-2">
            <a href="#" class="small text-primary" id="notifMarkAllRead">Mark all read</a>
            <a href="#" class="small text-muted" id="notifMarkAllUnread">Mark all unread</a>
          </div>
        </div>
        <div id="notifList">
          <div class="text-center text-muted small py-3">Loading…</div>
        </div>
      </div>
    </div>
    <?php endif; ?>


    <div class="dropdown">
      <button class="btn btn-link text-white p-0 d-flex align-items-center gap-2" data-bs-toggle="dropdown">
        <div class="pc-avatar-sm"><?= strtoupper(substr($user['name'], 0, 2)) ?></div>
        <span class="small d-none d-md-inline"><?= clean($user['name']) ?></span>
        <i class="ti ti-chevron-down" style="font-size:12px"></i>
      </button>
      <ul class="dropdown-menu dropdown-menu-end shadow">
        <li class="dropdown-header"><?= clean($user['name']) ?><br><small class="text-muted"><?= ucfirst($user['role']) ?></small></li>
        <li><hr class="dropdown-divider"></li>
        <?php if ($user['role'] !== 'vendor'): ?>
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/modules/employees/profile.php"><i class="ti ti-user me-2"></i>My Profile</a></li>
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/modules/attendance/my_attendance.php"><i class="ti ti-calendar-stats me-2"></i>My Attendance</a></li>
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/modules/leave/my_leaves.php"><i class="ti ti-beach me-2"></i>My Leaves</a></li>
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/modules/attendance/onduty.php"><i class="ti ti-briefcase me-2"></i>On Duty</a></li>
        <?php endif; ?>
        <li><a class="dropdown-item" href="<?= BASE_URL ?>/change_password.php"><i class="ti ti-key me-2"></i>Change Password</a></li>
        <li><hr class="dropdown-divider"></li>
        <li><a class="dropdown-item text-danger" href="<?= BASE_URL ?>/logout.php"><i class="ti ti-logout me-2"></i>Logout</a></li>
      </ul>
    </div>
  </div>
</nav>

<div class="pc-main-wrap">

<!-- SIDEBAR -->
<nav class="pc-sidebar" id="pcSidebar">
  <div class="pc-sidebar-search px-3 py-2">
    <input type="text" class="form-control form-control-sm" placeholder="Search module..." id="navSearch">
  </div>
  <div class="pc-sidebar-nav" id="sidebarNav">

    <?php if ($user['role'] === 'vendor'): ?>
    <div class="pc-nav-section">Vendor</div>
    <a href="<?= BASE_URL ?>/modules/companies/index.php" class="pc-nav-item <?= $page==='License Management'?'active':'' ?>">
      <i class="ti ti-building-skyscraper"></i> Organizations &amp; Licenses
    </a>
    <?php else: ?>

    <div class="pc-nav-section">Main</div>
    <a href="<?= BASE_URL ?>/dashboard.php" class="pc-nav-item <?= $page==='Dashboard'?'active':'' ?>">
      <i class="ti ti-dashboard"></i> Dashboard
    </a>
    <a href="<?= BASE_URL ?>/modules/employees/orgchart.php" class="pc-nav-item <?= $page==='Org Chart'?'active':'' ?>">
      <i class="ti ti-sitemap"></i> Organization Chart
    </a>

    <?php /* ── Feature-flagged menu item example ──────────────────
    Only show a nav link (and only let the page load — pair with
    requireFeature() at the top of that module file) for organizations
    the vendor has switched this feature ON for, e.g. Company A got a
    new module but Company B/C haven't been given it yet. Create the
    flag in the vendor console (Companies & Licenses > Feature Flags)
    first, then copy this block wherever the real link should go:

    if (hasFeature('your_feature_key')):
    ?>
    <a href="<?= BASE_URL ?>/modules/your_module/index.php" class="pc-nav-item">
      <i class="ti ti-sparkles"></i> Your New Feature
    </a>
    <?php endif; */ ?>

    <div class="pc-nav-section">Employee</div>
    <div class="pc-nav-item pc-has-sub <?= in_array($page,['Employee List','Add Employee','Employee Profile','Transfer','F&F Settlement'])?'expanded':'' ?>" data-sub="empSub">
      <i class="ti ti-users"></i> Employee Master <i class="ti ti-chevron-down pc-chevron ms-auto"></i>
    </div>
    <div class="pc-subnav" id="empSub">
      <a href="<?= BASE_URL ?>/modules/employees/list.php" class="pc-subnav-item">Employee List</a>
      <a href="<?= BASE_URL ?>/modules/employees/create.php" class="pc-subnav-item">Add Employee</a>
      <a href="<?= BASE_URL ?>/modules/employees/transfer.php" class="pc-subnav-item">Transfer</a>
      <a href="<?= BASE_URL ?>/modules/separation/index.php" class="pc-subnav-item">F&amp;F Settlement</a>
    </div>
    <a href="<?= BASE_URL ?>/modules/employees/assign.php" class="pc-nav-item"><i class="ti ti-clipboard-list"></i> Employee Assignment</a>
    <a href="<?= BASE_URL ?>/modules/employees/accounts.php" class="pc-nav-item"><i class="ti ti-credit-card"></i> Account Linking</a>

    <div class="pc-nav-section">Attendance</div>
    <a href="<?= BASE_URL ?>/modules/attendance/muster.php" class="pc-nav-item"><i class="ti ti-calendar-stats"></i> Muster Management <span class="badge bg-warning ms-auto text-dark" style="font-size:9px">3</span></a>
    <a href="<?= BASE_URL ?>/modules/attendance/marking.php" class="pc-nav-item"><i class="ti ti-fingerprint"></i> Attendance Marking</a>
    <a href="<?= BASE_URL ?>/modules/attendance/regularization.php" class="pc-nav-item"><i class="ti ti-edit"></i> Regularization</a>
    <a href="<?= BASE_URL ?>/modules/attendance/biometric_upload.php" class="pc-nav-item"><i class="ti ti-upload"></i> Biometric Upload</a>
    <a href="<?= BASE_URL ?>/modules/attendance/muster_report.php" class="pc-nav-item"><i class="ti ti-report"></i> Muster Report</a>
    <a href="<?= BASE_URL ?>/modules/attendance/permission.php" class="pc-nav-item"><i class="ti ti-clock-plus"></i> Permission</a>
    <a href="<?= BASE_URL ?>/modules/attendance/late_processing.php" class="pc-nav-item"><i class="ti ti-alarm"></i> Late Arrival Processing</a>
    <a href="<?= BASE_URL ?>/modules/company/leave_policy.php" class="pc-nav-item"><i class="ti ti-calendar-due"></i> Leave Policy</a>
    <a href="<?= BASE_URL ?>/modules/attendance/onduty.php" class="pc-nav-item"><i class="ti ti-briefcase"></i> On Duty</a>
    <!-- <a href="<?= BASE_URL ?>/modules/leave/index.php" class="pc-nav-item"><i class="ti ti-beach"></i> Leave Management</a> -->
    <a href="<?= BASE_URL ?>/modules/leave/index.php" class="pc-nav-item"><i class="ti ti-beach"></i> Leave Management</a>
    <a href="<?= BASE_URL ?>/modules/leave/bulk_balance.php" class="pc-nav-item"><i class="ti ti-file-upload"></i> Leave Balance Upload</a>
    <a href="<?= BASE_URL ?>/modules/attendance/timesheet.php" class="pc-nav-item"><i class="ti ti-clock"></i> Timesheet</a>
    <a href="<?= BASE_URL ?>/modules/attendance/timesheet.php" class="pc-nav-item"><i class="ti ti-clock"></i> Timesheet</a>


    <div class="pc-nav-section">Payroll</div>
    <div class="pc-nav-item pc-has-sub" data-sub="paySub">
      <i class="ti ti-receipt"></i> Payroll <i class="ti ti-chevron-down pc-chevron ms-auto"></i>
    </div>
    <div class="pc-subnav" id="paySub">
      <a href="<?= BASE_URL ?>/modules/payroll/paycodes.php" class="pc-subnav-item">Pay Codes</a>
      <a href="<?= BASE_URL ?>/modules/payroll/calculate.php" class="pc-subnav-item">Salary Calculation</a>
      <a href="<?= BASE_URL ?>/modules/payroll/arrears.php" class="pc-subnav-item">Arrear Calculation</a>
      <a href="<?= BASE_URL ?>/modules/payroll/leave_encashment.php" class="pc-subnav-item">Leave Encashment</a>
      <a href="<?= BASE_URL ?>/modules/payroll/lta.php" class="pc-subnav-item">Leave Travel</a>
      <a href="<?= BASE_URL ?>/modules/payroll/bonus.php" class="pc-subnav-item">Bonus &amp; Incentives</a>
      <a href="<?= BASE_URL ?>/modules/payroll/gratuity.php" class="pc-subnav-item">Gratuity</a>
      <a href="<?= BASE_URL ?>/modules/payroll/post_salary.php" class="pc-subnav-item">Post Salary</a>
      <a href="<?= BASE_URL ?>/modules/payroll/send_payslip_email.php" class="pc-subnav-item">Send Payslip by Email</a>
      <a href="<?= BASE_URL ?>/modules/payroll/disbursement.php" class="pc-subnav-item">Disbursement</a>
    </div>
    <a href="<?= BASE_URL ?>/modules/advance/index.php" class="pc-nav-item"><i class="ti ti-cash"></i> Advance Application</a>

    <div class="pc-nav-section">TDS &amp; Tax</div>
    <div class="pc-nav-item pc-has-sub" data-sub="tdsSub">
      <i class="ti ti-file-invoice"></i> TDS Management <i class="ti ti-chevron-down pc-chevron ms-auto"></i>
    </div>
    <div class="pc-subnav" id="tdsSub">
      <a href="<?= BASE_URL ?>/modules/tds/tax_slab.php" class="pc-subnav-item">Tax Slab</a>
      <a href="<?= BASE_URL ?>/modules/tds/tds_heads.php" class="pc-subnav-item">TDS Heads</a>
      <a href="<?= BASE_URL ?>/modules/tds/adb_rules.php" class="pc-subnav-item">ADB Rules</a>
      <a href="<?= BASE_URL ?>/modules/tds/investment.php" class="pc-subnav-item">Investment Declaration</a>
      <a href="<?= BASE_URL ?>/modules/tds/calculate.php" class="pc-subnav-item">TDS Calculation</a>
      <a href="<?= BASE_URL ?>/modules/tds/monthly_chart.php" class="pc-subnav-item">TDS Monthly Chart</a>
      <a href="<?= BASE_URL ?>/modules/tds/form16.php" class="pc-subnav-item">Form 16</a>
    </div>

    <div class="pc-nav-section">Statutory</div>
    <a href="<?= BASE_URL ?>/modules/statutory/pf.php" class="pc-nav-item"><i class="ti ti-building-bank"></i> PF / ECR</a>
    <a href="<?= BASE_URL ?>/modules/statutory/esi.php" class="pc-nav-item"><i class="ti ti-heart-rate-monitor"></i> ESI</a>
    <a href="<?= BASE_URL ?>/modules/statutory/pt.php" class="pc-nav-item"><i class="ti ti-building-community"></i> Professional Tax</a>

    <div class="pc-nav-section">HR Operations</div>
    <a href="<?= BASE_URL ?>/modules/recruitment/index.php" class="pc-nav-item"><i class="ti ti-user-plus"></i> Recruitment</a>
    <a href="<?= BASE_URL ?>/modules/appraisal/index.php" class="pc-nav-item"><i class="ti ti-trophy"></i> Appraisal</a>
    <a href="<?= BASE_URL ?>/modules/training/index.php" class="pc-nav-item"><i class="ti ti-school"></i> Training</a>
    <a href="<?= BASE_URL ?>/modules/expense/index.php" class="pc-nav-item"><i class="ti ti-credit-card"></i> Expense Booking</a>
    <a href="<?= BASE_URL ?>/modules/notice/index.php" class="pc-nav-item"><i class="ti ti-bell"></i> Notice Board</a>

    <div class="pc-nav-section">Reports</div>
    <div class="pc-nav-item pc-has-sub" data-sub="rptSub">
      <i class="ti ti-chart-bar"></i> Reports <i class="ti ti-chevron-down pc-chevron ms-auto"></i>
    </div>
    <div class="pc-subnav" id="rptSub">
      <a href="<?= BASE_URL ?>/modules/reports/monthly_summary.php" class="pc-subnav-item">Monthly Summary Report</a>
      <a href="<?= BASE_URL ?>/modules/reports/hr_reports.php" class="pc-subnav-item">HR Reports</a>
      <a href="<?= BASE_URL ?>/modules/reports/statutory.php" class="pc-subnav-item">Statutory</a>
      <a href="<?= BASE_URL ?>/modules/reports/earning_deduction.php" class="pc-subnav-item">Earning &amp; Deduction</a>
      <a href="<?= BASE_URL ?>/modules/reports/custom.php" class="pc-subnav-item">Custom Report</a>
      <a href="<?= BASE_URL ?>/modules/reports/summary.php" class="pc-subnav-item">Summary Report</a>
      <a href="<?= BASE_URL ?>/modules/reports/letter.php" class="pc-subnav-item">Letter Generation</a>
      <a href="<?= BASE_URL ?>/modules/reports/letter_templates.php" class="pc-subnav-item">Letter Templates</a>
      <a href="<?= BASE_URL ?>/modules/reports/bulk_upload.php" class="pc-subnav-item">Bulk Upload</a>
    </div>

    <div class="pc-nav-section">Configuration</div>
    <a href="<?= BASE_URL ?>/modules/company/index.php" class="pc-nav-item"><i class="ti ti-building"></i> Company Management</a>
    <a href="<?= BASE_URL ?>/modules/company/branding.php" class="pc-nav-item"><i class="ti ti-photo"></i> Company Branding &amp; Logo</a>
    <a href="<?= BASE_URL ?>/modules/company/email_settings.php" class="pc-nav-item"><i class="ti ti-mail"></i> Email Settings</a>
    <?php if (hasRole('superadmin','admin')): ?>
    <a href="<?= BASE_URL ?>/modules/organization/companies.php" class="pc-nav-item"><i class="ti ti-buildings"></i> My Companies</a>
    <?php endif; ?>
    <a href="<?= BASE_URL ?>/modules/users/index.php" class="pc-nav-item"><i class="ti ti-users-group"></i> User Management</a>
    <div class="pc-nav-item pc-has-sub" data-sub="cfgSub">
      <i class="ti ti-settings"></i> Configuration <i class="ti ti-chevron-down pc-chevron ms-auto"></i>
    </div>
    <div class="pc-subnav" id="cfgSub">
      <a href="<?= BASE_URL ?>/modules/configuration/departments.php" class="pc-subnav-item">Departments</a>
      <a href="<?= BASE_URL ?>/modules/configuration/locations.php" class="pc-subnav-item">Locations</a>
      <a href="<?= BASE_URL ?>/modules/configuration/designations.php" class="pc-subnav-item">Designations</a>
      <a href="<?= BASE_URL ?>/modules/configuration/salary_heads.php" class="pc-subnav-item">Salary Heads</a>
      <a href="<?= BASE_URL ?>/modules/configuration/leave_types.php" class="pc-subnav-item">Leave Types</a>
      <a href="<?= BASE_URL ?>/modules/configuration/shifts.php" class="pc-subnav-item">Shifts</a>
      <a href="<?= BASE_URL ?>/modules/configuration/holidays.php" class="pc-subnav-item">Holiday Calendar</a>
      <a href="<?= BASE_URL ?>/modules/configuration/menu_rights.php" class="pc-subnav-item">Menu Rights</a>
      <a href="<?= BASE_URL ?>/modules/configuration/pf_esi_setup.php" class="pc-subnav-item">PF / ESI Setup</a>
      <a href="<?= BASE_URL ?>/modules/configuration/gratuity_setup.php" class="pc-subnav-item">Gratuity Setup</a>
    </div>
    <a href="<?= BASE_URL ?>/modules/support/index.php" class="pc-nav-item"><i class="ti ti-headset"></i> Support Desk</a>

    <?php endif; ?>
  </div><!-- /sidebarNav -->
</nav>

<!-- MAIN CONTENT -->
<div class="pc-content" id="pcContent">
  <div class="pc-page-header">
    <div>
      <h5 class="mb-0 fw-bold"><?= $page ?></h5>
      <nav aria-label="breadcrumb"><ol class="breadcrumb mb-0" style="font-size:11px">
        <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/dashboard.php">Home</a></li>
        <li class="breadcrumb-item active"><?= $page ?></li>
      </ol></nav>
    </div>
    <div class="ms-auto d-flex align-items-center gap-2">
      <?= $headerActions ?? '' ?>
    </div>
  </div>
  <?php
  // Product update popup: vendor pushes an update from the vendor
  // console (Push Product Update card), and EVERY user in EVERY
  // organization/company sees a popup about it — like the "update
  // available" popup on a phone — the next time they load a page.
  // They click "Got it" to acknowledge; it won't pop up again for that
  // same update, but WILL pop up again for the next one that's pushed.
  if ($user['role'] !== 'vendor') {
      $db = Database::getInstance();
      $latestUpdate = $db->fetchOne("SELECT * FROM product_updates WHERE is_active=1 ORDER BY id DESC LIMIT 1");
      if ($latestUpdate && (int)($_SESSION['dismissed_update_id'] ?? 0) !== (int)$latestUpdate['id']):
  ?>
  <div class="modal fade" id="productUpdateModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h6 class="modal-title"><i class="ti ti-sparkles me-2 text-primary"></i>What's New — v<?= clean($latestUpdate['version']) ?></h6>
        </div>
        <div class="modal-body">
          <div class="fw-semibold mb-1"><?= clean($latestUpdate['title']) ?></div>
          <div class="small text-muted"><?= clean($latestUpdate['message']) ?></div>
        </div>
        <div class="modal-footer">
          <a href="?dismiss_update=<?= (int)$latestUpdate['id'] ?>" class="btn btn-pc btn-sm">Got it</a>
        </div>
      </div>
    </div>
  </div>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      new bootstrap.Modal(document.getElementById('productUpdateModal')).show();
    });
  </script>
  <?php endif; } ?>
  <?= $flash ?>
  <div class="pc-page-body">
