<?php
/**
 * Enterprise HRM ERP System - Delete Employee Master Change
 */

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

// Check permissions - allow HR Admin and Super Admin
if (!isHRAdmin() && !isSuperAdmin()) {
    redirect(BASE_URL . '/dashboard.php', 'Access denied. Only HR Admin and Super Admin can access this page.', 'error');
}

$siteId = getCurrentSiteId();

// Get and validate ID from URL
$changeId = 0;
if (isset($_GET['id'])) {
    $changeId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
    if ($changeId === false) {
        $changeId = 0;
    }
}

if ($changeId <= 0) {
    redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Invalid record ID. Please select a valid record to delete.', 'error');
}

// Get record data for audit log
try {
    $db = getDB();
    
    // First check if table exists
    $tableExists = $db->query("SHOW TABLES LIKE 'employee_master_change'")->rowCount() > 0;
    if (!$tableExists) {
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Table does not exist. Please run the migration first.', 'error');
    }
    
    // Check if change_id column exists
    $stmt = $db->query("SHOW COLUMNS FROM employee_master_change LIKE 'change_id'");
    if ($stmt->rowCount() == 0) {
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Table structure is incorrect. Please run the migration.', 'error');
    }
    
    // First try to get record without role restriction to verify it exists
    $checkStmt = $db->prepare("SELECT * FROM employee_master_change WHERE change_id = ?");
    $checkStmt->execute([$changeId]);
    $record = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$record) {
        error_log("Delete page - Record not found with change_id: {$changeId}");
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Record not found. Record ID: ' . $changeId, 'error');
    }
    
    // Now check role-based access
    if (isHRAdmin() && !isSuperAdmin()) {
        // HR Admin can only delete their own records
        if (isset($record['created_by']) && $record['created_by'] != getCurrentUserId()) {
            redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Access denied. You can only delete records you created.', 'error');
        }
    }
    
    // Delete record
    $deleteStmt = $db->prepare("DELETE FROM employee_master_change WHERE change_id = ?");
    $result = $deleteStmt->execute([$changeId]);
    
    if ($result && $deleteStmt->rowCount() > 0) {
        // Log audit
        try {
            logAudit('DELETE', 'employee_master_change', $changeId, $record, null);
        } catch (Exception $auditError) {
            error_log("Audit log error (non-critical): " . $auditError->getMessage());
        }
        
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Employee master change record deleted successfully.');
    } else {
        error_log("Delete failed - No rows affected. change_id: {$changeId}");
        redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'Failed to delete record. Please try again.', 'error');
    }
    
} catch (Exception $e) {
    error_log("Error deleting employee master change: " . $e->getMessage());
    redirect(BASE_URL . '/modules/employee/employee_master_change_list.php', 'An error occurred while deleting the record: ' . htmlspecialchars($e->getMessage()), 'error');
}

