<?php
// public/personnel/delete.php
declare(strict_types=1);

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/flash.php';
// ensure $pdo is loaded

session_start();
require_login();
$user = current_user();

// Only admin/hr can delete
if (!in_array($user['role'], ['admin','hr'], true)) {
    set_flash('You are not authorized to delete personnel records.', 'danger');
    header('Location: index.php');
    exit;
}

// ✅ Define CSRF check function if not already defined
if (!function_exists('check_csrf')) {
    function check_csrf(string $token): void {
        if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
            set_flash('Invalid CSRF token.', 'danger');
            header('Location: index.php');
            exit;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf($_POST['csrf_token'] ?? '');

    $id = (int)($_POST['id'] ?? 0);

    if ($id > 0) {
        $stmt = $pdo->prepare("DELETE FROM personnel WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $id]);

        if ($stmt->rowCount() > 0) {
            set_flash('Personnel record deleted successfully.', 'success');
        } else {
            set_flash('Record not found or could not be deleted.', 'warning');
        }
    } else {
        set_flash('Invalid personnel ID.', 'danger');
    }

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