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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = $_POST["action"] ?? "";
    $runId  = postInt("run_id");
    // FIX (07 Jul 2026): confirm this payroll run belongs to a company in
    // the current organization before posting/reversing it.
    $orgCompanies = orgCompanyIds($db);
    $runOk = $orgCompanies ? $db->fetchOne(
        "SELECT id FROM payroll_runs WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
        array_merge([$runId], $orgCompanies)
    ) : null;
    if (!$runOk) {
        setFlash("error", "Payroll run not found.");
    } elseif ($action === "post") {
        $db->execute("UPDATE payroll_runs SET status='posted',posted_by=?,posted_at=NOW() WHERE id=? AND status='processed'", [currentUser()["id"],$runId]);
        setFlash("success","Payroll posted successfully.");
    } elseif ($action === "reverse") {
        $db->execute("UPDATE payroll_runs SET status='processed',posted_by=NULL,posted_at=NULL WHERE id=? AND status='posted'", [$runId]);
        setFlash("success","Payroll posting reversed.");
    }
    header("Location: ".BASE_URL."/modules/payroll/post_salary.php"); exit;
}

// FIX: scope the runs list to the current organization's companies.
[$orgClause, $orgParams] = orgScopeClause($db, 'pr.company_id');
$runs = $db->fetchAll("SELECT pr.*,CONCAT(u.username) AS processed_by_name FROM payroll_runs pr LEFT JOIN users u ON u.id=pr.processed_by WHERE $orgClause ORDER BY pr.year DESC,pr.month DESC", $orgParams);
$months = ["","January","February","March","April","May","June","July","August","September","October","November","December"];

include __DIR__ . "/../../includes/header.php";
?>
<div class="pc-card">
  <div class="pc-card-title"><i class="ti ti-send me-2"></i>Payroll Posting</div>
  <div class="pc-table-wrap">
    <table class="pc-table">
      <thead><tr><th>Period</th><th>Employees</th><th>Total Gross</th><th>Total Deductions</th><th>Net Pay</th><th>Status</th><th>Posted At</th><th>Action</th></tr></thead>
      <tbody>
      <?php foreach($runs as $r): ?>
      <tr>
        <td class="fw-bold"><?=$months[$r["month"]]." ".$r["year"]?></td>
        <td><?=$r["total_employees"]?></td>
        <td>₹<?=number_format($r["total_gross"],2)?></td>
        <td>₹<?=number_format($r["total_deductions"],2)?></td>
        <td class="fw-bold text-success">₹<?=number_format($r["total_net"],2)?></td>
        <td><?=statusBadge($r["status"])?></td>
        <td><?=$r["posted_at"]?fmtDate($r["posted_at"]):"—"?></td>
        <td>
          <?php if($r["status"]==="processed"): ?>
          <form method="POST" class="d-inline" onsubmit="return confirm('Post payroll for <?=$months[$r["month"]]." ".$r["year"]?>? This will lock the payroll.')">
            <?=csrfField()?><input type="hidden" name="action" value="post"><input type="hidden" name="run_id" value="<?=$r["id"]?>">
            <button class="btn btn-sm btn-success">Post Payroll</button>
          </form>
          <?php elseif($r["status"]==="posted"): ?>
          <form method="POST" class="d-inline" onsubmit="return confirm('Reverse posting? This will unlock the payroll.')">
            <?=csrfField()?><input type="hidden" name="action" value="reverse"><input type="hidden" name="run_id" value="<?=$r["id"]?>">
            <button class="btn btn-sm btn-outline-warning">Reverse</button>
          </form>
          <?php else: ?>—<?php endif; ?>
        </td>
      </tr>
      <?php endforeach; if(!$runs): ?><tr><td colspan="8" class="text-center text-muted py-3">No payroll runs found. Process payroll first.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include __DIR__ . "/../../includes/footer.php"; ?>