<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/cache.php';

$id = $_GET['id'] ?? null;
if (!$id) {
    echo json_encode(['success' => false, 'error' => 'Missing employee ID']);
    exit;
}

// Start transaction for data integrity
$mysqli->begin_transaction();

try {
    // Delete from all related tables
    $tables = [
        'ppe_issuance' => 'personnel_id',
        'ppe_requests' => 'id',
        'competence_training' => 'id',
        'competence_medical' => 'id'
    ];

    foreach ($tables as $table => $idField) {
        $deleteStmt = $mysqli->prepare("DELETE FROM $table WHERE personnel_id = ?");
        if ($deleteStmt) {
            $deleteStmt->bind_param("i", $id);
            $deleteStmt->execute();
            $deleteStmt->close();
        }
    }

    // Delete the employee from personnel table
    $stmt = $mysqli->prepare("DELETE FROM personnel WHERE id = ?");
    $stmt->bind_param("i", $id);
    $ok = $stmt->execute();

    if ($ok) {
        $mysqli->commit();
        // Clear all caches
        $cache->flush('personnel');
        $cache->flush('departments');
        echo json_encode(['success' => true, 'message' => 'Employee and all related records deleted permanently']);
    } else {
        $mysqli->rollback();
        echo json_encode(['success' => false, 'error' => 'Failed to delete employee']);
    }
} catch (Exception $e) {
    $mysqli->rollback();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
