<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db   = Database::getInstance();
$page = 'Payroll Report';

[$plainOrg, $plainOrgP] = orgScopeClause($db, 'company_id');
$month = cleanInt($_GET['month'] ?? date('n'));
$year  = cleanInt($_GET['year']  ?? date('Y'));
$type  = get('type') ?: 'salary_summary';

$run = $db->fetchOne("SELECT * FROM payroll_runs WHERE month=? AND year=? AND $plainOrg", array_merge([$month,$year], $plainOrgP));

if ($type === 'jv_export' && isset($_GET['export']) && $run) {
    $heads = $db->fetchOne(
        "SELECT SUM(basic) basic, SUM(hra) hra, SUM(da) da, SUM(conveyance) conveyance, SUM(medical) medical,
                SUM(special_allowance) special_allowance, SUM(lta) lta, SUM(bonus) bonus, SUM(arrears) arrears,
                SUM(other_earnings) other_earnings, SUM(gross_salary) gross_salary,
                SUM(pf_employee) pf_employee, SUM(esi_employee) esi_employee,
                SUM(professional_tax) professional_tax, SUM(income_tax) income_tax, SUM(net_salary) net_salary
           FROM payroll_details WHERE payroll_run_id=?", [$run['id']]
    );
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="jv_export_' . monthName($month) . "_$year.csv\"");
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Head', 'Type', 'Amount']);
    $earningLabels = ['basic'=>'Basic','hra'=>'HRA','da'=>'DA','conveyance'=>'Conveyance','medical'=>'Medical',
        'special_allowance'=>'Special Allowance','lta'=>'LTA','bonus'=>'Bonus','arrears'=>'Arrears','other_earnings'=>'Other Earnings'];
    foreach ($earningLabels as $k => $label) {
        fputcsv($out, [$label, 'Debit (Expense)', number_format((float)$heads[$k], 2, '.', '')]);
    }
    $deductionLabels = ['pf_employee'=>'PF (Employee)','esi_employee'=>'ESI (Employee)','professional_tax'=>'Professional Tax','income_tax'=>'Income Tax'];
    foreach ($deductionLabels as $k => $label) {
        fputcsv($out, [$label, 'Credit (Payable)', number_format((float)$heads[$k], 2, '.', '')]);
    }
    fputcsv($out, ['Net Salary Payable', 'Credit (Bank/Payable)', number_format((float)$heads['net_salary'], 2, '.', '')]);
    fclose($out); exit;
}

$details = $run ? $db->fetchAll(
    "SELECT e.employee_id, CONCAT(e.first_name,' ',e.last_name) AS name, d.name AS dept,
            pd.basic, pd.hra, pd.da, pd.gross_salary, pd.pf_employee, pd.esi_employee,
            pd.professional_tax, pd.income_tax, pd.total_deductions, pd.net_salary
       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=? ORDER BY e.employee_id",
    [$run['id']]
) : [];

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-3">
    <div class="pc-card p-2">
      <div class="pc-card-title">Payroll Reports</div>
      <div class="list-group list-group-flush">
        <a href="?type=salary_summary&month=<?=$month?>&year=<?=$year?>" class="list-group-item list-group-item-action small <?=$type==='salary_summary'?'active':''?>">Salary Summary</a>
        <a href="<?=BASE_URL?>/modules/payroll/payslip.php" class="list-group-item list-group-item-action small">Payslip</a>
        <a href="?type=jv_export&month=<?=$month?>&year=<?=$year?>" class="list-group-item list-group-item-action small <?=$type==='jv_export'?'active':''?>">JV Export</a>
      </div>
    </div>
  </div>
  <div class="col-md-9">
    <div class="pc-card mb-3">
      <form method="GET" class="d-flex gap-2 align-items-end">
        <input type="hidden" name="type" value="<?= $type ?>">
        <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':''?>><?=monthName($m)?></option><?php endfor; ?>
          </select></div>
        <div><label class="pc-label">Year</label>
          <input type="number" name="year" value="<?=$year?>" class="form-control form-control-sm" style="width:90px"></div>
        <button class="btn btn-pc btn-sm">Apply</button>
        <?php if ($type === 'jv_export' && $run): ?>
        <a href="?type=jv_export&month=<?=$month?>&year=<?=$year?>&export=1" class="btn btn-outline-primary btn-sm ms-auto"><i class="ti ti-download me-1"></i>Download CSV</a>
        <?php endif; ?>
      </form>
    </div>

    <?php if (!$run): ?>
      <div class="alert alert-info">No processed payroll run found for <?=monthName($month)?> <?=$year?>.</div>
    <?php elseif ($type === 'salary_summary'): ?>
    <div class="pc-card">
      <div class="pc-card-title">Salary Summary — <?=monthName($month)?> <?=$year?> (<?=count($details)?> employees)</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Emp Code</th><th>Name</th><th>Dept</th><th>Basic</th><th>HRA</th><th>DA</th><th>Gross</th><th>PF</th><th>ESI</th><th>PT</th><th>TDS</th><th>Total Deductions</th><th>Net Pay</th></tr></thead>
          <tbody>
          <?php $tot = ['gross'=>0,'net'=>0]; foreach ($details as $d): $tot['gross']+=$d['gross_salary']; $tot['net']+=$d['net_salary']; ?>
          <tr>
            <td><?=clean($d['employee_id'])?></td><td><?=clean($d['name'])?></td><td><?=clean($d['dept']??'—')?></td>
            <td><?=number_format($d['basic'],2)?></td><td><?=number_format($d['hra'],2)?></td><td><?=number_format($d['da'],2)?></td>
            <td><?=number_format($d['gross_salary'],2)?></td><td><?=number_format($d['pf_employee'],2)?></td>
            <td><?=number_format($d['esi_employee'],2)?></td><td><?=number_format($d['professional_tax'],2)?></td>
            <td><?=number_format($d['income_tax'],2)?></td><td><?=number_format($d['total_deductions'],2)?></td>
            <td class="fw-bold"><?=number_format($d['net_salary'],2)?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$details): ?><tr><td colspan="13" class="text-center text-muted py-4">No records</td></tr><?php endif; ?>
          </tbody>
          <?php if ($details): ?>
          <tfoot><tr class="fw-bold"><td colspan="6" class="text-end">Total</td><td><?=number_format($tot['gross'],2)?></td><td colspan="5"></td><td><?=number_format($tot['net'],2)?></td></tr></tfoot>
          <?php endif; ?>
        </table>
      </div>
    </div>
    <?php elseif ($type === 'jv_export'): ?>
    <div class="pc-card">
      <div class="pc-card-title">Journal Voucher Preview — <?=monthName($month)?> <?=$year?></div>
      <p class="text-muted small">This groups the run's totals into Debit (expense heads: Basic/HRA/DA/etc) and Credit (payable heads: PF/ESI/PT/TDS/Net Salary) lines for import into your accounting system. Use "Download CSV" above to export.</p>
      <div class="alert alert-warning small"><i class="ti ti-info-circle me-1"></i>This is a generic debit/credit split, not mapped to your specific chart of accounts / GL codes — have your accounts team confirm the head-to-ledger mapping before posting.</div>
    </div>
    <?php endif; ?>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
