<?php
require_once __DIR__ . "/../../config/config.php";
require_once __DIR__ . "/../../includes/functions.php";
startSession(); requireLogin();
$db = Database::getInstance();
$page = "Disbursement";

$months = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
$selRun = cleanInt($_GET["run"] ?? 0);

// FIX (07 Jul 2026): this whole file exports bank account numbers and
// salary amounts (about as sensitive as it gets) with a run id from the
// URL and NO organization check — anyone logged in could export another
// organization's bank file just by changing ?run=. Scoped everything to
// the current org's companies below.
$orgCompanies = orgCompanyIds($db);
$runInOrg = $orgCompanies ? $db->fetchOne(
    "SELECT id FROM payroll_runs WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
    array_merge([$selRun], $orgCompanies)
) : null;
if ($selRun && !$runInOrg) { $selRun = 0; }

// Bank file export
if ($selRun && isset($_GET['export'])) {
    $run  = $db->fetchOne("SELECT * FROM payroll_runs WHERE id=?", [$selRun]);
    $bdet = $db->fetchAll("SELECT pd.net_salary, e.first_name, e.last_name, e.employee_id AS emp_code,
        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", [$selRun]);
    $mLabel = $run ? ($months[(int)$run['month']].' '.$run['year']) : 'Payroll';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="bank_file_'.str_replace(' ','_',$mLabel).'.csv"');
    header('Pragma: no-cache');
    $out = fopen('php://output','w');
    fputcsv($out,['Sl No','Emp Code','Beneficiary Name','Bank Name','Account Number','IFSC Code','Amount','Remarks']);
    $i=1; $total=0;
    foreach ($bdet as $b) {
        fputcsv($out,[$i++, $b['emp_code'], $b['account_holder_name']?:$b['first_name'].' '.$b['last_name'],
            $b['bank_name']??'', $b['account_number']??'', $b['ifsc_code']??'',
            number_format($b['net_salary'],2), 'Salary '.$mLabel]);
        $total += $b['net_salary'];
    }
    fputcsv($out,['','','','','','TOTAL',number_format($total,2),'']);
    fclose($out); exit;
}
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$runs   = $db->fetchAll("SELECT * FROM payroll_runs WHERE status IN ('posted','disbursed') AND $orgClause ORDER BY year DESC,month DESC", $orgParams);
$details = $selRun ? $db->fetchAll("SELECT pd.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code,b.account_number,b.ifsc_code,bk.name AS bank_name FROM payroll_details pd JOIN employees e ON e.id=pd.employee_id LEFT JOIN employee_bank_accounts b ON b.employee_id=pd.employee_id AND b.is_primary=1 LEFT JOIN banks bk ON bk.id=b.bank_id WHERE pd.payroll_run_id=? ORDER BY e.first_name", [$selRun]) : [];
$run = $selRun ? $db->fetchOne("SELECT * FROM payroll_runs WHERE id=?",[$selRun]) : null;

if ($_SERVER["REQUEST_METHOD"]==="POST") {
    verifyCsrf();
    $db->execute("UPDATE payroll_runs SET status='disbursed' WHERE id=?", [postInt("run_id")]);
    $db->execute("UPDATE payroll_details SET payment_status='paid' WHERE payroll_run_id=?", [postInt("run_id")]);
    setFlash("success","Disbursement marked as complete.");
    header("Location: ".BASE_URL."/modules/payroll/disbursement.php?run=".postInt("run_id")); exit;
}

include __DIR__ . "/../../includes/header.php";
?>
<div class="row g-3 mb-3">
  <div class="col-12">
    <div class="pc-card">
      <div class="d-flex gap-3 align-items-end">
        <div><label class="pc-label">Select Payroll Period</label>
          <select class="form-select form-select-sm" style="width:220px" onchange="location='?run='+this.value">
            <option value="">-- Select --</option>
            <?php foreach($runs as $r): ?><option value="<?=$r["id"]?>" <?=$selRun==$r["id"]?"selected":""?>><?=$months[$r["month"]]." ".$r["year"]?> (<?=ucfirst($r["status"])?>)</option><?php endforeach; ?>
          </select></div>
        <?php if($run && $run["status"]==="posted"): ?>
        <form method="POST" onsubmit="return confirm('Mark all as disbursed?')">
          <?=csrfField()?><input type="hidden" name="run_id" value="<?=$selRun?>">
          <button class="btn btn-pc btn-sm"><i class="ti ti-building-bank me-1"></i>Mark as Disbursed</button>
        </form>
        <?php endif; ?>
        <?php if($details): ?>
        <a href="?run=<?=$selRun?>&export=1" class="btn btn-sm btn-outline-secondary"><i class="ti ti-download me-1"></i>Export Bank File</a>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
<?php if($details): ?>
<div class="pc-card">
  <div class="pc-card-title">Disbursement Details — <?=$months[$run["month"]]." ".$run["year"]?> &nbsp; <span style="font-weight:400;font-size:12px;color:var(--pc-text2)">Total: ₹<?=number_format($run["total_net"],2)?></span></div>
  <div class="pc-table-wrap">
    <table class="pc-table">
      <thead><tr><th>Employee</th><th>Bank</th><th>A/C No</th><th>IFSC</th><th>Net Salary</th><th>Status</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["bank_name"]??'—')?></td>
        <td><?=clean($d["account_number"]??'—')?></td>
        <td><?=clean($d["ifsc_code"]??'—')?></td>
        <td class="fw-bold">₹<?=number_format($d["net_salary"],2)?></td>
        <td><?=statusBadge($d["payment_status"])?></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . "/../../includes/footer.php"; ?>