<?php
// ============================================================
// modules/advance/index.php – Advance Application Module
// ============================================================
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db   = Database::getInstance();
$page = 'Advance Application';
$user = currentUser();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');

    if ($action === 'apply') {
        $empId     = hasRole('employee') ? $user['emp_id'] : postInt('employee_id');
        // FIX (07 Jul 2026): confirm target employee belongs to current org.
        if (!hasRole('employee')) {
            $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: index.php'); exit;
            }
        }
        $headId    = postInt('advance_head_id');
        $amount    = cleanFloat($_POST['amount_requested'] ?? 0);
        $instl     = postInt('installments');
        $purpose   = post('purpose');

        $head = $db->fetchOne("SELECT * FROM advance_heads WHERE id=? AND is_active=1", [$headId]);
        if (!$head) { setFlash('error','Invalid advance type'); header('Location: index.php'); exit; }
        if ($head['max_amount'] > 0 && $amount > $head['max_amount']) {
            setFlash('error', 'Amount exceeds limit: ' . money($head['max_amount']));
            header('Location: index.php'); exit;
        }

        // Interest calculation
        $rate      = $head['interest_rate'];
        $interest  = 0;
        if ($rate > 0 && $head['interest_type'] === 'simple') {
            $interest = $amount * $rate / 100 / 12 * $instl;
        } elseif ($rate > 0 && $head['interest_type'] === 'compound') {
            $interest = $amount * (pow(1 + $rate / 1200, $instl) - 1);
        }
        $totalRep  = $amount + $interest;
        $emi       = round($totalRep / max(1, $instl), 2);

        $id = $db->insertRow('advance_applications', [
            'employee_id'         => $empId,
            'advance_head_id'     => $headId,
            'application_date'    => date('Y-m-d'),
            'amount_requested'    => $amount,
            'installments'        => $instl,
            'interest_rate'       => $rate,
            'total_repayable'     => $totalRep,
            'monthly_installment' => $emi,
            'purpose'             => $purpose,
            'status'              => 'pending',
        ]);
        auditLog('INSERT','advance_applications',$id);
        setFlash('success', "Advance application submitted. Monthly EMI: " . money($emi));
    }

    if (($action === 'approve' || $action === 'reject') && hasRole('superadmin','admin','hr','management')) {
        $appId    = postInt('app_id');
        $status   = $action === 'approve' ? 'approved' : 'rejected';
        $startM   = postInt('start_month') ?: date('n');
        $startY   = postInt('start_year')  ?: date('Y');

        // FIX (07 Jul 2026): confirm this application belongs to an
        // employee in the current org before approving/rejecting it.
        $orgCompanies = orgCompanyIds($db);
        $app = $db->fetchOne(
            "SELECT aa.* FROM advance_applications aa JOIN employees e ON e.id=aa.employee_id WHERE aa.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([$appId], $orgCompanies)
        );
        if (!$app) { setFlash('error', 'Application not found.'); header('Location: index.php'); exit; }
        if ($app && $status === 'approved') {
            $db->execute(
                "UPDATE advance_applications SET status='active',amount_approved=amount_requested,approved_by=?,approved_date=?,start_month=?,start_year=? WHERE id=?",
                [$user['id'], date('Y-m-d'), $startM, $startY, $appId]
            );
            // Create repayment schedule
            $balance = $app['total_repayable'];
            $principal = $app['amount_requested'];
            $m = $startM; $y = $startY;
            for ($i = 1; $i <= $app['installments']; $i++) {
                $principalEMI = round($principal / $app['installments'], 2);
                $intEMI       = round(($app['total_repayable'] - $principal) / $app['installments'], 2);
                $total        = $principalEMI + $intEMI;
                $balance      -= $total;
                $db->insertRow('advance_repayments', [
                    'advance_id'      => $appId,
                    'month'           => $m,
                    'year'            => $y,
                    'installment_no'  => $i,
                    'principal_amount'=> $principalEMI,
                    'interest_amount' => $intEMI,
                    'total_amount'    => $total,
                    'balance_after'   => max(0, $balance),
                    'status'          => 'pending',
                ]);
                $m++; if ($m > 12) { $m = 1; $y++; }
            }
        } else {
            $db->execute("UPDATE advance_applications SET status=?,approved_by=?,approved_date=? WHERE id=?",
                [$status, $user['id'], date('Y-m-d'), $appId]);
        }
        setFlash('success', "Advance application $status.");
    }

    header('Location: index.php'); exit;
}

// Fetch data
$advanceHeads = $db->fetchAll("SELECT * FROM advance_heads WHERE is_active=1 ORDER BY name");
[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');
$employees    = hasRole('employee') ? [] : $db->fetchAll("SELECT id,employee_id,first_name,last_name FROM employees WHERE status='active' AND $empOrgClause ORDER BY first_name", $empOrgParams);

// FIX (07 Jul 2026): scope to current org — this used to list every
// organization's advance applications (with amounts, EMIs) to any
// HR/admin/management user.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$where  = [$orgClause];
$params = $orgParams;
if (hasRole('employee')) { $where[] = 'aa.employee_id=?'; $params[] = $user['emp_id']; }
$applications = $db->fetchAll(
    "SELECT aa.*, ah.name AS head_name, e.first_name, e.last_name, e.employee_id AS emp_code
       FROM advance_applications aa
       JOIN advance_heads ah ON ah.id=aa.advance_head_id
       JOIN employees e ON e.id=aa.employee_id
      WHERE " . implode(' AND ',$where) . "
      ORDER BY aa.created_at DESC LIMIT 50",
    $params
);

$headerActions = '<button class="btn btn-pc btn-sm" data-bs-toggle="modal" data-bs-target="#applyModal">
  <i class="ti ti-plus me-1"></i>Apply Advance</button>';
include __DIR__ . '/../../includes/header.php';
?>
<!-- Apply Modal -->
<div class="modal fade" id="applyModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h6 class="modal-title">Advance Application</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form method="POST">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="apply">
        <div class="modal-body row g-3">
          <?php if (!hasRole('employee')): ?>
          <div class="col-12"><label class="pc-label">Employee *</label>
            <select name="employee_id" class="form-select form-select-sm" required>
              <option value="">Select</option>
              <?php foreach ($employees as $e): ?>
              <option value="<?= $e['id'] ?>"><?= clean($e['first_name'].' '.$e['last_name'].' ('.$e['employee_id'].')') ?></option>
              <?php endforeach; ?>
            </select></div>
          <?php endif; ?>
          <div class="col-6"><label class="pc-label">Advance Type *</label>
            <select name="advance_head_id" class="form-select form-select-sm" id="headSel" required onchange="updateHead()">
              <option value="">Select</option>
              <?php foreach ($advanceHeads as $h): ?>
              <option value="<?= $h['id'] ?>" data-max="<?= $h['max_amount'] ?>" data-rate="<?= $h['interest_rate'] ?>" data-maxinstl="<?= $h['max_installments'] ?>">
                <?= clean($h['name']) ?></option>
              <?php endforeach; ?>
            </select></div>
          <div class="col-6"><label class="pc-label">Amount (₹) *</label>
            <input type="number" name="amount_requested" id="amtInput" class="form-control form-control-sm" step="100" required oninput="calcPreview()"></div>
          <div class="col-6"><label class="pc-label">Installments *</label>
            <input type="number" name="installments" id="instlInput" class="form-control form-control-sm" min="1" max="60" value="12" required oninput="calcPreview()"></div>
          <div class="col-6"><label class="pc-label">Interest Rate %</label>
            <input type="text" id="rateDisplay" class="form-control form-control-sm" readonly></div>
          <div class="col-12"><label class="pc-label">Purpose *</label>
            <textarea name="purpose" class="form-control form-control-sm" rows="2" required></textarea></div>
          <!-- Preview -->
          <div class="col-12" id="previewBox" style="display:none">
            <div class="alert alert-info py-2 mb-0">
              <div class="d-flex justify-content-between small">
                <span>Total Repayable:</span><strong id="prvTotal">₹0</strong></div>
              <div class="d-flex justify-content-between small mt-1">
                <span>Monthly EMI:</span><strong id="prvEmi">₹0</strong></div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-pc btn-sm">Submit Application</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Applications Table -->
<div class="pc-card">
  <div class="pc-card-title">Advance Applications</div>
  <div class="pc-table-wrap">
    <table class="pc-table">
      <thead><tr><th>Employee</th><th>Type</th><th>Amount</th><th>Installments</th><th>EMI</th><th>Total Rep.</th><th>Purpose</th><th>Status</th><th>Actions</th></tr></thead>
      <tbody>
      <?php foreach ($applications as $a): ?>
      <tr>
        <td><div class="fw-semibold"><?= clean($a['first_name'].' '.$a['last_name']) ?></div>
          <div style="font-size:10px;color:var(--pc-text2)"><?= clean($a['emp_code']) ?></div></td>
        <td><?= clean($a['head_name']) ?></td>
        <td><?= money($a['amount_requested']) ?></td>
        <td><?= $a['installments'] ?>m</td>
        <td><?= money($a['monthly_installment']) ?></td>
        <td><?= money($a['total_repayable']) ?></td>
        <td style="max-width:120px;overflow:hidden;text-overflow:ellipsis"><?= clean($a['purpose']) ?></td>
        <td><?= statusBadge($a['status']) ?></td>
        <td>
          <?php if ($a['status']==='pending' && hasRole('superadmin','admin','hr','management')): ?>
          <button class="btn btn-sm btn-success" onclick="approveAdv(<?= $a['id'] ?>,'approve')" title="Approve"><i class="ti ti-check"></i></button>
          <button class="btn btn-sm btn-danger"  onclick="approveAdv(<?= $a['id'] ?>,'reject')"  title="Reject"><i class="ti ti-x"></i></button>
          <?php endif; ?>
          <?php if ($a['status']==='active'): ?>
          <a href="schedule.php?id=<?= $a['id'] ?>" class="btn btn-sm btn-outline-info" title="Schedule"><i class="ti ti-list"></i></a>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if (!$applications): ?>
      <tr><td colspan="9" class="text-center py-4 text-muted">No advance applications found</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Approve Modal -->
<div class="modal fade" id="advApproveModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header"><h6 class="modal-title" id="advModalTitle">Approve Advance</h6></div>
      <form method="POST">
        <?= csrfField() ?>
        <input type="hidden" name="action" id="advAction">
        <input type="hidden" name="app_id" id="advAppId">
        <div class="modal-body row g-2">
          <div class="col-6"><label class="pc-label">Start Month</label>
            <select name="start_month" class="form-select form-select-sm">
              <?php for ($m=1;$m<=12;$m++): ?>
              <option value="<?= $m ?>" <?= $m==date('n')?'selected':'' ?>><?= monthName($m) ?></option>
              <?php endfor; ?>
            </select></div>
          <div class="col-6"><label class="pc-label">Start Year</label>
            <input type="number" name="start_year" class="form-control form-control-sm" value="<?= date('Y') ?>"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-pc btn-sm" id="advSubmitBtn">Approve</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php $extraJs = "<script>
function updateHead() {
  const sel = document.getElementById('headSel');
  const opt = sel.options[sel.selectedIndex];
  document.getElementById('rateDisplay').value = opt.dataset.rate ? opt.dataset.rate+'%' : '0%';
  const maxInstl = opt.dataset.maxinstl || 60;
  document.getElementById('instlInput').max = maxInstl;
  calcPreview();
}
function calcPreview() {
  const sel  = document.getElementById('headSel').options[document.getElementById('headSel').selectedIndex];
  const amt  = parseFloat(document.getElementById('amtInput').value) || 0;
  const instl= parseInt(document.getElementById('instlInput').value) || 1;
  const rate = parseFloat(sel?.dataset?.rate) || 0;
  if (amt > 0 && instl > 0) {
    const interest = rate > 0 ? amt * rate / 100 / 12 * instl : 0;
    const total    = amt + interest;
    const emi      = total / instl;
    document.getElementById('prvTotal').textContent = '₹' + total.toFixed(2);
    document.getElementById('prvEmi').textContent   = '₹' + emi.toFixed(2);
    document.getElementById('previewBox').style.display = '';
  }
}
function approveAdv(id, action) {
  document.getElementById('advAction').value  = action;
  document.getElementById('advAppId').value   = id;
  document.getElementById('advModalTitle').textContent = action==='approve' ? 'Approve Advance' : 'Reject Advance';
  document.getElementById('advSubmitBtn').textContent  = action==='approve' ? 'Approve' : 'Reject';
  document.getElementById('advSubmitBtn').className    = 'btn btn-sm '+(action==='approve'?'btn-success':'btn-danger');
  new bootstrap.Modal(document.getElementById('advApproveModal')).show();
}
</script>"; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>