<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');

$id   = cleanInt($_GET['id'] ?? 0);
$csrf = $_GET['csrf'] ?? '';

if (!$id || !hash_equals($_SESSION['csrf_token'] ?? '', $csrf)) {
    setFlash('error', 'Invalid request.');
    header('Location: list.php'); exit;
}

$db  = Database::getInstance();
$emp = $db->fetchOne("SELECT first_name,last_name,employee_id,company_id FROM employees WHERE id=?", [$id]);
// FIX (07 Jul 2026): don't let anyone terminate an employee belonging to
// a different organization just by passing a different ?id=.
if ($emp && !in_array($emp['company_id'], orgCompanyIds($db))) { $emp = null; }
if (!$emp) { setFlash('error','Employee not found.'); header('Location: list.php'); exit; }

// Soft delete — set status to terminated instead of deleting record
$db->execute("UPDATE employees SET status='terminated' WHERE id=?", [$id]);

// Deactivate user account linked to this employee
$db->execute("UPDATE users SET is_active=0 WHERE employee_id=?", [$id]);

auditLog('DELETE', 'employees', $id, ['status'=>'active'], ['status'=>'terminated']);
setFlash('success', 'Employee '.clean($emp['first_name'].' '.$emp['last_name']).' ('.$emp['employee_id'].') has been deactivated.');
header('Location: list.php'); exit;