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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    // FIX (07 Jul 2026): bank account data is sensitive — verify the
    // target employee/account actually belongs to the current org before
    // reading or writing anything.
    $orgCompanies = orgCompanyIds($db);
    if ($action === 'save') {
        $empId = postInt('employee_id');
        $target = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
        if (!$target || !in_array($target['company_id'], $orgCompanies)) {
            setFlash('error', 'Employee not found.');
            header('Location: '.BASE_URL.'/modules/employees/accounts.php'); exit;
        }
        $isPrimary = postInt('is_primary');
        if ($isPrimary) $db->execute("UPDATE employee_bank_accounts SET is_primary=0 WHERE employee_id=?", [$empId]);
        $existing = $db->fetchOne("SELECT id FROM employee_bank_accounts WHERE employee_id=? AND account_number=?", [$empId, post('account_number')]);
        if ($existing) {
            $db->execute("UPDATE employee_bank_accounts SET bank_id=?,account_holder_name=?,ifsc_code=?,branch_name=?,account_type=?,upi_id=?,payment_mode=?,is_primary=? WHERE id=?",
                [postInt('bank_id'),post('account_holder_name'),post('ifsc_code'),post('branch_name'),post('account_type'),post('upi_id'),post('payment_mode'),$isPrimary,$existing['id']]);
        } else {
            $db->execute("INSERT INTO employee_bank_accounts (employee_id,bank_id,account_holder_name,account_number,ifsc_code,branch_name,account_type,upi_id,payment_mode,is_primary) VALUES (?,?,?,?,?,?,?,?,?,?)",
                [$empId,postInt('bank_id'),post('account_holder_name'),post('account_number'),post('ifsc_code'),post('branch_name'),post('account_type'),post('upi_id'),post('payment_mode'),$isPrimary]);
        }
        setFlash('success','Bank account saved successfully.');
    } elseif ($action === 'delete') {
        $acct = $db->fetchOne(
            "SELECT a.id FROM employee_bank_accounts a JOIN employees e ON e.id=a.employee_id WHERE a.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt('id')], $orgCompanies)
        );
        if ($acct) {
            $db->execute("DELETE FROM employee_bank_accounts WHERE id=?", [postInt('id')]);
            setFlash('success','Account removed.');
        } else {
            setFlash('error','Account not found.');
        }
    }
    header('Location: '.BASE_URL.'/modules/employees/accounts.php'); exit;
}

$selEmp   = cleanInt($_GET['emp'] ?? 0);
[$acctOrgClause, $acctOrgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id, CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $acctOrgClause ORDER BY first_name", $acctOrgParams);
$banks     = $db->fetchAll("SELECT id,name FROM banks WHERE is_active=1 ORDER BY name");
// FIX: only show accounts/info if the selected employee is actually in this org.
$empIdsInOrg = array_column($employees, 'id');
$selEmpValid = $selEmp && in_array($selEmp, $empIdsInOrg);
$accounts  = $selEmpValid ? $db->fetchAll("SELECT a.*,b.name AS bank_name FROM employee_bank_accounts a LEFT JOIN banks b ON b.id=a.bank_id WHERE a.employee_id=? ORDER BY a.is_primary DESC", [$selEmp]) : [];
$empInfo   = $selEmpValid ? $db->fetchOne("SELECT * FROM employees WHERE id=?", [$selEmp]) : null;

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-12">
    <div class="pc-card mb-3">
      <form method="GET" class="d-flex gap-2 align-items-end">
        <div><label class="pc-label">Select Employee</label>
          <select name="emp" class="form-select form-select-sm" style="width:280px" onchange="this.form.submit()">
            <option value="">-- Select Employee --</option>
            <?php foreach($employees as $e): ?><option value="<?=$e['id']?>" <?=$selEmp==$e['id']?'selected':''?>><?=clean($e['label'])?></option><?php endforeach; ?>
          </select></div>
      </form>
    </div>
  </div>
</div>

<?php if($selEmp && $empInfo): ?>
<div class="row g-3">
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-credit-card me-2"></i>Add / Update Bank Account</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save"><input type="hidden" name="employee_id" value="<?=$selEmp?>">
        <div class="mb-2"><label class="pc-label">Account Holder Name</label><input type="text" name="account_holder_name" class="form-control form-control-sm" value="<?=clean($empInfo['first_name'].' '.$empInfo['last_name'])?>" required></div>
        <div class="mb-2"><label class="pc-label">Bank</label>
          <select name="bank_id" class="form-select form-select-sm"><option value="">Select Bank</option><?php foreach($banks as $b): ?><option value="<?=$b['id']?>"><?=clean($b['name'])?></option><?php endforeach; ?></select></div>
        <div class="mb-2"><label class="pc-label">Account Number</label><input type="text" name="account_number" class="form-control form-control-sm" required></div>
        <div class="mb-2"><label class="pc-label">IFSC Code</label><input type="text" name="ifsc_code" class="form-control form-control-sm" style="text-transform:uppercase"></div>
        <div class="mb-2"><label class="pc-label">Branch Name</label><input type="text" name="branch_name" class="form-control form-control-sm"></div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">Account Type</label>
            <select name="account_type" class="form-select form-select-sm"><option value="savings">Savings</option><option value="current">Current</option></select></div>
          <div class="col"><label class="pc-label">Payment Mode</label>
            <select name="payment_mode" class="form-select form-select-sm"><option value="bank_transfer">Bank Transfer</option><option value="cash">Cash</option><option value="cheque">Cheque</option><option value="upi">UPI</option></select></div>
        </div>
        <div class="mb-2"><label class="pc-label">UPI ID (optional)</label><input type="text" name="upi_id" class="form-control form-control-sm"></div>
        <div class="mb-3 form-check"><input type="checkbox" name="is_primary" value="1" class="form-check-input" id="isPrimary"><label class="form-check-label small" for="isPrimary">Set as Primary Account</label></div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-device-floppy me-1"></i>Save Account</button>
      </form>
    </div>
  </div>
  <div class="col-md-7">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-building-bank me-2"></i>Linked Accounts — <?=clean($empInfo['first_name'].' '.$empInfo['last_name'])?></div>
      <?php if($accounts): ?>
      <?php foreach($accounts as $a): ?>
      <div class="border rounded p-3 mb-2 position-relative" style="background:<?=$a['is_primary']?'var(--pc-brand-light)':'#fafbfd'?>">
        <?php if($a['is_primary']): ?><span class="badge position-absolute top-0 end-0 m-2" style="background:var(--pc-brand);color:#fff">Primary</span><?php endif; ?>
        <div class="fw-bold mb-1"><?=clean($a['bank_name']??'Bank')?> — <?=clean($a['account_type'])?></div>
        <div class="small text-muted mb-1">A/C: <strong><?=clean($a['account_number'])?></strong> &nbsp;|&nbsp; IFSC: <?=clean($a['ifsc_code'])?></div>
        <div class="small text-muted mb-2">Holder: <?=clean($a['account_holder_name'])?> &nbsp;|&nbsp; Mode: <?=ucfirst(str_replace('_',' ',$a['payment_mode']))?></div>
        <form method="POST" class="d-inline" onsubmit="return confirm('Remove this account?')">
          <?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$a['id']?>">
          <button class="btn btn-sm btn-outline-danger py-0"><i class="ti ti-trash me-1"></i>Remove</button>
        </form>
      </div>
      <?php endforeach; ?>
      <?php else: ?><div class="text-muted text-center py-3">No bank accounts linked yet.</div><?php endif; ?>
    </div>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>