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

// FIX (07 Jul 2026): scope to current org — this exposed salary details
// (gross, PF, ESI, TDS, net pay) across every organization.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$details = $db->fetchAll("SELECT pd.*,
    CONCAT(e.first_name,' ',e.last_name) AS emp_name, e.employee_id AS emp_code,
    d.name AS dept
    FROM payroll_details pd
    JOIN employees e ON e.id=pd.employee_id
    JOIN payroll_runs pr ON pr.id=pd.payroll_run_id
    LEFT JOIN departments d ON d.id=e.department_id
    WHERE pr.month=? AND pr.year=? AND $orgClause
    ORDER BY e.first_name", array_merge([$month,$year], $orgParams));

// ── CSV Export ────────────────────────────────────────────────
if ($format === 'csv' && $details) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="earnings_deductions_'.$months[$month].'_'.$year.'.csv"');
    header('Pragma: no-cache');
    $out = fopen('php://output','w');
    $hdr = ['Emp Code','Name','Dept','Basic','HRA','DA','Conveyance','Medical','Special Allowance','LTA','Bonus','Arrears','Other Earnings','Gross Salary','PF(EE)','ESI(EE)','PT','TDS','Advance','Other Deductions','Total Deductions','Net Pay'];
    fputcsv($out,$hdr);
    foreach ($details as $d) {
        fputcsv($out,[
            $d['emp_code'], $d['emp_name'], $d['dept']??'',
            $d['basic']??0, $d['hra']??0, $d['da']??0, $d['conveyance']??0,
            $d['medical']??0, $d['special_allowance']??0, $d['lta']??0,
            $d['bonus']??0, $d['arrears']??0, $d['other_earnings']??0,
            $d['gross_salary']??0, $d['pf_employee']??0, $d['esi_employee']??0,
            $d['professional_tax']??0, $d['income_tax']??0, $d['advance_recovery']??0,
            $d['other_deductions']??0, $d['total_deductions']??0, $d['net_salary']??0,
        ]);
    }
    fclose($out); exit;
}

// ── Totals ────────────────────────────────────────────────────
$totals = ['gross_salary'=>0,'pf_employee'=>0,'esi_employee'=>0,'professional_tax'=>0,'income_tax'=>0,'advance_recovery'=>0,'total_deductions'=>0,'net_salary'=>0];
foreach ($details as $d) foreach ($totals as $k=>$_) $totals[$k] += ($d[$k]??0);

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2 flex-wrap 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>
    <div><label class="pc-label">View</label>
      <select name="type" class="form-select form-select-sm">
        <option value="both" <?=$type==='both'?'selected':''?>>Earnings + Deductions</option>
        <option value="earn" <?=$type==='earn'?'selected':''?>>Earnings Only</option>
        <option value="deduct" <?=$type==='deduct'?'selected':''?>>Deductions Only</option>
      </select></div>
    <button class="btn btn-pc btn-sm"><i class="ti ti-search me-1"></i>Generate</button>
    <?php if($details): ?>
    <a href="?month=<?=$month?>&year=<?=$year?>&type=<?=$type?>&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 ($details): ?>
<div class="row g-3 mb-3">
  <?php foreach([['Gross','gross_salary','green'],['PF','pf_employee','amber'],['ESI','esi_employee','blue'],['TDS','income_tax','red'],['Net Pay','net_salary','brand']] as [$lbl,$k,$clr]): ?>
  <div class="col"><div class="pc-stat"><div class="pc-stat-icon <?=$clr?>" style="width:38px;height:38px;font-size:16px"><i class="ti ti-cash"></i></div><div class="pc-stat-val" style="font-size:16px">₹<?=number_format($totals[$k],0)?></div><div class="pc-stat-label"><?=$lbl?></div></div></div>
  <?php endforeach; ?>
</div>
<div class="pc-card">
  <div class="pc-card-title"><?=$months[$month]?> <?=$year?> — Earnings & Deductions Register</div>
  <div class="pc-table-wrap">
    <table class="pc-table" style="font-size:11.5px">
      <thead>
        <tr>
          <th>Employee</th><th>Dept</th>
          <?php if($type!=='deduct'): ?><th>Basic</th><th>HRA</th><th>Special</th><th>Other Earn</th><th>Gross</th><?php endif; ?>
          <?php if($type!=='earn'): ?><th>PF</th><th>ESI</th><th>PT</th><th>TDS</th><th>Advance</th><th>Total Ded</th><?php endif; ?>
          <th>Net Pay</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($details as $d): ?>
      <tr>
        <td><div class="fw-semibold"><?=clean($d['emp_name'])?></div><small class="text-muted"><?=clean($d['emp_code'])?></small></td>
        <td><?=clean($d['dept']??'—')?></td>
        <?php if($type!=='deduct'): ?>
        <td>₹<?=number_format($d['basic']??0,0)?></td>
        <td>₹<?=number_format($d['hra']??0,0)?></td>
        <td>₹<?=number_format($d['special_allowance']??0,0)?></td>
        <td>₹<?=number_format($d['other_earnings']??0,0)?></td>
        <td class="fw-semibold">₹<?=number_format($d['gross_salary']??0,0)?></td>
        <?php endif; ?>
        <?php if($type!=='earn'): ?>
        <td>₹<?=number_format($d['pf_employee']??0,0)?></td>
        <td>₹<?=number_format($d['esi_employee']??0,0)?></td>
        <td>₹<?=number_format($d['professional_tax']??0,0)?></td>
        <td>₹<?=number_format($d['income_tax']??0,0)?></td>
        <td>₹<?=number_format($d['advance_recovery']??0,0)?></td>
        <td class="fw-semibold text-danger">₹<?=number_format($d['total_deductions']??0,0)?></td>
        <?php endif; ?>
        <td class="fw-bold text-success">₹<?=number_format($d['net_salary']??0,0)?></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr style="background:var(--pc-brand-light);font-weight:700">
          <td colspan="2">TOTAL</td>
          <?php if($type!=='deduct'): ?><td colspan="4"></td><td>₹<?=number_format($totals['gross_salary'],0)?></td><?php endif; ?>
          <?php if($type!=='earn'): ?><td colspan="4"></td><td></td><td class="text-danger">₹<?=number_format($totals['total_deductions'],0)?></td><?php endif; ?>
          <td class="text-success">₹<?=number_format($totals['net_salary'],0)?></td>
        </tr>
      </tfoot>
    </table>
  </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'; ?>