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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = $_POST["action"] ?? "";
    if ($action === "save") {
        $empId = postInt("employee_id"); $fy = post("fy");
        // FIX (07 Jul 2026): confirm target employee belongs to current org.
        $target = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
        if (!$target || !in_array($target['company_id'], orgCompanyIds($db))) {
            setFlash('error', 'Employee not found.');
            header("Location: ".BASE_URL."/modules/tds/investment.php"); exit;
        }
        $headIds = $_POST["head_id"] ?? [];
        $amounts = $_POST["declared_amount"] ?? [];
        foreach($headIds as $i=>$hid) {
            if (!($amounts[$i]??0)) continue;
            $existing = $db->fetchOne("SELECT id FROM investment_declarations WHERE employee_id=? AND financial_year=? AND tds_head_id=?",[$empId,$fy,$hid]);
            if ($existing) $db->execute("UPDATE investment_declarations SET declared_amount=?,status='submitted' WHERE id=?",[$amounts[$i],$existing["id"]]);
            else $db->execute("INSERT INTO investment_declarations (employee_id,financial_year,tds_head_id,declared_amount) VALUES (?,?,?,?)",[$empId,$fy,$hid,$amounts[$i]]);
        }
        setFlash("success","Investment declaration saved.");
    } elseif ($action === "verify") {
        // FIX: confirm this declaration belongs to a current-org employee.
        $orgCompanies = orgCompanyIds($db);
        $decl = $db->fetchOne(
            "SELECT d.id FROM investment_declarations d JOIN employees e ON e.id=d.employee_id WHERE d.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt("id")], $orgCompanies)
        );
        if ($decl) {
            $db->execute("UPDATE investment_declarations SET status='verified',verified_amount=declared_amount WHERE id=?",[postInt("id")]);
            setFlash("success","Declaration verified.");
        } else {
            setFlash("error","Declaration not found.");
        }
    }
    header("Location: ".BASE_URL."/modules/tds/investment.php"); exit;
}

$fy        = $_GET["fy"] ?? (date("Y")."-".(date("Y")+1));
$selEmp    = cleanInt($_GET["emp"] ?? 0);
// FIX: scope dropdown to org and reject ?emp=<other org's employee>.
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
if ($selEmp && !in_array($selEmp, array_column($employees, 'id'))) { $selEmp = 0; }
$heads     = $db->fetchAll("SELECT * FROM tds_heads WHERE is_active=1 ORDER BY section");
$decls     = $selEmp ? $db->fetchAll("SELECT d.*,t.section,t.name AS head_name,t.max_limit FROM investment_declarations d JOIN tds_heads t ON t.id=d.tds_head_id WHERE d.employee_id=? AND d.financial_year=? ORDER BY t.section",[$selEmp,$fy]) : [];
$declMap   = []; foreach($decls as $d) $declMap[$d["tds_head_id"]] = $d;

include __DIR__ . "/../../includes/header.php";
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2">
    <div><label class="pc-label">Employee</label><select name="emp" class="form-select form-select-sm" style="width:260px"><option value="">Select</option><?php foreach($employees as $e): ?><option value="<?=$e["id"]?>" <?=$selEmp==$e["id"]?"selected":""?>><?=clean($e["label"])?></option><?php endforeach; ?></select></div>
    <div><label class="pc-label">Financial Year</label><input type="text" name="fy" class="form-control form-control-sm" value="<?=clean($fy)?>" style="width:90px"></div>
    <button class="btn btn-pc btn-sm align-self-end">Go</button>
  </form>
</div>
<?php if($selEmp): ?>
<div class="row g-3">
  <div class="col-md-7">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-receipt-2 me-2"></i>Submit Declaration — FY <?=clean($fy)?></div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save"><input type="hidden" name="employee_id" value="<?=$selEmp?>"><input type="hidden" name="fy" value="<?=clean($fy)?>">
        <table class="pc-table">
          <thead><tr><th>Section</th><th>Description</th><th>Max Limit</th><th>Declared (₹)</th></tr></thead>
          <tbody>
          <?php foreach($heads as $h): $existing=$declMap[$h["id"]]??null; ?>
          <tr>
            <td><code><?=clean($h["section"])?></code><input type="hidden" name="head_id[]" value="<?=$h["id"]?>"></td>
            <td><?=clean($h["name"])?></td>
            <td><?=$h["max_limit"]>0?"₹".number_format($h["max_limit"]):"—"?></td>
            <td><input type="number" name="declared_amount[]" class="form-control form-control-sm" style="width:110px" value="<?=$existing["declared_amount"]??0?>" min="0" max="<?=$h["max_limit"]>0?$h["max_limit"]:9999999?>"></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <div class="mt-3"><button class="btn btn-pc btn-sm"><i class="ti ti-device-floppy me-1"></i>Save Declaration</button></div>
      </form>
    </div>
  </div>
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title">Submitted Declarations</div>
      <?php if($decls): ?>
      <?php $total=0; foreach($decls as $d): $total+=$d["declared_amount"]; ?>
      <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:12.5px">
        <div><code><?=clean($d["section"])?></code> <?=clean($d["head_name"])?></div>
        <div class="d-flex align-items-center gap-2">
          <span class="fw-bold">₹<?=number_format($d["declared_amount"],2)?></span>
          <?=statusBadge($d["status"])?>
          <?php if($d["status"]==="submitted"): ?>
          <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="verify"><input type="hidden" name="id" value="<?=$d["id"]?>"><button class="btn btn-xs btn-success py-0 px-1" style="font-size:9px">Verify</button></form>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
      <div class="d-flex justify-content-between pt-2 fw-bold"><span>Total Declared</span><span style="color:var(--pc-brand)">₹<?=number_format($total,2)?></span></div>
      <?php else: ?><div class="text-muted text-center small py-3">No declarations yet</div><?php endif; ?>
    </div>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . "/../../includes/footer.php"; ?>