<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db     = Database::getInstance();
$page   = 'Summary Report';
$month  = intval($_GET['month'] ?? date('n'));
$year   = intval($_GET['year']  ?? date('Y'));
$format = $_GET['format'] ?? 'html';
$months = ['','January','February','March','April','May','June','July','August','September','October','November','December'];

// FIX (07 Jul 2026): payroll_runs now has company_id (see the Payroll
// batch) — without this scope, this could pick up a DIFFERENT
// organization's run for the same month.
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$run     = $db->fetchOne("SELECT * FROM payroll_runs WHERE month=? AND year=? AND $orgClause", array_merge([$month,$year], $orgParams));
$details = $run ? $db->fetchAll("SELECT pd.*,e.department_id,d.name AS dept FROM payroll_details pd JOIN employees e ON e.id=pd.employee_id LEFT JOIN departments d ON d.id=e.department_id WHERE pd.payroll_run_id=?", [$run['id']]) : [];

// Department-wise summary
$deptSummary = [];
foreach ($details as $d) {
    $dept = $d['dept'] ?? 'Unassigned';
    if (!isset($deptSummary[$dept])) $deptSummary[$dept] = ['count'=>0,'gross'=>0,'deductions'=>0,'net'=>0,'pf'=>0,'esi'=>0,'pt'=>0,'tds'=>0];
    $deptSummary[$dept]['count']++;
    $deptSummary[$dept]['gross']      += $d['gross_salary']??0;
    $deptSummary[$dept]['deductions'] += $d['total_deductions']??0;
    $deptSummary[$dept]['net']        += $d['net_salary']??0;
    $deptSummary[$dept]['pf']         += $d['pf_employee']??0;
    $deptSummary[$dept]['esi']        += $d['esi_employee']??0;
    $deptSummary[$dept]['pt']         += $d['professional_tax']??0;
    $deptSummary[$dept]['tds']        += $d['income_tax']??0;
}

// CSV Export
if ($format === 'csv' && $deptSummary) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="summary_'.$months[$month].'_'.$year.'.csv"');
    header('Pragma: no-cache');
    $out = fopen('php://output','w');
    fputcsv($out,['Department','Employees','Gross Salary','PF','ESI','PT','TDS','Total Deductions','Net Pay','Avg Net']);
    foreach ($deptSummary as $dept=>$s) fputcsv($out,[$dept,$s['count'],$s['gross'],$s['pf'],$s['esi'],$s['pt'],$s['tds'],$s['deductions'],$s['net'],$s['count']>0?round($s['net']/$s['count'],2):0]);
    fclose($out); exit;
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2 align-items-end">
    <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?>" <?=$month==$m?'selected':''?>><?=$months[$m]?></option><?php endfor; ?>
      </select></div>
    <div><label class="pc-label">Year</label>
      <select name="year" class="form-select form-select-sm">
        <?php for($y=date('Y');$y>=date('Y')-3;$y--): ?><option value="<?=$y?>" <?=$year==$y?'selected':''?>><?=$y?></option><?php endfor; ?>
      </select></div>
    <button class="btn btn-pc btn-sm"><i class="ti ti-search me-1"></i>Generate</button>
    <?php if($run && $deptSummary): ?>
    <a href="?month=<?=$month?>&year=<?=$year?>&format=csv" 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>
    <?php endif; ?>
  </form>
</div>

<?php if ($run && $details): ?>
<div class="row g-3 mb-3">
  <?php foreach([['Employees Paid',$run['total_employees']??count($details),'blue','ti-users'],['Total Gross','₹'.number_format(($run['total_gross']??0)/100000,2).'L','green','ti-cash'],['Deductions','₹'.number_format(($run['total_deductions']??0)/100000,2).'L','red','ti-minus'],['Net Pay','₹'.number_format(($run['total_net']??0)/100000,2).'L','brand','ti-wallet']] as [$lbl,$val,$clr,$ico]): ?>
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon <?=$clr?>" style="width:42px;height:42px;font-size:20px"><i class="ti <?=$ico?>"></i></div><div class="pc-stat-val" style="font-size:18px"><?=$val?></div><div class="pc-stat-label"><?=$lbl?></div></div></div>
  <?php endforeach; ?>
</div>
<div class="row g-3">
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title">Department-wise Summary — <?=$months[$month]?> <?=$year?></div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Department</th><th>Employees</th><th>Gross</th><th>PF</th><th>ESI</th><th>TDS</th><th>Total Ded</th><th>Net Pay</th><th>Avg Net</th></tr></thead>
          <tbody>
          <?php $tg=$td=$tn=0; foreach($deptSummary as $dept=>$s): $tg+=$s['gross'];$td+=$s['deductions'];$tn+=$s['net']; ?>
          <tr>
            <td class="fw-semibold"><?=clean($dept)?></td>
            <td><?=$s['count']?></td>
            <td>₹<?=number_format($s['gross'],0)?></td>
            <td>₹<?=number_format($s['pf'],0)?></td>
            <td>₹<?=number_format($s['esi'],0)?></td>
            <td>₹<?=number_format($s['tds'],0)?></td>
            <td class="text-danger">₹<?=number_format($s['deductions'],0)?></td>
            <td class="fw-bold text-success">₹<?=number_format($s['net'],0)?></td>
            <td class="text-muted">₹<?=number_format($s['count']>0?$s['net']/$s['count']:0,0)?></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
          <tfoot><tr style="background:var(--pc-brand-light);font-weight:700">
            <td colspan="2">Total</td>
            <td>₹<?=number_format($tg,0)?></td><td colspan="3"></td>
            <td class="text-danger">₹<?=number_format($td,0)?></td>
            <td class="text-success">₹<?=number_format($tn,0)?></td>
            <td></td>
          </tr></tfoot>
        </table>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title">Cost Breakdown</div>
      <?php $erPf=array_sum(array_column($details,'pf_employer'??0)); $erEsi=array_sum(array_column($details,'esi_employer'??0));
      foreach([['Gross Salary',$run['total_gross']??0,'brand'],['PF — Employer',$erPf,'amber'],['ESI — Employer',$erEsi,'blue'],['Total CTC',($run['total_gross']??0)+$erPf+$erEsi,'green']] as [$lbl,$val,$clr]): ?>
      <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:12.5px">
        <span class="text-muted"><?=$lbl?></span>
        <span class="fw-bold" style="color:var(--pc-<?=$clr?>)">₹<?=number_format($val,2)?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php else: ?>
<div class="pc-card"><div class="text-muted text-center py-4">No payroll data for <?=$months[$month]?> <?=$year?>. Process payroll first.</div></div>
<?php endif; ?>
<style>@media print{.pc-topbar,.pc-sidebar,.pc-page-header,.pc-card:first-child{display:none!important}}</style>
<?php include __DIR__ . '/../../includes/footer.php'; ?>