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

// Handle form submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    // FIX (07 Jul 2026): validate the target employee_id/transfer id belongs
    // to the current organization before touching it — otherwise anyone
    // logged in could submit/approve a transfer for another org's employee.
    $orgCompanies = orgCompanyIds($db);
    if ($action === 'add') {
        $targetEmp = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [postInt('employee_id')]);
        if (!$targetEmp || !in_array($targetEmp['company_id'], $orgCompanies)) {
            setFlash('error', 'Invalid employee selected.');
            header('Location: '.BASE_URL.'/modules/employees/transfer.php'); exit;
        }
        $db->execute("INSERT INTO employee_transfers (employee_id,transfer_date,from_department_id,to_department_id,from_designation_id,to_designation_id,from_location_id,to_location_id,reason,status) VALUES (?,?,?,?,?,?,?,?,?,'pending')",
            [postInt('employee_id'), post('transfer_date'), postInt('from_dept'), postInt('to_dept'), postInt('from_desig'), postInt('to_desig'), postInt('from_loc'), postInt('to_loc'), post('reason')]);
        setFlash('success','Transfer request created successfully.');
    } elseif ($action === 'approve') {
        $t = $db->fetchOne(
            "SELECT t.*, e.company_id FROM employee_transfers t JOIN employees e ON e.id=t.employee_id WHERE t.id=?",
            [postInt('id')]
        );
        if (!$t || !in_array($t['company_id'], $orgCompanies)) {
            setFlash('error', 'Transfer not found.');
            header('Location: '.BASE_URL.'/modules/employees/transfer.php'); exit;
        }
        $db->execute("UPDATE employee_transfers SET status='approved',approved_by=? WHERE id=?", [currentUser()['id'], postInt('id')]);
        // Update employee record
        $db->execute("UPDATE employees SET department_id=?,designation_id=?,location_id=? WHERE id=?",
            [$t['to_department_id'],$t['to_designation_id'],$t['to_location_id'],$t['employee_id']]);
        $db->execute("UPDATE employee_transfers SET status='completed' WHERE id=?", [postInt('id')]);
        setFlash('success','Transfer approved and employee record updated.');
    } elseif ($action === 'reject') {
        $t = $db->fetchOne(
            "SELECT t.id FROM employee_transfers t JOIN employees e ON e.id=t.employee_id WHERE t.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt('id')], $orgCompanies)
        );
        if ($t) {
            $db->execute("UPDATE employee_transfers SET status='rejected' WHERE id=?", [postInt('id')]);
            setFlash('success','Transfer rejected.');
        } else {
            setFlash('error', 'Transfer not found.');
        }
    }
    header('Location: '.BASE_URL.'/modules/employees/transfer.php'); exit;
}

[$transferOrgClause, $transferOrgParams] = orgScopeClause($db, 'e.company_id');
$transfers = $db->fetchAll("SELECT t.*,
    CONCAT(e.first_name,' ',e.last_name) AS emp_name, e.employee_id AS emp_code,
    fd.name AS from_dept, td.name AS to_dept,
    fl.name AS from_loc, tl.name AS to_loc,
    fd2.name AS from_desig, td2.name AS to_desig
  FROM employee_transfers t
  JOIN employees e ON e.id=t.employee_id
  LEFT JOIN departments fd ON fd.id=t.from_department_id
  LEFT JOIN departments td ON td.id=t.to_department_id
  LEFT JOIN locations fl ON fl.id=t.from_location_id
  LEFT JOIN locations tl ON tl.id=t.to_location_id
  LEFT JOIN designations fd2 ON fd2.id=t.from_designation_id
  LEFT JOIN designations td2 ON td2.id=t.to_designation_id
  WHERE $transferOrgClause
  ORDER BY t.created_at DESC", $transferOrgParams);

[$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);
$departments  = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");
$designations = $db->fetchAll("SELECT id,name FROM designations WHERE is_active=1 ORDER BY name");
$locations    = $db->fetchAll("SELECT id,name FROM locations WHERE is_active=1 ORDER BY name");

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3 mb-3">
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-arrows-exchange me-2"></i>New Transfer Request</div>
      <form method="POST">
        <?= csrfField() ?><input type="hidden" name="action" value="add">
        <div class="mb-2"><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['label']) ?></option><?php endforeach; ?>
          </select></div>
        <div class="mb-2"><label class="pc-label">Transfer Date</label><input type="date" name="transfer_date" class="form-control form-control-sm" required value="<?=date('Y-m-d')?>"></div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">From Dept</label>
            <select name="from_dept" class="form-select form-select-sm"><option value="">Select</option><?php foreach($departments as $d): ?><option value="<?=$d['id']?>"><?=clean($d['name'])?></option><?php endforeach; ?></select></div>
          <div class="col"><label class="pc-label">To Dept</label>
            <select name="to_dept" class="form-select form-select-sm"><option value="">Select</option><?php foreach($departments as $d): ?><option value="<?=$d['id']?>"><?=clean($d['name'])?></option><?php endforeach; ?></select></div>
        </div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">From Designation</label>
            <select name="from_desig" class="form-select form-select-sm"><option value="">Select</option><?php foreach($designations as $d): ?><option value="<?=$d['id']?>"><?=clean($d['name'])?></option><?php endforeach; ?></select></div>
          <div class="col"><label class="pc-label">To Designation</label>
            <select name="to_desig" class="form-select form-select-sm"><option value="">Select</option><?php foreach($designations as $d): ?><option value="<?=$d['id']?>"><?=clean($d['name'])?></option><?php endforeach; ?></select></div>
        </div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">From Location</label>
            <select name="from_loc" class="form-select form-select-sm"><option value="">Select</option><?php foreach($locations as $l): ?><option value="<?=$l['id']?>"><?=clean($l['name'])?></option><?php endforeach; ?></select></div>
          <div class="col"><label class="pc-label">To Location</label>
            <select name="to_loc" class="form-select form-select-sm"><option value="">Select</option><?php foreach($locations as $l): ?><option value="<?=$l['id']?>"><?=clean($l['name'])?></option><?php endforeach; ?></select></div>
        </div>
        <div class="mb-3"><label class="pc-label">Reason</label><textarea name="reason" class="form-control form-control-sm" rows="2"></textarea></div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-send me-1"></i>Submit Transfer</button>
      </form>
    </div>
  </div>
  <div class="col-md-7">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-list me-2"></i>Transfer History</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>From → To Dept</th><th>From → To Location</th><th>Date</th><th>Status</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach($transfers as $t): ?>
          <tr>
            <td><div class="fw-semibold"><?=clean($t['emp_name'])?></div><small class="text-muted"><?=clean($t['emp_code'])?></small></td>
            <td><span class="text-muted"><?=clean($t['from_dept']??'—')?></span> → <strong><?=clean($t['to_dept']??'—')?></strong></td>
            <td><span class="text-muted"><?=clean($t['from_loc']??'—')?></span> → <strong><?=clean($t['to_loc']??'—')?></strong></td>
            <td><?=fmtDate($t['transfer_date'])?></td>
            <td><?=statusBadge($t['status'])?></td>
            <td>
              <?php if($t['status']==='pending'): ?>
              <form method="POST" class="d-inline"><input type="hidden" name="action" value="approve"><?=csrfField()?><input type="hidden" name="id" value="<?=$t['id']?>"><button class="btn btn-sm btn-success py-0">Approve</button></form>
              <form method="POST" class="d-inline"><input type="hidden" name="action" value="reject"><?=csrfField()?><input type="hidden" name="id" value="<?=$t['id']?>"><button class="btn btn-sm btn-danger py-0">Reject</button></form>
              <?php else: ?>—<?php endif; ?>
            </td>
          </tr>
          <?php endforeach; if(!$transfers): ?><tr><td colspan="6" class="text-center text-muted py-3">No transfers found</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>