<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db     = Database::getInstance();
$page   = 'HR Reports';
$rType  = get('type');
$month  = cleanInt($_GET['month'] ?? date('n'));
$year   = cleanInt($_GET['year']  ?? date('Y'));
$dept   = cleanInt($_GET['dept']  ?? 0);
$format = get('format') ?: 'html';
$departments = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");

// ── CSV helper ────────────────────────────────────────────────
function startCsv(string $name): void {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header('Pragma: no-cache'); header('Expires: 0');
}

// ── Report functions ──────────────────────────────────────────
// FIX (07 Jul 2026): none of the report functions below were scoped to
// the current organization — every one of them reported across every
// organization's employees. Each now adds an org-scope clause.
function headcountReport(Database $db, int $dept): array {
    $where = $dept ? "AND e.department_id=$dept" : '';
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT d.name AS dept_name,
        COUNT(e.id) AS total,
        SUM(e.status='active') AS active,
        SUM(e.status='probation') AS probation,
        SUM(e.status='on_leave') AS on_leave,
        SUM(e.gender='male') AS male,
        SUM(e.gender='female') AS female,
        ROUND(AVG(TIMESTAMPDIFF(YEAR,e.date_of_birth,CURDATE())),1) AS avg_age
    FROM employees e LEFT JOIN departments d ON d.id=e.department_id
    WHERE e.status != 'terminated' AND $orgClause $where
    GROUP BY d.name ORDER BY d.name", $orgParams);
}

function attendanceSummary(Database $db, int $month, int $year, int $dept): array {
    $where = $dept ? "AND e.department_id=$dept" : '';
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name, d.name AS dept,
        COALESCE(ms.present_days,0) AS present_days,
        COALESCE(ms.absent_days,0) AS absent_days,
        COALESCE(ms.half_days,0) AS half_days,
        COALESCE(ms.leave_days,0) AS leave_days,
        COALESCE(ms.week_off_days,0) AS week_off_days,
        COALESCE(ms.lop_days,0) AS lop_days,
        COALESCE(ms.ot_hours,0) AS ot_hours,
        COALESCE(ms.late_count,0) AS late_count
    FROM employees e
    LEFT JOIN departments d ON d.id=e.department_id
    LEFT JOIN muster_summary ms ON ms.employee_id=e.id AND ms.month=? AND ms.year=?
    WHERE e.status='active' AND $orgClause $where ORDER BY e.first_name", array_merge([$month,$year], $orgParams));
}

function salaryRegister(Database $db, int $month, int $year, int $dept): array {
    $where = $dept ? "AND e.department_id=$dept" : '';
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name, e.pan_number,
        d.name AS dept, des.name AS designation,
        COALESCE(pd.basic,0) AS basic, COALESCE(pd.hra,0) AS hra,
        COALESCE(pd.da,0) AS da, COALESCE(pd.special_allowance,0) AS special_allowance,
        COALESCE(pd.gross_salary,0) AS gross_salary,
        COALESCE(pd.pf_employee,0) AS pf_employee,
        COALESCE(pd.esi_employee,0) AS esi_employee,
        COALESCE(pd.professional_tax,0) AS professional_tax,
        COALESCE(pd.income_tax,0) AS income_tax,
        COALESCE(pd.advance_recovery,0) AS advance_recovery,
        COALESCE(pd.total_deductions,0) AS total_deductions,
        COALESCE(pd.net_salary,0) AS net_salary
    FROM employees e
    LEFT JOIN departments d ON d.id=e.department_id
    LEFT JOIN designations des ON des.id=e.designation_id
    LEFT JOIN payroll_details pd ON pd.employee_id=e.id AND pd.month=? AND pd.year=?
    WHERE e.status='active' AND $orgClause $where ORDER BY e.employee_id", array_merge([$month,$year], $orgParams));
}

function leaveSummary(Database $db, int $year): array {
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name, d.name AS dept,
        lt.code AS lt_code, lt.name AS lt_name,
        lb.allocated, lb.used, lb.carry_forward,
        (lb.allocated + COALESCE(lb.carry_forward,0) - lb.used) AS available
    FROM employee_leave_balance lb
    JOIN employees e ON e.id=lb.employee_id
    JOIN leave_types lt ON lt.id=lb.leave_type_id
    LEFT JOIN departments d ON d.id=e.department_id
    WHERE lb.year=? AND e.status='active' AND $orgClause
    ORDER BY e.first_name, lt.name", array_merge([$year], $orgParams));
}

function recruitmentReport(Database $db): array {
    // job_openings has no employee/company link in this schema — flagged
    // as a known follow-up (see README), left global for now.
    return $db->fetchAll("SELECT jo.title, d.name AS dept,
        jo.openings, jo.status, jo.posted_date, jo.closing_date,
        COUNT(ja.id) AS applicants,
        SUM(ja.status='joined') AS joined,
        SUM(ja.status='rejected') AS rejected,
        SUM(ja.status='interview') AS interview
    FROM job_openings jo
    LEFT JOIN departments d ON d.id=jo.department_id
    LEFT JOIN job_applicants ja ON ja.job_id=jo.id
    GROUP BY jo.id ORDER BY jo.posted_date DESC");
}

function newJoiners(Database $db, int $month, int $year): array {
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name,
        d.name AS dept, des.name AS designation, e.date_of_joining, e.employment_type
    FROM employees e
    LEFT JOIN departments d ON d.id=e.department_id
    LEFT JOIN designations des ON des.id=e.designation_id
    WHERE MONTH(e.date_of_joining)=? AND YEAR(e.date_of_joining)=? AND $orgClause
    ORDER BY e.date_of_joining", array_merge([$month,$year], $orgParams));
}

function attritionReport(Database $db, int $year): array {
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name,
        d.name AS dept, des.name AS designation, e.date_of_joining, e.status,
        TIMESTAMPDIFF(YEAR,e.date_of_joining,CURDATE()) AS service_years
    FROM employees e
    LEFT JOIN departments d ON d.id=e.department_id
    LEFT JOIN designations des ON des.id=e.designation_id
    WHERE e.status IN ('resigned','terminated') AND YEAR(e.updated_at)=? AND $orgClause
    ORDER BY e.updated_at DESC", array_merge([$year], $orgParams));
}

function pfRegister(Database $db, int $month, int $year): array {
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name,
        e.uan_number, e.pf_number,
        COALESCE(pd.basic,0) AS pf_wages,
        COALESCE(pd.pf_employee,0) AS ee_pf,
        COALESCE(pd.pf_employer,0) AS er_pf,
        COALESCE(pd.esi_employee,0) AS ee_esi,
        COALESCE(pd.esi_employer,0) AS er_esi
    FROM employees e
    LEFT JOIN payroll_details pd ON pd.employee_id=e.id AND pd.month=? AND pd.year=?
    WHERE e.status='active' AND e.pf_applicable=1 AND $orgClause
    ORDER BY e.employee_id", array_merge([$month,$year], $orgParams));
}

function tdsSummary(Database $db, int $month, int $year): array {
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name, e.pan_number, e.tax_regime,
        COALESCE(tc.gross_income,0) AS gross_income,
        COALESCE(tc.net_taxable_income,0) AS net_taxable_income,
        COALESCE(tc.tax_liability,0) AS tax_liability,
        COALESCE(tc.tds_this_month,0) AS tds_this_month,
        COALESCE(tc.tds_deducted_ytd,0) AS tds_ytd
    FROM employees e
    LEFT JOIN tds_calculations tc ON tc.employee_id=e.id AND tc.month=? AND tc.year=?
    WHERE e.status='active' AND e.tds_applicable=1 AND $orgClause
    ORDER BY e.employee_id", array_merge([$month,$year], $orgParams));
}

function birthdayReport(Database $db): array {
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    return $db->fetchAll("SELECT e.employee_id, e.first_name, e.last_name,
        e.date_of_birth, d.name AS dept,
        DATE_FORMAT(e.date_of_birth, CONCAT(YEAR(CURDATE()),'-%m-%d')) AS bday_this_year,
        TIMESTAMPDIFF(YEAR,e.date_of_birth,CURDATE())+1 AS turning_age
    FROM employees e LEFT JOIN departments d ON d.id=e.department_id
    WHERE e.status='active' AND e.date_of_birth IS NOT NULL AND $orgClause
    HAVING bday_this_year BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    ORDER BY bday_this_year", $orgParams);
}

// ── Handle CSV output before any HTML ────────────────────────
if ($format === 'csv' && $rType) {
    switch ($rType) {
        case 'headcount':
            startCsv("headcount_$year.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Department','Total','Active','Probation','On Leave','Male','Female','Avg Age']);
            foreach (headcountReport($db,$dept) as $r)
                fputcsv($out,[$r['dept_name'],$r['total'],$r['active'],$r['probation'],$r['on_leave'],$r['male'],$r['female'],$r['avg_age']]);
            exit;
        case 'attendance':
            startCsv("attendance_{$month}_{$year}.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Emp ID','Name','Dept','Present','Absent','Half Day','Leave','Week Off','LOP','OT Hrs','Late']);
            foreach (attendanceSummary($db,$month,$year,$dept) as $r)
                fputcsv($out,[$r['employee_id'],$r['first_name'].' '.$r['last_name'],$r['dept'],$r['present_days'],$r['absent_days'],$r['half_days'],$r['leave_days'],$r['week_off_days'],$r['lop_days'],$r['ot_hours'],$r['late_count']]);
            exit;
        case 'salary_register':
            startCsv("salary_{$month}_{$year}.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Emp ID','Name','PAN','Dept','Designation','Basic','HRA','DA','Special','Gross','PF(EE)','ESI(EE)','PT','TDS','Advance','Total Deductions','Net Pay']);
            foreach (salaryRegister($db,$month,$year,$dept) as $r)
                fputcsv($out,[$r['employee_id'],$r['first_name'].' '.$r['last_name'],$r['pan_number'],$r['dept'],$r['designation'],$r['basic'],$r['hra'],$r['da'],$r['special_allowance'],$r['gross_salary'],$r['pf_employee'],$r['esi_employee'],$r['professional_tax'],$r['income_tax'],$r['advance_recovery'],$r['total_deductions'],$r['net_salary']]);
            exit;
        case 'leave_summary':
            startCsv("leave_{$year}.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Emp ID','Name','Dept','Leave Type','Allocated','Used','Carry Fwd','Available']);
            foreach (leaveSummary($db,$year) as $r)
                fputcsv($out,[$r['employee_id'],$r['first_name'].' '.$r['last_name'],$r['dept'],$r['lt_name'],$r['allocated'],$r['used'],$r['carry_forward'],$r['available']]);
            exit;
        case 'pf_register':
            startCsv("pf_{$month}_{$year}.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Emp ID','Name','UAN','PF No','PF Wages','EE PF','ER PF','EE ESI','ER ESI','Total']);
            foreach (pfRegister($db,$month,$year) as $r)
                fputcsv($out,[$r['employee_id'],$r['first_name'].' '.$r['last_name'],$r['uan_number'],$r['pf_number'],$r['pf_wages'],$r['ee_pf'],$r['er_pf'],$r['ee_esi'],$r['er_esi'],$r['ee_pf']+$r['er_pf']+$r['ee_esi']+$r['er_esi']]);
            exit;
        case 'tds_summary':
            startCsv("tds_{$month}_{$year}.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Emp ID','Name','PAN','Regime','Gross Income','Taxable Income','Tax Liability','TDS This Month','TDS YTD']);
            foreach (tdsSummary($db,$month,$year) as $r)
                fputcsv($out,[$r['employee_id'],$r['first_name'].' '.$r['last_name'],$r['pan_number'],$r['tax_regime'],$r['gross_income'],$r['net_taxable_income'],$r['tax_liability'],$r['tds_this_month'],$r['tds_ytd']]);
            exit;
        case 'new_joiners':
            startCsv("joiners_{$month}_{$year}.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Emp ID','Name','Dept','Designation','Date of Joining','Type']);
            foreach (newJoiners($db,$month,$year) as $r)
                fputcsv($out,[$r['employee_id'],$r['first_name'].' '.$r['last_name'],$r['dept'],$r['designation'],$r['date_of_joining'],$r['employment_type']]);
            exit;
        case 'attrition':
            startCsv("attrition_{$year}.csv");
            $out = fopen('php://output','w');
            fputcsv($out,['Emp ID','Name','Dept','Designation','Joined','Status','Service Years']);
            foreach (attritionReport($db,$year) as $r)
                fputcsv($out,[$r['employee_id'],$r['first_name'].' '.$r['last_name'],$r['dept'],$r['designation'],$r['date_of_joining'],$r['status'],$r['service_years']]);
            exit;
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<?php if (!$rType): ?>
<div class="row g-3">
  <?php $reports = [
    ['headcount',      'ti-users',         'Headcount Report',     'Dept-wise employee count, gender & age distribution','brand'],
    ['attendance',     'ti-calendar-stats','Attendance Summary',   'Monthly P/A/LOP/late count per employee',            'green'],
    ['salary_register','ti-receipt',       'Salary Register',      'Full payroll register with earnings & deductions',   'blue'],
    ['leave_summary',  'ti-beach',         'Leave Summary',        'Leave balance, usage and carry-forward',             'amber'],
    ['pf_register',    'ti-building-bank', 'PF / ESI Register',   'PF & ESI contribution register for filing',          'green'],
    ['tds_summary',    'ti-file-invoice',  'TDS Summary',          'Monthly TDS deducted & Form 16 basis',               'red'],
    ['recruitment',    'ti-user-plus',     'Recruitment Report',   'Job openings, applicants, interview & joining',      'brand'],
    ['birthday',       'ti-cake',          'Birthday Report',      'Upcoming employee birthdays (next 30 days)',          'amber'],
    ['new_joiners',    'ti-user-check',    'New Joiners',          'Employees who joined in selected period',            'blue'],
    ['attrition',      'ti-user-off',      'Attrition Report',     'Resignations, terminations & attrition rate',        'red'],
  ]; foreach ($reports as [$type,$icon,$title,$desc,$cls]): ?>
  <div class="col-md-4 col-lg-3">
    <div class="pc-card h-100 hover-lift">
      <div class="d-flex gap-3">
        <div class="pc-stat-icon <?=$cls?>" style="flex-shrink:0;width:44px;height:44px;font-size:20px"><i class="ti <?=$icon?>"></i></div>
        <div>
          <div class="fw-semibold mb-1"><?=$title?></div>
          <div class="small text-muted mb-2"><?=$desc?></div>
          <a href="?type=<?=$type?>" class="btn btn-pc btn-sm"><i class="ti ti-arrow-right me-1"></i>Generate</a>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php else:
$csvUrl = '?type='.$rType.'&month='.$month.'&year='.$year.'&dept='.$dept.'&format=csv';
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2 flex-wrap align-items-end">
    <input type="hidden" name="type" value="<?=clean($rType)?>">
    <?php if (in_array($rType,['attendance','salary_register','pf_register','tds_summary','new_joiners'])): ?>
    <div><label class="pc-label">Month</label>
      <select name="month" class="form-select form-select-sm">
        <?php for($m=1;$m<=12;$m++): ?><option value="<?=$m?>" <?=$m===$month?'selected':''?>><?=monthName($m)?></option><?php endfor; ?>
      </select></div>
    <?php endif; ?>
    <div><label class="pc-label">Year</label>
      <select name="year" class="form-select form-select-sm">
        <?php for($y=date('Y')-2;$y<=date('Y')+1;$y++): ?><option value="<?=$y?>" <?=$y===$year?'selected':''?>><?=$y?></option><?php endfor; ?>
      </select></div>
    <?php if (in_array($rType,['headcount','attendance','salary_register'])): ?>
    <div><label class="pc-label">Department</label>
      <select name="dept" class="form-select form-select-sm" style="width:160px">
        <option value="">All</option>
        <?php foreach($departments as $d): ?><option value="<?=$d['id']?>" <?=$dept==$d['id']?'selected':''?>><?=clean($d['name'])?></option><?php endforeach; ?>
      </select></div>
    <?php endif; ?>
    <button class="btn btn-pc btn-sm"><i class="ti ti-refresh me-1"></i>Generate</button>
    <a href="<?=$csvUrl?>" class="btn btn-sm btn-outline-success"><i class="ti ti-download me-1"></i>Export CSV</a>
    <button type="button" onclick="window.print()" class="btn btn-sm btn-outline-secondary"><i class="ti ti-printer me-1"></i>Print</button>
    <a href="hr_reports.php" class="btn btn-sm btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>Back</a>
  </form>
</div>

<?php
switch ($rType) {
    // ── Headcount ─────────────────────────────────────────────
    case 'headcount':
        $data = headcountReport($db,$dept);
        echo "<div class='pc-card'><div class='pc-card-title'>Headcount Report — $year</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Department</th><th>Total</th><th>Active</th><th>Probation</th><th>On Leave</th><th>Male</th><th>Female</th><th>Avg Age</th></tr></thead><tbody>";
        $tot = ['total'=>0,'active'=>0,'probation'=>0,'on_leave'=>0,'male'=>0,'female'=>0];
        foreach ($data as $r) {
            foreach ($tot as $k=>$_) $tot[$k] += $r[$k];
            echo "<tr><td class='fw-semibold'>".clean($r['dept_name']??'Unassigned')."</td><td>{$r['total']}</td>
                  <td><span class='badge' style='background:var(--pc-green-bg);color:var(--pc-green)'>{$r['active']}</span></td>
                  <td>{$r['probation']}</td><td>{$r['on_leave']}</td>
                  <td>{$r['male']}</td><td>{$r['female']}</td><td>{$r['avg_age']}</td></tr>";
        }
        echo "<tr style='background:var(--pc-brand-light);font-weight:700'><td>TOTAL</td><td>{$tot['total']}</td><td>{$tot['active']}</td><td>{$tot['probation']}</td><td>{$tot['on_leave']}</td><td>{$tot['male']}</td><td>{$tot['female']}</td><td>—</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── Attendance ────────────────────────────────────────────
    case 'attendance':
        $data = attendanceSummary($db,$month,$year,$dept);
        echo "<div class='pc-card'><div class='pc-card-title'>Attendance Summary — ".monthName($month)." $year</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Emp ID</th><th>Employee</th><th>Dept</th><th>Present</th><th>Absent</th><th>Half Day</th><th>Leave</th><th>Week Off</th><th>LOP</th><th>OT Hrs</th><th>Late</th></tr></thead><tbody>";
        foreach ($data as $r) {
            echo "<tr><td>".clean($r['employee_id'])."</td><td class='fw-semibold'>".clean($r['first_name'].' '.$r['last_name'])."</td>
                  <td>".clean($r['dept']??'')."</td>
                  <td><span class='badge' style='background:var(--pc-green-bg);color:var(--pc-green)'>{$r['present_days']}</span></td>
                  <td><span class='badge' style='background:var(--pc-red-bg);color:var(--pc-red)'>{$r['absent_days']}</span></td>
                  <td>{$r['half_days']}</td><td>{$r['leave_days']}</td><td>{$r['week_off_days']}</td>
                  <td class='fw-bold' style='color:var(--pc-amber)'>{$r['lop_days']}</td>
                  <td>{$r['ot_hours']}</td><td>{$r['late_count']}</td></tr>";
        }
        if (!$data) echo "<tr><td colspan='11' class='text-center text-muted py-3'>No data for selected period</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── Salary Register ───────────────────────────────────────
    case 'salary_register':
        $data = salaryRegister($db,$month,$year,$dept);
        echo "<div class='pc-card'><div class='pc-card-title'>Salary Register — ".monthName($month)." $year</div><div class='pc-table-wrap'><table class='pc-table' style='font-size:11px'>";
        echo "<thead><tr><th>Emp ID</th><th>Name</th><th>Dept</th><th>Basic</th><th>HRA</th><th>Special</th><th>Gross</th><th>PF</th><th>ESI</th><th>PT</th><th>TDS</th><th>Adv</th><th>Deductions</th><th>Net Pay</th></tr></thead><tbody>";
        $tot = array_fill_keys(['gross_salary','pf_employee','esi_employee','professional_tax','income_tax','advance_recovery','total_deductions','net_salary'],0);
        foreach ($data as $r) {
            foreach ($tot as $k=>$_) $tot[$k] += $r[$k];
            echo "<tr><td>".clean($r['employee_id'])."</td><td class='fw-semibold'>".clean($r['first_name'].' '.$r['last_name'])."</td>
                  <td>".clean($r['dept']??'')."</td>
                  <td>".money($r['basic'])."</td><td>".money($r['hra'])."</td><td>".money($r['special_allowance'])."</td>
                  <td class='fw-bold'>".money($r['gross_salary'])."</td>
                  <td>".money($r['pf_employee'])."</td><td>".money($r['esi_employee'])."</td>
                  <td>".money($r['professional_tax'])."</td><td>".money($r['income_tax'])."</td>
                  <td>".money($r['advance_recovery'])."</td>
                  <td class='text-danger fw-semibold'>".money($r['total_deductions'])."</td>
                  <td class='text-success fw-bold'>".money($r['net_salary'])."</td></tr>";
        }
        echo "<tr style='background:var(--pc-brand-light);font-weight:700'><td colspan='3'>TOTAL</td>
              <td colspan='3'></td><td>".money($tot['gross_salary'])."</td>
              <td>".money($tot['pf_employee'])."</td><td>".money($tot['esi_employee'])."</td>
              <td>".money($tot['professional_tax'])."</td><td>".money($tot['income_tax'])."</td>
              <td>".money($tot['advance_recovery'])."</td>
              <td class='text-danger'>".money($tot['total_deductions'])."</td>
              <td class='text-success'>".money($tot['net_salary'])."</td></tr>";
        if (!$data) echo "<tr><td colspan='14' class='text-center text-muted py-3'>No payroll data for ".monthName($month)." $year</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── Leave Summary ─────────────────────────────────────────
    case 'leave_summary':
        $data = leaveSummary($db,$year);
        echo "<div class='pc-card'><div class='pc-card-title'>Leave Balance Summary — $year</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Emp ID</th><th>Employee</th><th>Dept</th><th>Leave Type</th><th>Allocated</th><th>Used</th><th>Carry Fwd</th><th>Available</th></tr></thead><tbody>";
        foreach ($data as $r) {
            $avail = (int)$r['available'];
            echo "<tr><td>".clean($r['employee_id'])."</td><td class='fw-semibold'>".clean($r['first_name'].' '.$r['last_name'])."</td>
                  <td>".clean($r['dept']??'')."</td>
                  <td><span class='badge' style='background:var(--pc-blue-bg);color:var(--pc-blue)'>".clean($r['lt_code'])."</span> ".clean($r['lt_name'])."</td>
                  <td>{$r['allocated']}</td><td class='text-danger'>{$r['used']}</td><td>{$r['carry_forward']}</td>
                  <td class='fw-bold ".($avail>0?'text-success':'text-danger')."'>{$avail}</td></tr>";
        }
        if (!$data) echo "<tr><td colspan='8' class='text-center text-muted py-3'>No leave balance data</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── PF / ESI Register ─────────────────────────────────────
    case 'pf_register':
        $data = pfRegister($db,$month,$year);
        echo "<div class='pc-card'><div class='pc-card-title'>PF / ESI Register — ".monthName($month)." $year</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Emp ID</th><th>Name</th><th>UAN</th><th>PF Wages</th><th>EE PF</th><th>ER PF</th><th>EE ESI</th><th>ER ESI</th><th>Total</th></tr></thead><tbody>";
        $tot = ['pf_wages'=>0,'ee_pf'=>0,'er_pf'=>0,'ee_esi'=>0,'er_esi'=>0];
        foreach ($data as $r) {
            foreach ($tot as $k=>$_) $tot[$k] += $r[$k];
            $total = $r['ee_pf']+$r['er_pf']+$r['ee_esi']+$r['er_esi'];
            echo "<tr><td>".clean($r['employee_id'])."</td><td class='fw-semibold'>".clean($r['first_name'].' '.$r['last_name'])."</td>
                  <td>".clean($r['uan_number']??'—')."</td>
                  <td>".money($r['pf_wages'])."</td><td>".money($r['ee_pf'])."</td><td>".money($r['er_pf'])."</td>
                  <td>".money($r['ee_esi'])."</td><td>".money($r['er_esi'])."</td>
                  <td class='fw-bold'>".money($total)."</td></tr>";
        }
        if (!$data) echo "<tr><td colspan='9' class='text-center text-muted py-3'>No PF data for selected period</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── TDS Summary ───────────────────────────────────────────
    case 'tds_summary':
        $data = tdsSummary($db,$month,$year);
        echo "<div class='pc-card'><div class='pc-card-title'>TDS Summary — ".monthName($month)." $year</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Emp ID</th><th>Name</th><th>PAN</th><th>Regime</th><th>Gross Income</th><th>Taxable Income</th><th>Tax Liability</th><th>TDS This Month</th><th>TDS YTD</th></tr></thead><tbody>";
        $tot = ['gross_income'=>0,'net_taxable_income'=>0,'tax_liability'=>0,'tds_this_month'=>0,'tds_ytd'=>0];
        foreach ($data as $r) {
            foreach ($tot as $k=>$_) $tot[$k] += $r[$k];
            echo "<tr><td>".clean($r['employee_id'])."</td><td class='fw-semibold'>".clean($r['first_name'].' '.$r['last_name'])."</td>
                  <td><code>".clean($r['pan_number']??'—')."</code></td>
                  <td>".statusBadge($r['tax_regime']==='new'?'active':'pending')." ".ucfirst($r['tax_regime'])."</td>
                  <td>".money($r['gross_income'])."</td><td>".money($r['net_taxable_income'])."</td>
                  <td>".money($r['tax_liability'])."</td>
                  <td class='fw-bold'>".money($r['tds_this_month'])."</td>
                  <td>".money($r['tds_ytd'])."</td></tr>";
        }
        echo "<tr style='background:var(--pc-brand-light);font-weight:700'><td colspan='4'>TOTAL</td>
              <td>".money($tot['gross_income'])."</td><td>".money($tot['net_taxable_income'])."</td>
              <td>".money($tot['tax_liability'])."</td><td>".money($tot['tds_this_month'])."</td><td>".money($tot['tds_ytd'])."</td></tr>";
        if (!$data) echo "<tr><td colspan='9' class='text-center text-muted py-3'>No TDS data. Process payroll first.</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── Recruitment ───────────────────────────────────────────
    case 'recruitment':
        $data = recruitmentReport($db);
        echo "<div class='pc-card'><div class='pc-card-title'>Recruitment Report</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Position</th><th>Dept</th><th>Openings</th><th>Applicants</th><th>Interview</th><th>Joined</th><th>Rejected</th><th>Status</th><th>Posted</th></tr></thead><tbody>";
        foreach ($data as $r) {
            echo "<tr><td class='fw-semibold'>".clean($r['title'])."</td><td>".clean($r['dept']??'—')."</td>
                  <td>{$r['openings']}</td><td><span class='badge' style='background:var(--pc-blue-bg);color:var(--pc-blue)'>{$r['applicants']}</span></td>
                  <td>{$r['interview']}</td>
                  <td class='text-success fw-bold'>{$r['joined']}</td>
                  <td class='text-danger'>{$r['rejected']}</td>
                  <td>".statusBadge($r['status'])."</td><td>".fmtDate($r['posted_date'])."</td></tr>";
        }
        if (!$data) echo "<tr><td colspan='9' class='text-center text-muted py-3'>No job openings found</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── Birthday ──────────────────────────────────────────────
    case 'birthday':
        $data = birthdayReport($db);
        echo "<div class='pc-card'><div class='pc-card-title'>Upcoming Birthdays — Next 30 Days</div>";
        if ($data) {
            echo "<div class='pc-table-wrap'><table class='pc-table'><thead><tr><th>Employee</th><th>Dept</th><th>Birthday</th><th>Turning Age</th></tr></thead><tbody>";
            foreach ($data as $e) {
                echo "<tr><td class='fw-semibold'>".clean($e['first_name'].' '.$e['last_name'])."<br><small class='text-muted'>".clean($e['employee_id'])."</small></td>
                      <td>".clean($e['dept']??'—')."</td>
                      <td>".fmtDate($e['date_of_birth'],'d M')."</td>
                      <td><span class='badge' style='background:var(--pc-amber-bg);color:var(--pc-amber)'>{$e['turning_age']} yrs</span></td></tr>";
            }
            echo "</tbody></table></div>";
        } else {
            echo "<div class='text-center py-5 text-muted'><i class='ti ti-cake' style='font-size:36px;opacity:0.3'></i><br>No birthdays in the next 30 days</div>";
        }
        echo "</div>";
        break;

    // ── New Joiners ───────────────────────────────────────────
    case 'new_joiners':
        $data = newJoiners($db,$month,$year);
        echo "<div class='pc-card'><div class='pc-card-title'>New Joiners — ".monthName($month)." $year (".count($data)." employees)</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Emp ID</th><th>Name</th><th>Dept</th><th>Designation</th><th>Joining Date</th><th>Type</th></tr></thead><tbody>";
        foreach ($data as $r) {
            echo "<tr><td>".clean($r['employee_id'])."</td><td class='fw-semibold'>".clean($r['first_name'].' '.$r['last_name'])."</td>
                  <td>".clean($r['dept']??'—')."</td><td>".clean($r['designation']??'—')."</td>
                  <td>".fmtDate($r['date_of_joining'])."</td>
                  <td>".ucfirst($r['employment_type'])."</td></tr>";
        }
        if (!$data) echo "<tr><td colspan='6' class='text-center text-muted py-3'>No joiners in ".monthName($month)." $year</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    // ── Attrition ─────────────────────────────────────────────
    case 'attrition':
        $data = attritionReport($db,$year);
        // FIX (07 Jul 2026): scope to current org.
        [$totOrgClause, $totOrgParams] = orgScopeClause($db, 'company_id');
        $total = $db->fetchOne("SELECT COUNT(*) AS c FROM employees WHERE status='active' AND $totOrgClause", $totOrgParams);
        $rate  = ($total['c']??0) > 0 ? round(count($data)/($total['c']+count($data))*100,2) : 0;
        echo "<div class='pc-card mb-3'><div class='d-flex gap-3'>
              <div class='pc-stat flex-fill'><div class='pc-stat-val'>".count($data)."</div><div class='pc-stat-label'>Exits in $year</div></div>
              <div class='pc-stat flex-fill'><div class='pc-stat-val'>{$rate}%</div><div class='pc-stat-label'>Attrition Rate</div></div>
              </div></div>";
        echo "<div class='pc-card'><div class='pc-card-title'>Attrition Report — $year</div><div class='pc-table-wrap'><table class='pc-table'>";
        echo "<thead><tr><th>Emp ID</th><th>Name</th><th>Dept</th><th>Designation</th><th>Joined</th><th>Status</th><th>Service</th></tr></thead><tbody>";
        foreach ($data as $r) {
            echo "<tr><td>".clean($r['employee_id'])."</td><td class='fw-semibold'>".clean($r['first_name'].' '.$r['last_name'])."</td>
                  <td>".clean($r['dept']??'—')."</td><td>".clean($r['designation']??'—')."</td>
                  <td>".fmtDate($r['date_of_joining'])."</td>
                  <td>".statusBadge($r['status'])."</td>
                  <td>{$r['service_years']} yrs</td></tr>";
        }
        if (!$data) echo "<tr><td colspan='7' class='text-center text-muted py-3'>No exits recorded in $year</td></tr>";
        echo "</tbody></table></div></div>";
        break;

    default:
        echo "<div class='pc-card text-center py-5 text-muted'><i class='ti ti-chart-bar d-block mb-2' style='font-size:36px;opacity:0.3'></i>Select a report type from the HR Reports hub.</div>";
}
?>
<?php endif; ?>
<style>@media print { .pc-topbar,.pc-sidebar,.pc-page-header,.no-print,.pc-card:first-child { display:none !important; } }</style>
<?php include __DIR__ . '/../../includes/footer.php'; ?>