<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
include 'config.php';

require_once 'vendor/autoload.php';
require_once 'fpdf/fpdf.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if (!isset($_SESSION['user_id'])) die("Access denied");

$username_session = $_SESSION['username'] ?? 'Admin';
function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }

/* ================= EMPLOYEES ================= */
$employees = $conn->query("
    SELECT id AS emp_id, first_name AS emp_name
    FROM users ORDER BY first_name
");

/* ================= OT SETTINGS ================= */
$settings = $conn->query("SELECT * FROM ot_settings WHERE id=1")->fetch_assoc();
$working_days  = (int)$settings['working_days'];
$working_hours = (float)$settings['working_hours'];

/* ================= FLASH ================= */
$msg = $_SESSION['msg'] ?? '';
$err = $_SESSION['err'] ?? '';
unset($_SESSION['msg'], $_SESSION['err']);

/* ================= SAVE SETTINGS ================= */
if (isset($_POST['save_settings'])) {
    $stmt = $conn->prepare("UPDATE ot_settings SET working_days=?, working_hours=? WHERE id=1");
    $stmt->bind_param("id", $_POST['working_days'], $_POST['working_hours']);
    $stmt->execute();
    $_SESSION['msg'] = "OT settings updated";
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* ================= ADD / UPDATE OT ================= */
if (isset($_POST['add_ot']) || isset($_POST['update_ot'])) {
    $emp_id  = (int)$_POST['emp_id'];
    $ot_date = $_POST['ot_date'];
    $month   = date('Y-m', strtotime($ot_date));
    $edit_id = $_POST['edit_id'] ?? '';

    if (!$edit_id) {
        $chk = $conn->prepare("SELECT id FROM ot_entries WHERE emp_id=? AND ot_date=?");
        $chk->bind_param("is", $emp_id, $ot_date);
        $chk->execute();
        $chk->store_result();
        if ($chk->num_rows > 0) {
            $_SESSION['err'] = "OT already exists for this employee on selected date";
            header("Location: ".$_SERVER['PHP_SELF']); exit;
        }
    }

    if ($edit_id) {
        $stmt = $conn->prepare("
            UPDATE ot_entries SET
            emp_id=?, ot_date=?, month_year=?, salary=?, per_day=?,
            ot_hours=?, ot_days=?, ot_salary=?
            WHERE id=?
        ");
        $stmt->bind_param("issdddddi", $emp_id,$ot_date,$month,$_POST['salary'],$_POST['per_day'],$_POST['ot_hours'],$_POST['ot_days'],$_POST['ot_salary'],$edit_id);
        $_SESSION['msg'] = "OT updated";
    } else {
        $stmt = $conn->prepare("
            INSERT INTO ot_entries
            (emp_id,ot_date,month_year,salary,per_day,ot_hours,ot_days,ot_salary)
            VALUES (?,?,?,?,?,?,?,?)
        ");
        $stmt->bind_param("issddddd", $emp_id,$ot_date,$month,$_POST['salary'],$_POST['per_day'],$_POST['ot_hours'],$_POST['ot_days'],$_POST['ot_salary']);
        $_SESSION['msg'] = "OT added";
    }
    $stmt->execute();
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* ================= DELETE ================= */
if (isset($_GET['delete'])) {
    $stmt = $conn->prepare("DELETE FROM ot_entries WHERE id=?");
    $stmt->bind_param("i", $_GET['delete']);
    $stmt->execute();
    $_SESSION['msg'] = "OT deleted";
    header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* ================= EDIT FETCH ================= */
$edit_data = null;
if (isset($_GET['edit'])) {
    $edit_data = $conn->query("SELECT * FROM ot_entries WHERE id=".(int)$_GET['edit'])->fetch_assoc();
}

/* ================= FILTER ================= */
$filter_emp   = $_GET['emp_id'] ?? '';
$filter_month = $_GET['month']  ?? '';
$from         = $_GET['from']   ?? '';
$to           = $_GET['to']     ?? '';

$where = [];
if ($filter_emp)   $where[] = "o.emp_id=".(int)$filter_emp;
if ($filter_month) $where[] = "o.month_year='".$conn->real_escape_string($filter_month)."'";
if ($from && $to)  $where[] = "o.ot_date BETWEEN '$from' AND '$to'";
$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

/* ================= EXPORT ================= */
if (isset($_GET['export'])) {
    $type = $_GET['export'];
    $sql  = "SELECT o.ot_date, u.first_name AS employee, o.ot_hours, o.ot_days, o.ot_salary
             FROM ot_entries o LEFT JOIN users u ON u.id=o.emp_id $where_sql ORDER BY o.ot_date";
    $res  = $conn->query($sql);

    if ($type === 'csv') {
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=ot_report.csv");
        $out = fopen("php://output", "w");
        fputcsv($out, ['Date','Employee','Hours','Days','Amount']);
        while ($r = $res->fetch_assoc()) fputcsv($out, $r);
        fclose($out); exit;
    }
    if ($type === 'xlsx') {
        $sheet = new Spreadsheet(); $ws = $sheet->getActiveSheet();
        $ws->fromArray(['Date','Employee','Hours','Days','Amount'], null, 'A1');
        $row = 2;
        while ($r = $res->fetch_assoc()) $ws->fromArray(array_values($r), null, 'A'.$row++);
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header("Content-Disposition: attachment; filename=ot_report.xlsx");
        (new Xlsx($sheet))->save("php://output"); exit;
    }
    if ($type === 'pdf') {
        $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','B',10);
        foreach (['Date','Employee','Hours','Days','Amount'] as $hd) $pdf->Cell(38,8,$hd,1);
        $pdf->Ln(); $pdf->SetFont('Arial','',9);
        while ($r = $res->fetch_assoc()) { foreach ($r as $v) $pdf->Cell(38,8,$v,1); $pdf->Ln(); }
        $pdf->Output('D','ot_report.pdf'); exit;
    }
}

/* ================= SUMMARY STATS ================= */
$total_ot_q = $conn->query("SELECT SUM(ot_hours) AS th, SUM(ot_days) AS td, SUM(ot_salary) AS ts FROM ot_entries $where_sql");
$ot_totals  = $total_ot_q->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · OT Dashboard</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=Sora:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
  --ink:        #0f172a;
  --ink-2:      #334155;
  --muted:      #94a3b8;
  --border:     #e2e8f0;
  --surface:    #ffffff;
  --bg:         #f1f5f9;
  --sidebar-bg: #0f172a;
  --sidebar-w:  260px;
  --radius:     12px;
  --radius-lg:  18px;
  --shadow:     0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  --shadow-md:  0 4px 8px rgba(15,23,42,.08), 0 12px 40px rgba(15,23,42,.10);
  --primary:    #1d4ed8;
  --primary-lt: #3b82f6;
  --primary-bg: #eff6ff;
  --green:      #059669;
  --green-bg:   #ecfdf5;
  --red:        #dc2626;
  --red-bg:     #fef2f2;
  --amber:      #d97706;
  --amber-bg:   #fffbeb;
  --violet:     #7c3aed;
  --violet-bg:  #f5f3ff;
  --cyan:       #0891b2;
  --cyan-bg:    #ecfeff;
  font-family: 'Sora', system-ui, sans-serif;
}

html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -webkit-font-smoothing: antialiased; }

.layout { display: flex; min-height: 100vh; }

/* ── SIDEBAR ── */
.sidebar {
  width: var(--sidebar-w); background: var(--sidebar-bg);
  position: fixed; inset: 0 auto 0 0; z-index: 200;
  display: flex; flex-direction: column;
  overflow-y: auto; overflow-x: hidden;
  transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none;
}
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand {
  padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px;
  border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px;
}
.brand-logo {
  width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1);
  border-radius: 8px; display: flex; align-items: center; justify-content: center;
  font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0;
}
.brand-name { font-size: 15px; font-weight: 700; color: #fff; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-item { list-style: none; }
.nav-link, .nav-dropdown-toggle {
  display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px;
  color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500;
  cursor: pointer; border: none; background: none; width: 100%; text-align: left;
  transition: background .15s, color .15s;
}
.nav-link:hover, .nav-dropdown-toggle:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width: 16px; text-align: center; font-size: 13px; }
.nav-dropdown-toggle .arrow { margin-left: auto; transition: transform .2s; font-size: 10px; }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height: 600px; }
.nav-submenu .nav-link { font-size: 12px; padding: 6px 10px; color: rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color: #fff; background: rgba(255,255,255,.05); }
.sidebar-footer { margin-top: auto; padding: 12px; border-top: 1px solid rgba(255,255,255,.06); }

/* ── CONTENT ── */
.content { flex: 1; margin-left: var(--sidebar-w); min-width: 0; display: flex; flex-direction: column; transition: margin .3s cubic-bezier(.4,0,.2,1); }
.content.expanded { margin-left: 0; }

/* ── TOPBAR ── */
.topbar {
  height: 60px; background: var(--surface); border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px; padding: 0 24px;
  position: sticky; top: 0; z-index: 100;
}
.hamburger-btn {
  width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border);
  background: var(--surface); display: flex; align-items: center; justify-content: center;
  cursor: pointer; color: var(--ink-2); font-size: 15px; flex-shrink: 0; transition: background .15s;
}
.hamburger-btn:hover { background: var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.topbar-spacer { flex: 1; }
.topbar-user { display:flex; align-items:center; gap:8px; font-size:13px; color:var(--ink-2); font-weight:500; }
.topbar-avatar {
  width: 30px; height: 30px; border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6, #6366f1);
  display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700;
}

/* ── PAGE ── */
.page { padding: 24px; flex: 1; }
.page-header { margin-bottom: 24px; display:flex; align-items:flex-start; justify-content:space-between; flex-wrap:wrap; gap:12px; }
.page-title  { font-size: 22px; font-weight: 700; color: var(--ink); letter-spacing: -.4px; }
.page-subtitle { font-size: 13px; color: var(--muted); margin-top: 2px; }

/* ── ALERTS ── */
.alert {
  padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500;
  display: flex; align-items: flex-start; gap: 10px; margin-bottom: 20px;
  border: 1px solid transparent; animation: fadeUp .25s ease;
}
.alert-success { background: #d1fae5; border-color: #6ee7b7; color: #065f46; }
.alert-danger   { background: var(--red-bg); border-color: #fca5a5; color: #991b1b; }
@keyframes fadeUp { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }

/* ── STATS ── */
.stats-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:14px; margin-bottom:24px; }
.scard { background:var(--surface); border-radius:var(--radius); padding:18px 20px; box-shadow:var(--shadow); border:1px solid var(--border); position:relative; overflow:hidden; transition:transform .2s,box-shadow .2s; }
.scard:hover { transform:translateY(-3px); box-shadow:var(--shadow-md); }
.scard::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; border-radius:3px 3px 0 0; }
.scard.blue::before   { background:var(--primary-lt); }
.scard.green::before  { background:var(--green); }
.scard.amber::before  { background:var(--amber); }
.scard.violet::before { background:var(--violet); }
.scard-icon { width:40px; height:40px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:.9rem; margin-bottom:14px; }
.scard-icon.blue   { background:var(--primary-bg); color:var(--primary); }
.scard-icon.green  { background:var(--green-bg);   color:var(--green); }
.scard-icon.amber  { background:var(--amber-bg);   color:var(--amber); }
.scard-icon.violet { background:var(--violet-bg);  color:var(--violet); }
.scard-val   { font-size:1.8rem; font-weight:700; line-height:1; color:var(--ink); }
.scard-label { font-size:.72rem; color:var(--muted); font-weight:600; margin-top:4px; text-transform:uppercase; letter-spacing:.4px; }
.scard-sub   { font-size:.72rem; color:var(--ink-2); margin-top:3px; }

/* ── CARD ── */
.card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; margin-bottom:24px; }
.card-header { padding:14px 20px; border-bottom:1px solid var(--border); display:flex; align-items:center; gap:8px; }
.card-header-icon { width:32px; height:32px; border-radius:8px; display:flex; align-items:center; justify-content:center; font-size:.8rem; }
.card-title { font-size:14px; font-weight:700; color:var(--ink); }
.card-body  { padding:20px; }

/* ── FORM ELEMENTS ── */
.form-label { display:block; font-size:.75rem; font-weight:700; text-transform:uppercase; letter-spacing:.8px; color:var(--muted); margin-bottom:5px; }
.form-input, .form-select {
  width:100%; border:1px solid var(--border); border-radius:8px;
  padding:8px 12px; font-size:13px; font-family:'Sora',sans-serif;
  color:var(--ink); background:var(--bg); outline:none;
  transition:border-color .15s,box-shadow .15s;
}
.form-input:focus, .form-select:focus {
  border-color:var(--primary-lt); box-shadow:0 0 0 3px rgba(59,130,246,.12); background:var(--surface);
}
.form-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:14px; }
.form-row-settings { display:grid; grid-template-columns:1fr 1fr auto; gap:14px; align-items:end; }

/* ── TABLE ── */
.table-wrap { overflow-x:auto; }
table.data-table { width:100%; border-collapse:collapse; }
table.data-table th { background:#f8fafc; padding:10px 14px; font-size:.7rem; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.6px; border-bottom:1px solid var(--border); text-align:left; white-space:nowrap; }
table.data-table td { padding:11px 14px; font-size:.83rem; color:var(--ink); border-bottom:1px solid #f1f5f9; vertical-align:middle; }
table.data-table tr:last-child td { border-bottom:none; }
table.data-table tr:hover td { background:#fafbfd; }
table.data-table tfoot td { background:#f8fafc; font-weight:700; font-size:.83rem; color:var(--ink); border-top:1.5px solid var(--border); }
table.data-table td.num { font-family:'JetBrains Mono',monospace; font-size:.8rem; }

/* ── BUTTONS ── */
.btn { display:inline-flex; align-items:center; gap:6px; padding:8px 16px; border-radius:8px; font-size:.82rem; font-weight:700; font-family:inherit; border:none; cursor:pointer; transition:all .2s; text-decoration:none; }
.btn:hover { transform:translateY(-1px); }
.btn-primary { background:var(--primary); color:#fff; box-shadow:0 3px 10px rgba(29,78,216,.2); }
.btn-primary:hover { background:#1e40af; color:#fff; }
.btn-success { background:var(--green);  color:#fff; }
.btn-success:hover { background:#047857; color:#fff; }
.btn-danger  { background:var(--red);    color:#fff; }
.btn-danger:hover  { background:#b91c1c; color:#fff; }
.btn-amber   { background:var(--amber);  color:#fff; }
.btn-amber:hover   { background:#b45309; color:#fff; }
.btn-outline { background:transparent; color:var(--ink-2); border:1.5px solid var(--border); }
.btn-outline:hover { border-color:var(--primary-lt); color:var(--primary); background:var(--primary-bg); }
.btn-sm  { padding:5px 12px; font-size:.76rem; border-radius:7px; }
.btn-xs  { padding:4px 9px;  font-size:.72rem; border-radius:6px; }
.btn-icon-warning { background:var(--amber-bg); color:var(--amber); border:1px solid #fde68a; }
.btn-icon-warning:hover { background:var(--amber); color:#fff; }
.btn-icon-danger  { background:var(--red-bg);   color:var(--red);   border:1px solid #fca5a5; }
.btn-icon-danger:hover  { background:var(--red);   color:#fff; }

/* ── FILTER CARD ── */
.filter-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:14px; }
.divider { height:1px; background:var(--border); margin:16px 0; }
.export-row { display:flex; gap:9px; align-items:center; flex-wrap:wrap; }
.export-label { font-size:.78rem; color:var(--muted); font-weight:600; display:flex; align-items:center; gap:5px; }

/* ── BADGE ── */
.badge { display:inline-flex; align-items:center; padding:3px 10px; border-radius:50px; font-size:.7rem; font-weight:700; }
.badge-blue   { background:var(--primary-bg); color:var(--primary); }
.badge-green  { background:var(--green-bg);   color:#065f46; }
.badge-amber  { background:var(--amber-bg);   color:#92400e; }
.badge-violet { background:var(--violet-bg);  color:var(--violet); }

@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
  .form-row-settings { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="layout">

<!-- ── SIDEBAR ── -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC</div>
      <div class="brand-sub">Admin Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item">
        <a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="manage_users.php"         class="nav-link"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="digital.php"              class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)">
          <i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu open">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="mobile_attendance.php"       class="nav-link"><i class="fas fa-mobile-alt"></i>       Daily Attendance Report</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="ot_dashboard.php"            class="nav-link active"><i class="fas fa-hourglass-half"></i> OT Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="manager_hr_leave_apply.php"  class="nav-link"><i class="fas fa-calendar-plus"></i>    Apply Leave</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>  Login Credentials</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<!-- ── CONTENT ── -->
<div class="content" id="content">

  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>CAB</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">OT Dashboard</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username_session ?: 'A', 0, 1)); ?></div>
      <?php echo h($username_session ?: 'Admin'); ?>
    </div>
  </div>

  <div class="page">

    <div class="page-header">
      <div>
        <div class="page-title">Overtime Management</div>
        <div class="page-subtitle">Track, manage and export employee overtime records</div>
      </div>
      <a href="dashboard_admin.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> Dashboard</a>
    </div>

    <?php if($msg): ?>
    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= h($msg) ?></div>
    <?php endif; ?>
    <?php if($err): ?>
    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= h($err) ?></div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-grid">
      <div class="scard blue"><div class="scard-icon blue"><i class="fas fa-calendar-day"></i></div><div class="scard-val"><?= $working_days ?></div><div class="scard-label">Working Days</div><div class="scard-sub">Per month</div></div>
      <div class="scard amber"><div class="scard-icon amber"><i class="fas fa-clock"></i></div><div class="scard-val"><?= $working_hours ?></div><div class="scard-label">Working Hours</div><div class="scard-sub">Per day</div></div>
      <div class="scard green"><div class="scard-icon green"><i class="fas fa-hourglass-half"></i></div><div class="scard-val"><?= number_format($ot_totals['th'] ?? 0, 1) ?></div><div class="scard-label">Total OT Hours</div><div class="scard-sub">Filtered results</div></div>
      <div class="scard violet"><div class="scard-icon violet"><i class="fas fa-money-bill-wave"></i></div><div class="scard-val">₹<?= number_format($ot_totals['ts'] ?? 0, 0) ?></div><div class="scard-label">Total OT Amount</div><div class="scard-sub">Filtered results</div></div>
    </div>

    <!-- OT Settings -->
    <div class="card">
      <div class="card-header">
        <div class="card-header-icon" style="background:var(--primary-bg);color:var(--primary)"><i class="fas fa-gear"></i></div>
        <div class="card-title">OT Settings</div>
      </div>
      <div class="card-body">
        <form method="post">
          <div class="form-row-settings">
            <div>
              <label class="form-label">Working Days (Month)</label>
              <input type="number" name="working_days" value="<?= h($working_days) ?>" class="form-input" required>
            </div>
            <div>
              <label class="form-label">Working Hours (Day)</label>
              <input type="number" step="0.5" name="working_hours" value="<?= h($working_hours) ?>" class="form-input" required>
            </div>
            <div>
              <button class="btn btn-primary" name="save_settings"><i class="fas fa-save"></i> Save Settings</button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- OT Entry Form -->
    <div class="card">
      <div class="card-header">
        <div class="card-header-icon" style="background:var(--green-bg);color:var(--green)"><i class="fas fa-<?= $edit_data ? 'pen' : 'plus' ?>"></i></div>
        <div class="card-title"><?= $edit_data ? 'Edit OT Entry' : 'Add OT Entry' ?></div>
      </div>
      <div class="card-body">
        <form method="post">
          <input type="hidden" name="edit_id" value="<?= h($edit_data['id'] ?? '') ?>">
          <div class="form-row">
            <div>
              <label class="form-label">Employee</label>
              <select name="emp_id" class="form-select" required>
                <option value="">Select Employee</option>
                <?php $employees->data_seek(0); while($e = $employees->fetch_assoc()): ?>
                <option value="<?= $e['emp_id'] ?>" <?= ($edit_data && $edit_data['emp_id'] == $e['emp_id']) ? 'selected' : '' ?>><?= h($e['emp_name']) ?></option>
                <?php endwhile; ?>
              </select>
            </div>
            <div>
              <label class="form-label">OT Date</label>
              <input type="date" name="ot_date" class="form-input" value="<?= h($edit_data['ot_date'] ?? '') ?>" required>
            </div>
            <div>
              <label class="form-label">Salary (₹)</label>
              <input type="number" step="0.01" id="salary" name="salary" class="form-input" value="<?= h($edit_data['salary'] ?? '') ?>" required placeholder="0.00">
            </div>
            <div>
              <label class="form-label">Per Day (₹) <span style="color:var(--green);font-size:.7rem">Auto</span></label>
              <input type="number" step="0.01" id="per_day" name="per_day" class="form-input" readonly value="<?= h($edit_data['per_day'] ?? '') ?>" style="background:#f8fafc;color:var(--ink-2)">
            </div>
            <div>
              <label class="form-label">OT Hours</label>
              <input type="number" step="0.1" id="ot_hours" name="ot_hours" class="form-input" value="<?= h($edit_data['ot_hours'] ?? '') ?>" required placeholder="0.0">
            </div>
            <div>
              <label class="form-label">OT Days <span style="color:var(--green);font-size:.7rem">Auto</span></label>
              <input type="number" step="0.01" id="ot_days" name="ot_days" class="form-input" readonly value="<?= h($edit_data['ot_days'] ?? '') ?>" style="background:#f8fafc;color:var(--ink-2)">
            </div>
            <div>
              <label class="form-label">OT Salary (₹) <span style="color:var(--green);font-size:.7rem">Auto</span></label>
              <input type="number" step="0.01" id="ot_salary" name="ot_salary" class="form-input" readonly value="<?= h($edit_data['ot_salary'] ?? '') ?>" style="background:#f8fafc;color:var(--ink-2)">
            </div>
            <div style="display:flex;align-items:flex-end">
              <button class="btn btn-primary" name="<?= $edit_data ? 'update_ot' : 'add_ot' ?>" style="width:100%">
                <i class="fas fa-<?= $edit_data ? 'check' : 'plus' ?>"></i> <?= $edit_data ? 'Update OT' : 'Add OT' ?>
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- Filter -->
    <div class="card">
      <div class="card-header">
        <div class="card-header-icon" style="background:var(--bg);color:var(--muted)"><i class="fas fa-sliders"></i></div>
        <div class="card-title">Filter Reports</div>
      </div>
      <div class="card-body">
        <form method="get">
          <div class="filter-grid">
            <div>
              <label class="form-label">Employee</label>
              <select name="emp_id" class="form-select">
                <option value="">All Employees</option>
                <?php $employees->data_seek(0); while($e = $employees->fetch_assoc()): ?>
                <option value="<?= $e['emp_id'] ?>" <?= $filter_emp == $e['emp_id'] ? 'selected' : '' ?>><?= h($e['emp_name']) ?></option>
                <?php endwhile; ?>
              </select>
            </div>
            <div>
              <label class="form-label">Month</label>
              <input type="month" name="month" class="form-input" value="<?= h($filter_month) ?>">
            </div>
            <div>
              <label class="form-label">From Date</label>
              <input type="date" name="from" class="form-input" value="<?= h($from) ?>">
            </div>
            <div>
              <label class="form-label">To Date</label>
              <input type="date" name="to" class="form-input" value="<?= h($to) ?>">
            </div>
            <div style="display:flex;align-items:flex-end">
              <button type="submit" class="btn btn-primary" style="width:100%"><i class="fas fa-search"></i> Apply</button>
            </div>
          </div>
          <div class="divider"></div>
          <div class="export-row">
            <?php
            $exportParams = $_GET;
            unset($exportParams['export']);
            ?>
            <span class="export-label"><i class="fas fa-download"></i> Export:</span>
            <a href="?<?= http_build_query($exportParams + ['export'=>'csv'])  ?>" class="btn btn-outline btn-sm"><i class="fas fa-file-csv"></i> CSV</a>
            <a href="?<?= http_build_query($exportParams + ['export'=>'xlsx']) ?>" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
            <a href="?<?= http_build_query($exportParams + ['export'=>'pdf'])  ?>" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> PDF</a>
          </div>
        </form>
      </div>
    </div>

    <!-- Date-wise Report -->
    <div class="card">
      <div class="card-header">
        <div class="card-header-icon" style="background:var(--primary-bg);color:var(--primary)"><i class="fas fa-table"></i></div>
        <div class="card-title">Date-wise OT Report</div>
      </div>
      <div class="table-wrap">
        <table class="data-table">
          <thead>
            <tr>
              <th>Date</th>
              <th>Employee</th>
              <th>OT Hours</th>
              <th>OT Days</th>
              <th>Amount (₹)</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php
          $q = $conn->query("
              SELECT o.*, u.first_name FROM ot_entries o
              LEFT JOIN users u ON u.id=o.emp_id
              $where_sql ORDER BY o.ot_date DESC
          ");
          $has_rows = false;
          while ($r = $q->fetch_assoc()):
            $has_rows = true;
          ?>
          <tr>
            <td><?= date('d M Y', strtotime($r['ot_date'])) ?></td>
            <td><strong><?= h($r['first_name']) ?></strong></td>
            <td><span class="badge badge-blue"><?= $r['ot_hours'] ?> hrs</span></td>
            <td class="num"><?= $r['ot_days'] ?></td>
            <td class="num" style="color:var(--green);font-weight:700">₹<?= number_format($r['ot_salary'],2) ?></td>
            <td>
              <div style="display:flex;gap:6px">
                <a href="?edit=<?= $r['id'] ?>" class="btn btn-xs btn-icon-warning"><i class="fas fa-pen"></i> Edit</a>
                <a href="?delete=<?= $r['id'] ?>" class="btn btn-xs btn-icon-danger" onclick="return confirm('Delete this OT entry?')"><i class="fas fa-trash"></i> Delete</a>
              </div>
            </td>
          </tr>
          <?php endwhile; ?>
          <?php if(!$has_rows): ?>
          <tr><td colspan="6" style="text-align:center;padding:30px;color:var(--muted)"><i class="fas fa-inbox" style="font-size:1.5rem;display:block;margin-bottom:8px"></i>No OT records found</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Monthly Summary -->
    <div class="card">
      <div class="card-header">
        <div class="card-header-icon" style="background:var(--green-bg);color:var(--green)"><i class="fas fa-chart-bar"></i></div>
        <div class="card-title">Monthly OT Summary</div>
      </div>
      <div class="table-wrap">
        <table class="data-table">
          <thead>
            <tr>
              <th>Employee</th>
              <th>Total OT Hours</th>
              <th>Total OT Days</th>
              <th>Total Amount (₹)</th>
            </tr>
          </thead>
          <tbody>
          <?php
          $mq = $conn->query("
              SELECT u.first_name, SUM(o.ot_hours) h, SUM(o.ot_days) d, SUM(o.ot_salary) s
              FROM ot_entries o LEFT JOIN users u ON u.id=o.emp_id
              $where_sql GROUP BY o.emp_id ORDER BY s DESC
          ");
          $grand_h = $grand_d = $grand_s = 0;
          $rows = $mq->fetch_all(MYSQLI_ASSOC);
          foreach($rows as $r):
            $grand_h += $r['h']; $grand_d += $r['d']; $grand_s += $r['s'];
          ?>
          <tr>
            <td><strong><?= h($r['first_name']) ?></strong></td>
            <td><span class="badge badge-blue"><?= number_format($r['h'],1) ?> hrs</span></td>
            <td class="num"><?= number_format($r['d'],2) ?></td>
            <td class="num" style="color:var(--green);font-weight:700">₹<?= number_format($r['s'],2) ?></td>
          </tr>
          <?php endforeach; ?>
          <?php if(!empty($rows)): ?>
          <tfoot>
            <tr>
              <td>Grand Total</td>
              <td><span class="badge badge-amber"><?= number_format($grand_h,1) ?> hrs</span></td>
              <td class="num"><?= number_format($grand_d,2) ?></td>
              <td class="num" style="color:var(--primary)">₹<?= number_format($grand_s,2) ?></td>
            </tr>
          </tfoot>
          <?php endif; ?>
        </table>
      </div>
    </div>

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<script>
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.nextElementSibling.classList.toggle('open');
  btn.classList.toggle('open');
}

// OT Auto-calculation
const wd = <?= $working_days ?>;
const wh = <?= $working_hours ?>;

function calculateAll() {
  const salary   = parseFloat(document.getElementById('salary').value)   || 0;
  const ot_hours = parseFloat(document.getElementById('ot_hours').value) || 0;
  const per_day  = salary && wd ? salary / wd : 0;
  const ot_days  = ot_hours && wh ? ot_hours / wh : 0;
  const ot_salary = per_day * ot_days;
  document.getElementById('per_day').value  = per_day.toFixed(2);
  document.getElementById('ot_days').value  = ot_days.toFixed(2);
  document.getElementById('ot_salary').value = ot_salary.toFixed(2);
}
document.getElementById('salary').addEventListener('input', calculateAll);
document.getElementById('ot_hours').addEventListener('input', calculateAll);
</script>
</body>
</html>