<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db = Database::getInstance();
$page = 'Expense Booking';
$user = currentUser();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    // FIX (07 Jul 2026): validate every target against the current org.
    $orgCompanies = orgCompanyIds($db);
    if ($action === 'submit') {
        $empId = $user['emp_id'] ?: 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/expense/index.php'); exit;
        }
        $db->execute("INSERT INTO expense_claims (employee_id,expense_type_id,expense_date,amount,description,project_code,status) VALUES (?,?,?,?,?,?,'pending')",
            [$empId, postInt('expense_type_id'), post('expense_date'), post('amount'), post('description'), post('project_code')]);
        $newClaimId = $db->lastInsertId();
        $applicantName = $db->fetchValue("SELECT CONCAT(first_name,' ',last_name) FROM employees WHERE id=?", [$empId]);
        notifyReportingHead($db, $empId, 'Expense Claim', "$applicantName submitted an expense claim of " . post('amount') . ".", 'expense', $newClaimId);
        notifyAllSuperadmins($db, $empId, 'Expense Claim', "$applicantName submitted an expense claim of " . post('amount') . ".", 'expense', $newClaimId);
        setFlash('success', 'Expense claim submitted.');
    } elseif (in_array($action, ['approve','reject','pay'])) {
        $claim = $db->fetchOne(
            "SELECT ec.id,ec.employee_id FROM expense_claims ec JOIN employees e ON e.id=ec.employee_id WHERE ec.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt('id')], $orgCompanies)
        );
        if (!$claim) {
            setFlash('error', 'Claim not found.');
        } elseif ($action === 'approve') {
            $db->execute("UPDATE expense_claims SET status='approved',approved_by=?,approved_date=NOW() WHERE id=?", [currentUser()['id'], postInt('id')]);
            notify($db, (int)$claim['employee_id'], 'Expense Approved', 'Your expense claim was approved.', 'expense', postInt('id'));
            notifyAllSuperadmins($db, (int)$claim['employee_id'], 'Expense Approved', "Expense claim for employee #" . $claim['employee_id'] . " was approved.", 'expense', postInt('id'));
            setFlash('success', 'Approved.');
        } elseif ($action === 'reject') {
            $db->execute("UPDATE expense_claims SET status='rejected',approved_by=?,approved_date=NOW() WHERE id=?", [currentUser()['id'], postInt('id')]);
            notify($db, (int)$claim['employee_id'], 'Expense Rejected', 'Your expense claim was rejected.', 'expense', postInt('id'));
            notifyAllSuperadmins($db, (int)$claim['employee_id'], 'Expense Rejected', "Expense claim for employee #" . $claim['employee_id'] . " was rejected.", 'expense', postInt('id'));
            setFlash('success', 'Rejected.');
        } else {
            $db->execute("UPDATE expense_claims SET status='paid',payment_date=NOW() WHERE id=?", [postInt('id')]);
            notify($db, (int)$claim['employee_id'], 'Expense Paid', 'Your expense claim has been marked as paid.', 'expense', postInt('id'));
            notifyAllSuperadmins($db, (int)$claim['employee_id'], 'Expense Paid', "Expense claim for employee #" . $claim['employee_id'] . " was marked as paid.", 'expense', postInt('id'));
            setFlash('success', 'Marked as paid.');
        }
    }
    header('Location: ' . BASE_URL . '/modules/expense/index.php'); exit;
}

// FIX: parameterized (was raw string concatenation — a SQL injection
// path since $filter came straight from the URL) and scoped to org.
$filterOptions = ['all','pending','approved','paid','rejected'];
$filter = in_array($_GET['filter'] ?? '', $filterOptions) ? $_GET['filter'] : 'all';
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$where  = $orgClause;
$params = $orgParams;
if ($filter !== 'all') { $where .= ' AND ec.status=?'; $params[] = $filter; }
$claims = $db->fetchAll("SELECT ec.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code,et.name AS category
    FROM expense_claims ec
    JOIN employees e ON e.id=ec.employee_id
    LEFT JOIN expense_types et ON et.id=ec.expense_type_id
    WHERE $where
    ORDER BY ec.expense_date DESC", $params);
[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');
$employees    = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $empOrgClause ORDER BY first_name", $empOrgParams);
$expenseTypes = $db->fetchAll("SELECT id,name,max_amount,requires_bill FROM expense_types WHERE is_active=1 ORDER BY name");

$stats = ['total' => 0, 'pending' => 0, 'approved' => 0, 'paid' => 0];
foreach ($claims as $c) { $stats['total'] += $c['amount']; if (isset($stats[$c['status']])) $stats[$c['status']] += $c['amount']; }

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3 mb-3">
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon brand" style="width:42px;height:42px;font-size:20px"><i class="ti ti-receipt"></i></div><div class="pc-stat-val" style="font-size:18px">₹<?=number_format($stats['total'],0)?></div><div class="pc-stat-label">Total Claims</div></div></div>
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon amber" style="width:42px;height:42px;font-size:20px"><i class="ti ti-clock"></i></div><div class="pc-stat-val" style="font-size:18px">₹<?=number_format($stats['pending'],0)?></div><div class="pc-stat-label">Pending</div></div></div>
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon green" style="width:42px;height:42px;font-size:20px"><i class="ti ti-check"></i></div><div class="pc-stat-val" style="font-size:18px">₹<?=number_format($stats['approved'],0)?></div><div class="pc-stat-label">Approved</div></div></div>
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon blue" style="width:42px;height:42px;font-size:20px"><i class="ti ti-cash"></i></div><div class="pc-stat-val" style="font-size:18px">₹<?=number_format($stats['paid'],0)?></div><div class="pc-stat-label">Paid</div></div></div>
</div>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-plus me-2"></i>Submit Expense Claim</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="submit">
        <?php if (!$user['emp_id']): ?>
        <div class="mb-2"><label class="pc-label">Employee</label>
          <select name="employee_id" class="form-select form-select-sm">
            <option value="">Select</option>
            <?php foreach ($employees as $e): ?><option value="<?=$e['id']?>"><?=clean($e['label'])?></option><?php endforeach; ?>
          </select></div>
        <?php endif; ?>
        <div class="mb-2"><label class="pc-label">Expense Date</label><input type="date" name="expense_date" class="form-control form-control-sm" value="<?=date('Y-m-d')?>" required></div>
        <div class="mb-2"><label class="pc-label">Category</label>
          <select name="expense_type_id" class="form-select form-select-sm" required>
            <option value="">Select</option>
            <?php foreach ($expenseTypes as $t): ?>
            <option value="<?=$t['id']?>"><?=clean($t['name'])?><?=$t['max_amount']>0?' (max ₹'.number_format($t['max_amount']).')':''?></option>
            <?php endforeach; ?>
          </select></div>
        <div class="mb-2"><label class="pc-label">Amount (₹)</label><input type="number" name="amount" class="form-control form-control-sm" step="0.01" required></div>
        <div class="mb-2"><label class="pc-label">Project Code (optional)</label><input type="text" name="project_code" class="form-control form-control-sm"></div>
        <div class="mb-3"><label class="pc-label">Description / Purpose</label><textarea name="description" class="form-control form-control-sm" rows="2" required></textarea></div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-send me-1"></i>Submit Claim</button>
      </form>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title d-flex align-items-center">
        <i class="ti ti-list me-2"></i>Expense Claims
        <div class="ms-auto d-flex gap-1">
          <?php foreach (['all','pending','approved','paid','rejected'] as $f): ?>
          <a href="?filter=<?=$f?>" class="btn btn-xs <?=$filter===$f?'btn-pc':'btn-outline-secondary'?> py-0 px-2" style="font-size:10px"><?=ucfirst($f)?></a>
          <?php endforeach; ?>
        </div>
      </div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>Date</th><th>Category</th><th>Amount</th><th>Description</th><th>Status</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach ($claims as $c): ?>
          <tr>
            <td><div class="fw-semibold"><?=clean($c['emp_name'])?></div><small class="text-muted"><?=clean($c['emp_code'])?></small></td>
            <td><?=fmtDate($c['expense_date'])?></td>
            <td><span class="badge" style="background:var(--pc-brand-light);color:var(--pc-brand)"><?=clean($c['category'] ?? '—')?></span></td>
            <td class="fw-bold">₹<?=number_format($c['amount'],2)?></td>
            <td><?=clean(substr($c['description'],0,40))?><?=strlen($c['description'])>40?'...':''?></td>
            <td><?=statusBadge($c['status'])?></td>
            <td>
              <?php if ($c['status']==='pending'): ?>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?=$c['id']?>"><button class="btn btn-xs btn-success py-0 px-1">Approve</button></form>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="reject"><input type="hidden" name="id" value="<?=$c['id']?>"><button class="btn btn-xs btn-danger py-0 px-1">Reject</button></form>
              <?php elseif ($c['status']==='approved'): ?>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="pay"><input type="hidden" name="id" value="<?=$c['id']?>"><button class="btn btn-xs btn-primary py-0 px-1">Mark Paid</button></form>
              <?php else: ?>—<?php endif; ?>
            </td>
          </tr>
          <?php endforeach; if (!$claims): ?><tr><td colspan="7" class="text-center text-muted py-3">No claims found</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>