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

// FIX (07 Jul 2026): exports PAN, UAN, and bank account numbers with no
// organization scoping at all — restricted to the current org's companies.
$orgCompanies = orgCompanyIds($db);
$run = $orgCompanies ? $db->fetchOne(
    "SELECT * FROM payroll_runs WHERE month=? AND year=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
    array_merge([$month,$year], $orgCompanies)
) : null;
$details = $run ? $db->fetchAll("SELECT pd.*,
    e.employee_id AS emp_code, e.first_name, e.last_name, e.pan_number, e.uan_number,
    d.name AS dept, des.name AS designation
    FROM payroll_details pd
    JOIN employees e ON e.id=pd.employee_id
    LEFT JOIN departments d ON d.id=e.department_id
    LEFT JOIN designations des ON des.id=e.designation_id
    WHERE pd.payroll_run_id=?
    ORDER BY e.employee_id", [$run['id']]) : [];

if ($format === 'csv') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="payroll_'.$months[$month].'_'.$year.'.csv"');
    header('Pragma: no-cache');
    $out = fopen('php://output','w');
    fputcsv($out,['Emp Code','Name','PAN','UAN','Dept','Designation',
        'Present Days','LOP Days',
        'Basic','HRA','DA','Conveyance','Medical','Special Allowance','LTA','Incentive','Bonus','Arrears','Other Earnings','Gross Salary',
        'PF (EE)','PF (ER)','ESI (EE)','ESI (ER)','Professional Tax','Income Tax','Advance Recovery','Loan Recovery','Other Deductions','Total Deductions',
        'Net Salary','Payment Status']);
    foreach ($details as $d) {
        fputcsv($out,[
            $d['emp_code'], $d['first_name'].' '.$d['last_name'], $d['pan_number']??'', $d['uan_number']??'',
            $d['dept']??'', $d['designation']??'',
            $d['present_days']??0, $d['lop_days']??0,
            $d['basic']??0, $d['hra']??0, $d['da']??0, $d['conveyance']??0,
            $d['medical']??0, $d['special_allowance']??0, $d['lta']??0,
            $d['incentive']??0, $d['bonus']??0, $d['arrears']??0, $d['other_earnings']??0,
            $d['gross_salary']??0,
            $d['pf_employee']??0, $d['pf_employer']??0,
            $d['esi_employee']??0, $d['esi_employer']??0,
            $d['professional_tax']??0, $d['income_tax']??0,
            $d['advance_recovery']??0, $d['loan_recovery']??0, $d['other_deductions']??0,
            $d['total_deductions']??0, $d['net_salary']??0, $d['payment_status']??'pending'
        ]);
    }
    fclose($out); exit;
}

// Bank file format (NEFT/RTGS)
if ($format === 'bank') {
    header('Content-Type: text/plain; charset=UTF-8');
    header('Content-Disposition: attachment; filename="bank_transfer_'.$months[$month].'_'.$year.'.txt"');
    header('Pragma: no-cache');
    $bank_details = $run ? $db->fetchAll("SELECT pd.net_salary, e.first_name, e.last_name,
        eba.account_number, eba.ifsc_code, eba.account_holder_name, bk.name AS bank_name
        FROM payroll_details pd
        JOIN employees e ON e.id=pd.employee_id
        LEFT JOIN employee_bank_accounts eba ON eba.employee_id=pd.employee_id AND eba.is_primary=1
        LEFT JOIN banks bk ON bk.id=eba.bank_id
        WHERE pd.payroll_run_id=?
        ORDER BY e.employee_id", [$run['id']]) : [];
    echo "NEFT/RTGS Salary Transfer — ".$months[$month]." $year\n";
    echo str_repeat('-',80)."\n";
    echo sprintf("%-5s %-30s %-20s %-15s %15s\n",'#','Beneficiary Name','Account Number','IFSC','Amount');
    echo str_repeat('-',80)."\n";
    $total = 0; $i=1;
    foreach ($bank_details as $b) {
        echo sprintf("%-5d %-30s %-20s %-15s %15s\n",
            $i++, $b['account_holder_name'] ?: $b['first_name'].' '.$b['last_name'],
            $b['account_number']??'N/A', $b['ifsc_code']??'N/A',
            number_format($b['net_salary'],2));
        $total += $b['net_salary'];
    }
    echo str_repeat('-',80)."\n";
    echo sprintf("%-52s %15s\n",'TOTAL',number_format($total,2))."\n";
    exit;
}

// HTML view (when accessed directly without format param)
$page = 'Export Payroll';
include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2 align-items-end flex-wrap">
    <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':''?>><?=$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?>" <?=$y===$year?'selected':''?>><?=$y?></option><?php endfor; ?>
      </select></div>
    <button class="btn btn-pc btn-sm"><i class="ti ti-search me-1"></i>Load</button>
    <?php if($run && $details): ?>
    <a href="?month=<?=$month?>&year=<?=$year?>&format=csv" class="btn btn-sm btn-outline-success"><i class="ti ti-file-spreadsheet me-1"></i>Full Payroll CSV</a>
    <a href="?month=<?=$month?>&year=<?=$year?>&format=bank" class="btn btn-sm btn-outline-primary"><i class="ti ti-building-bank me-1"></i>Bank Transfer File</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="pc-card">
  <div class="pc-card-title">Payroll Export — <?=$months[$month]?> <?=$year?>
    <span style="font-weight:400;font-size:12px"> | <?=count($details)?> employees | Net: ₹<?=number_format($run['total_net']??0,2)?></span>
  </div>
  <div class="pc-table-wrap"><table class="pc-table" style="font-size:12px">
    <thead><tr><th>Emp</th><th>Name</th><th>Dept</th><th>Gross</th><th>PF</th><th>ESI</th><th>PT</th><th>TDS</th><th>Total Ded</th><th>Net Pay</th><th>Status</th></tr></thead>
    <tbody>
    <?php foreach($details as $d): ?>
    <tr>
      <td><?=clean($d['emp_code'])?></td>
      <td class="fw-semibold"><?=clean($d['first_name'].' '.$d['last_name'])?></td>
      <td><?=clean($d['dept']??'—')?></td>
      <td>₹<?=number_format($d['gross_salary']??0,0)?></td>
      <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 class="text-danger fw-semibold">₹<?=number_format($d['total_deductions']??0,0)?></td>
      <td class="text-success fw-bold">₹<?=number_format($d['net_salary']??0,0)?></td>
      <td><?=statusBadge($d['payment_status']??'pending')?></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
    <tfoot><tr style="background:var(--pc-brand-light);font-weight:700">
      <td colspan="3">TOTAL — <?=count($details)?> employees</td>
      <td>₹<?=number_format($run['total_gross']??0,0)?></td>
      <td colspan="4"></td>
      <td class="text-danger">₹<?=number_format($run['total_deductions']??0,0)?></td>
      <td class="text-success">₹<?=number_format($run['total_net']??0,0)?></td>
      <td></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'; ?>