<?php
// ============================================================
// modules/separation/index.php – Full & Final Settlement
// ============================================================
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db   = Database::getInstance();
$page = 'F&F Settlement';

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

    if ($action === 'initiate') {
        $empId      = postInt('employee_id');
        // 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: index.php'); exit;
        }
        $lwd        = post('last_working_date');
        $resignDate = post('resignation_date');
        $reasonId   = postInt('leaving_reason_id');
        $noticeDays = postInt('notice_period_days');
        $servedDays = postInt('notice_served_days');

        // Calc salary payable (remaining month days)
        $sal    = $db->fetchOne("SELECT gross_monthly FROM employee_salary WHERE employee_id=?", [$empId]);
        $gross  = $sal['gross_monthly'] ?? 0;
        $perDay = $gross / 26;
        $lwdDay = (int)date('j', strtotime($lwd));
        $salPayable = round($perDay * $lwdDay, 2);

        // Notice pay recovery
        $shortfall  = max(0, $noticeDays - $servedDays);
        $noticeRec  = round($perDay * $shortfall, 2);

        // Leave encashment — FIX (07 Aug 2026): use each COMPANY's own
        // leave policy (Companies → Leave Policy: which leave types are
        // encashable, and at what % of the per-day rate — e.g. 80% or
        // 90%, matches "current salary * company's encashment rate")
        // instead of the old global leave_types.encashable flag at a
        // flat 100%. Falls back to the old behaviour if
        // migration_company_leave_policy.sql hasn't been run yet, so
        // this keeps working either way.
        $empCompanyId = $target['company_id'];
        $leaveEncash = 0.0; $encashDays = 0.0;
        try {
            $encashRows = $db->fetchAll(
                "SELECT (lb.allocated+lb.carry_forward-lb.used) AS bal, clp.encashment_rate_percent
                   FROM employee_leave_balance lb
                   JOIN company_leave_policy clp ON clp.leave_type_id=lb.leave_type_id AND clp.company_id=? AND clp.is_active=1 AND clp.encashable=1
                  WHERE lb.employee_id=? AND lb.year=?",
                [$empCompanyId, $empId, date('Y')]
            );
            foreach ($encashRows as $r) {
                $days = max(0, (float)$r['bal']);
                $encashDays += $days;
                $leaveEncash += round($perDay * $days * ((float)$r['encashment_rate_percent'] / 100), 2);
            }
        } catch (Throwable $e) {
            // migration_company_leave_policy.sql not run yet — fall back
            // to the old global flag at a flat 100% (previous behaviour).
            $leaveBal = $db->fetchOne(
                "SELECT SUM(lb.allocated+lb.carry_forward-lb.used) AS bal
                   FROM employee_leave_balance lb
                   JOIN leave_types lt ON lt.id=lb.leave_type_id
                  WHERE lb.employee_id=? AND lt.encashable=1 AND lb.year=?",
                [$empId, date('Y')]
            );
            $encashDays  = $leaveBal['bal'] ?? 0;
            $leaveEncash = round($perDay * $encashDays, 2);
        }

        // Gratuity
        $emp     = $db->fetchOne("SELECT date_of_joining FROM employees WHERE id=?", [$empId]);
        $service = yearsOfService($emp['date_of_joining']);
        $gratuity = 0;
        if ($service >= 5) {
            $basic   = $gross * 0.40;
            $gratuity = round(($basic / 26) * 15 * floor($service), 2);
            $gsSetup = $db->fetchOne("SELECT max_gratuity_amount FROM gratuity_setup LIMIT 1");
            $gratuity = min($gratuity, $gsSetup['max_gratuity_amount'] ?? 2000000);
        }

        // Bonus payable
        $bonus = 0;
        $bSetup = $db->fetchOne("SELECT percentage FROM bonus_setup WHERE is_active=1 LIMIT 1");
        if ($bSetup) {
            $basic = $gross * 0.40;
            $bonus = round($basic * $bSetup['percentage'] / 100, 2);
        }

        // Pending advances
        $pendAdv = $db->fetchValue(
            "SELECT COALESCE(SUM(ar.total_amount),0) FROM advance_repayments ar
              JOIN advance_applications aa ON aa.id=ar.advance_id
             WHERE aa.employee_id=? AND ar.status='pending'",
            [$empId]
        ) ?? 0;

        $totalPayable = $salPayable + $leaveEncash + $gratuity + $bonus - $noticeRec - $pendAdv;

        $existing = $db->fetchValue("SELECT id FROM separations WHERE employee_id=?", [$empId]);
        if ($existing) {
            $db->updateRow('separations', [
                'resignation_date'      => $resignDate,
                'last_working_date'     => $lwd,
                'leaving_reason_id'     => $reasonId,
                'notice_period_days'    => $noticeDays,
                'notice_served_days'    => $servedDays,
                'notice_pay_recovery'   => $noticeRec,
                'salary_payable'        => $salPayable,
                'leave_encashment'      => $leaveEncash,
                'gratuity_amount'       => $gratuity,
                'bonus_payable'         => $bonus,
                'total_payable'         => $totalPayable,
                'status'                => 'processing',
            ], $existing);
            $sepId = $existing;
        } else {
            $sepId = $db->insertRow('separations', [
                'employee_id'           => $empId,
                'resignation_date'      => $resignDate,
                'last_working_date'     => $lwd,
                'leaving_reason_id'     => $reasonId,
                'notice_period_days'    => $noticeDays,
                'notice_served_days'    => $servedDays,
                'notice_pay_recovery'   => $noticeRec,
                'salary_payable'        => $salPayable,
                'leave_encashment'      => $leaveEncash,
                'gratuity_amount'       => $gratuity,
                'bonus_payable'         => $bonus,
                'total_payable'         => $totalPayable,
                'status'                => 'initiated',
            ]);
            // Create clearance items
            $items = ['ID Card Returned','IT Assets Returned','Exit Interview Done',
                      'Documents Collected','PF Transfer Initiated','ESI Closure','Advance Settled'];
            foreach ($items as $item) {
                $db->insertRow('separation_clearance', ['separation_id'=>$sepId,'item'=>$item]);
            }
        }

        // Update employee status
        $db->execute("UPDATE employees SET status='resigned' WHERE id=?", [$empId]);
        setFlash('success','F&F Settlement initiated. Total payable: '.money($totalPayable));
        header('Location: index.php?view='.$sepId); exit;
    }

    if ($action === 'update_clearance') {
        $sepId  = postInt('sep_id');
        $itemId = postInt('item_id');
        $cleared= postInt('cleared');
        // FIX (07 Jul 2026): confirm this separation case belongs to an
        // employee in the current org.
        $orgCompanies = orgCompanyIds($db);
        $owned = $db->fetchOne(
            "SELECT s.id FROM separations s JOIN employees e ON e.id=s.employee_id WHERE s.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([$sepId], $orgCompanies)
        );
        if (!$owned) { jsonResponse(false, 'Case not found.'); }
        $db->execute("UPDATE separation_clearance SET is_cleared=?,cleared_by=?,cleared_date=? WHERE id=? AND separation_id=?",
            [$cleared, currentUser()['id'], date('Y-m-d'), $itemId, $sepId]);
        jsonResponse(true, 'Clearance updated');
    }

    if ($action === 'complete') {
        $sepId = postInt('sep_id');
        // FIX: same ownership check as above.
        $orgCompanies = orgCompanyIds($db);
        $owned = $db->fetchOne(
            "SELECT s.id FROM separations s JOIN employees e ON e.id=s.employee_id WHERE s.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([$sepId], $orgCompanies)
        );
        if (!$owned) { setFlash('error','Case not found.'); header('Location: index.php'); exit; }
        $db->execute("UPDATE separations SET status='completed',cleared_date=? WHERE id=?", [date('Y-m-d'),$sepId]);
        setFlash('success','F&F Settlement completed.');
        header('Location: index.php'); exit;
    }

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

// View single F&F
$viewId = cleanInt($_GET['view'] ?? 0);
$sepDetail = null;
$clearance = [];
// FIX (07 Jul 2026): scope everything below to the current org — this
// exposed salary/gratuity F&F figures for any organization's employee
// via ?view=<id>, and listed every organization's F&F cases.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
if ($viewId) {
    $sepDetail = $db->fetchOne(
        "SELECT s.*, e.first_name, e.last_name, e.employee_id AS emp_code,
                e.date_of_joining, lr.reason AS leaving_reason,
                d.name AS dept, des.name AS designation
           FROM separations s
           JOIN employees e ON e.id=s.employee_id
      LEFT JOIN leaving_reasons lr ON lr.id=s.leaving_reason_id
      LEFT JOIN departments d ON d.id=e.department_id
      LEFT JOIN designations des ON des.id=e.designation_id
          WHERE s.id=? AND $orgClause", array_merge([$viewId], $orgParams)
    );
    if (!$sepDetail) { $viewId = 0; }
    else $clearance = $db->fetchAll("SELECT * FROM separation_clearance WHERE separation_id=?", [$viewId]);
}

// All separations
$separations = $db->fetchAll(
    "SELECT s.*, e.first_name, e.last_name, e.employee_id AS emp_code, lr.reason AS leaving_reason
       FROM separations s
       JOIN employees e ON e.id=s.employee_id
  LEFT JOIN leaving_reasons lr ON lr.id=s.leaving_reason_id
      WHERE $orgClause
      ORDER BY s.created_at DESC LIMIT 50", $orgParams
);

[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');
$employees     = $db->fetchAll("SELECT id,employee_id,first_name,last_name FROM employees WHERE status IN('active','probation') AND $empOrgClause ORDER BY first_name", $empOrgParams);
$leavingReasons= $db->fetchAll("SELECT * FROM leaving_reasons WHERE is_active=1 ORDER BY reason");

$headerActions = '<button class="btn btn-pc btn-sm" data-bs-toggle="modal" data-bs-target="#initModal">
  <i class="ti ti-plus me-1"></i>Initiate F&F</button>';
include __DIR__ . '/../../includes/header.php';
?>

<?php if ($sepDetail): ?>
<!-- F&F Detail View -->
<div class="d-flex justify-content-between align-items-center mb-3">
  <h6 class="fw-bold mb-0"><?= clean($sepDetail['first_name'].' '.$sepDetail['last_name']) ?> – F&F Settlement</h6>
  <a href="index.php" class="btn btn-sm btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>Back to List</a>
</div>

<div class="row g-3">
  <!-- Settlement Summary -->
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title">Settlement Summary</div>
      <table class="table table-sm" style="font-size:12px">
        <tr><th>Employee</th><td><?= clean($sepDetail['first_name'].' '.$sepDetail['last_name']) ?></td></tr>
        <tr><th>Emp Code</th><td><?= clean($sepDetail['emp_code']) ?></td></tr>
        <tr><th>Department</th><td><?= clean($sepDetail['dept']??'—') ?></td></tr>
        <tr><th>Designation</th><td><?= clean($sepDetail['designation']??'—') ?></td></tr>
        <tr><th>Date of Joining</th><td><?= fmtDate($sepDetail['date_of_joining']) ?></td></tr>
        <tr><th>Resignation Date</th><td><?= fmtDate($sepDetail['resignation_date']) ?></td></tr>
        <tr><th>Last Working Day</th><td><?= fmtDate($sepDetail['last_working_date']) ?></td></tr>
        <tr><th>Leaving Reason</th><td><?= clean($sepDetail['leaving_reason']??'—') ?></td></tr>
        <tr><th>Notice Period</th><td><?= $sepDetail['notice_period_days'] ?> days</td></tr>
        <tr><th>Notice Served</th><td><?= $sepDetail['notice_served_days'] ?> days</td></tr>
        <tr><th>Status</th><td><?= statusBadge($sepDetail['status']) ?></td></tr>
      </table>

      <div class="pc-section-divider">Financial Calculation</div>
      <table class="table table-sm mb-0" style="font-size:12px">
        <tr><td>Salary Payable</td><td class="text-end text-success fw-semibold"><?= money($sepDetail['salary_payable']) ?></td></tr>
        <tr><td>Leave Encashment</td><td class="text-end text-success fw-semibold"><?= money($sepDetail['leave_encashment']) ?></td></tr>
        <tr><td>Gratuity</td><td class="text-end text-success fw-semibold"><?= money($sepDetail['gratuity_amount']) ?></td></tr>
        <tr><td>Bonus Payable</td><td class="text-end text-success fw-semibold"><?= money($sepDetail['bonus_payable']) ?></td></tr>
        <tr><td>Notice Pay Recovery</td><td class="text-end text-danger">– <?= money($sepDetail['notice_pay_recovery']) ?></td></tr>
        <tr class="table-primary fw-bold">
          <td>Total Payable</td>
          <td class="text-end"><?= money($sepDetail['total_payable']) ?></td>
        </tr>
      </table>

      <?php if ($sepDetail['status'] !== 'completed'): ?>
      <form method="POST" class="mt-3" onsubmit="return confirm('Mark this F&F as completed?')">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="complete">
        <input type="hidden" name="sep_id" value="<?= $sepDetail['id'] ?>">
        <button type="submit" class="btn btn-success btn-sm w-100">
          <i class="ti ti-check me-1"></i>Mark as Completed
        </button>
      </form>
      <?php endif; ?>
    </div>
  </div>

  <!-- Clearance Checklist -->
  <div class="col-md-7">
    <div class="pc-card">
      <div class="pc-card-title">Clearance Checklist</div>
      <?php
      $clearedCount = array_sum(array_column($clearance,'is_cleared'));
      $totalItems   = count($clearance);
      $pct = $totalItems > 0 ? round($clearedCount/$totalItems*100) : 0;
      ?>
      <div class="mb-3">
        <div class="d-flex justify-content-between small mb-1">
          <span>Clearance Progress</span>
          <span class="fw-bold"><?= $clearedCount ?>/<?= $totalItems ?> items</span>
        </div>
        <div class="pc-progress"><div class="pc-progress-fill" style="width:<?= $pct ?>%;background:<?= $pct===100?'#16a34a':'var(--pc-brand)' ?>"></div></div>
      </div>
      <?php foreach ($clearance as $cl): ?>
      <div class="d-flex align-items-center gap-3 py-2 border-bottom">
        <div class="form-check mb-0">
          <input class="form-check-input" type="checkbox" id="cl<?= $cl['id'] ?>"
            <?= $cl['is_cleared']?'checked':'' ?>
            onchange="updateClearance(<?= $viewId ?>, <?= $cl['id'] ?>, this.checked?1:0)">
        </div>
        <div class="flex-grow-1">
          <div class="fw-semibold small"><?= clean($cl['item']) ?></div>
          <?php if ($cl['cleared_date']): ?>
          <div style="font-size:10px;color:var(--pc-text2)">Cleared on <?= fmtDate($cl['cleared_date']) ?></div>
          <?php endif; ?>
        </div>
        <span class="badge bg-<?= $cl['is_cleared']?'success':'secondary' ?>"><?= $cl['is_cleared']?'Done':'Pending' ?></span>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Letter generation -->
    <div class="pc-card mt-3">
      <div class="pc-card-title">Document Generation</div>
      <div class="d-flex gap-2 flex-wrap">
        <a href="../reports/letter.php?type=experience&emp=<?= $sepDetail['employee_id']??0 ?>" class="btn btn-sm btn-outline-primary">
          <i class="ti ti-file-text me-1"></i>Experience Letter
        </a>
        <a href="../reports/letter.php?type=relieving&emp=<?= $sepDetail['employee_id']??0 ?>" class="btn btn-sm btn-outline-success">
          <i class="ti ti-file-text me-1"></i>Relieving Letter
        </a>
        <a href="../reports/letter.php?type=fnf&sep=<?= $viewId ?>" class="btn btn-sm btn-outline-secondary">
          <i class="ti ti-receipt me-1"></i>F&F Statement
        </a>
      </div>
    </div>
  </div>
</div>

<?php else: ?>
<!-- List View -->
<div class="pc-card">
  <div class="pc-card-title">F&F Settlement Cases</div>
  <div class="pc-table-wrap">
    <table class="pc-table">
      <thead>
        <tr><th>Employee</th><th>Last Working Day</th><th>Leaving Reason</th>
          <th>Total Payable</th><th>Status</th><th>Actions</th></tr>
      </thead>
      <tbody>
      <?php foreach ($separations as $s): ?>
      <tr>
        <td>
          <div class="fw-semibold"><?= clean($s['first_name'].' '.$s['last_name']) ?></div>
          <div style="font-size:10px;color:var(--pc-text2)"><?= clean($s['emp_code']) ?></div>
        </td>
        <td><?= fmtDate($s['last_working_date']) ?></td>
        <td><?= clean($s['leaving_reason']??'—') ?></td>
        <td class="fw-semibold"><?= money($s['total_payable']) ?></td>
        <td><?= statusBadge($s['status']) ?></td>
        <td>
          <a href="?view=<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary">
            <i class="ti ti-eye me-1"></i>View
          </a>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if (!$separations): ?>
      <tr><td colspan="6" class="text-center py-4 text-muted">No F&F cases found</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<!-- Initiate Modal -->
<div class="modal fade" id="initModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header"><h6 class="modal-title">Initiate F&F Settlement</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form method="POST">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="initiate">
        <div class="modal-body row g-3">
          <div class="col-md-6"><label class="pc-label">Employee *</label>
            <select name="employee_id" class="form-select form-select-sm" required>
              <option value="">Select Employee</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>
          <div class="col-md-6"><label class="pc-label">Leaving Reason *</label>
            <select name="leaving_reason_id" class="form-select form-select-sm" required>
              <option value="">Select</option>
              <?php foreach ($leavingReasons as $r): ?>
              <option value="<?= $r['id'] ?>"><?= clean($r['reason']) ?></option>
              <?php endforeach; ?>
            </select></div>
          <div class="col-md-4"><label class="pc-label">Resignation Date</label>
            <input type="date" name="resignation_date" class="form-control form-control-sm"></div>
          <div class="col-md-4"><label class="pc-label">Last Working Date *</label>
            <input type="date" name="last_working_date" class="form-control form-control-sm" required></div>
          <div class="col-md-4"></div>
          <div class="col-md-4"><label class="pc-label">Notice Period (Days)</label>
            <input type="number" name="notice_period_days" class="form-control form-control-sm" value="30" min="0"></div>
          <div class="col-md-4"><label class="pc-label">Notice Served (Days)</label>
            <input type="number" name="notice_served_days" class="form-control form-control-sm" value="30" min="0"></div>
          <div class="col-12">
            <div class="alert alert-info small mb-0">
              <i class="ti ti-info-circle me-1"></i>
              System will auto-calculate: Salary Payable, Leave Encashment, Gratuity, Bonus, Notice Pay Recovery based on employee records.
            </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">Calculate & Initiate</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php $extraJs = "<script>
function updateClearance(sepId, itemId, cleared) {
  pcAjax('index.php', {
    action: 'update_clearance', sep_id: sepId, item_id: itemId, cleared: cleared
  }, function() {
    showToast('Clearance updated', 'success');
  });
}
</script>"; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>