<?php
/**
 * Enterprise HRM ERP System - Delete Resigned & Abscondee Record
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$siteId = getCurrentSiteId();
$exitId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

if ($exitId <= 0) {
    redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php?month=' . $selectedMonth . '&year=' . $selectedYear, 'Invalid record ID.', 'error');
}

try {
    $db = getDB();
    $db->beginTransaction();
    
    // Check if record exists and belongs to this site
    $stmt = $db->prepare("SELECT exit_id FROM resigned_abscondee WHERE exit_id = ? AND site_id = ?");
    $stmt->execute([$exitId, $siteId]);
    $record = $stmt->fetch();
    
    if (!$record) {
        $db->rollBack();
        redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php?month=' . $selectedMonth . '&year=' . $selectedYear, 'Record not found.', 'error');
    }
    
    // Delete record
    $stmt = $db->prepare("DELETE FROM resigned_abscondee WHERE exit_id = ? AND site_id = ?");
    $stmt->execute([$exitId, $siteId]);
    
    $db->commit();
    
    logAudit('DELETE', 'resigned_abscondee', $exitId);
    
    redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php?month=' . $selectedMonth . '&year=' . $selectedYear, 'Record deleted successfully.');
    
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    error_log("Error deleting entry: " . $e->getMessage());
    redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php?month=' . $selectedMonth . '&year=' . $selectedYear, 'Error deleting record.', 'error');
}

