<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
error_reporting(0); // Suppress inline tracking errors to avoid corrupting JSON stream output
header('Content-Type: application/json; charset=utf-8');

require '../config.php';

if (session_status() === PHP_SESSION_NONE && !headers_sent()) { session_start(); }
session_write_close();

if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
    echo json_encode(['status' => 'error', 'message' => 'Security Error: Missing authorization context profiles.']);
    exit;
}

$userRole = strtolower(trim($_SESSION['role']));

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['request_id']) || !isset($_POST['action_type'])) {
    echo json_encode(['status' => 'error', 'message' => 'Malformed interface routing parameters.']);
    exit;
}

$requestId = intval($_POST['request_id']);
$actionType = strtoupper(trim($_POST['action_type']));

if ($requestId <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid identifying record parameters.']);
    exit;
}

// 1. Fetch Target Data Matrix Row
$reqStmt = $conn->prepare("SELECT * FROM leave_requests WHERE id = ? LIMIT 1");
$reqStmt->bind_param("i", $requestId);
$reqStmt->execute();
$requestData = $reqStmt->get_result()->fetch_assoc();
$reqStmt->close();

if (!$requestData) {
    echo json_encode(['status' => 'error', 'message' => 'Target entity not found in matching rows.']);
    exit;
}

// ---- PRIVILEGED DELETION LOGIC LAYER ----
if ($actionType === 'DELETE') {
    if (!in_array($userRole, ['admin', 'superadmin', 'hr'])) {
        echo json_encode(['status' => 'error', 'message' => 'Access Denied: Insufficient authorization level to remove data entries.']);
        exit;
    }
    $delStmt = $conn->prepare("DELETE FROM leave_requests WHERE id = ?");
    $delStmt->bind_param("i", $requestId);
    if ($delStmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Leave application completely purged from system tables.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Database operation error executing deletion schema.']);
    }
    $delStmt->close();
    exit;
}

// ---- DYNAMIC RULES ENGINE WORKFLOW EVALUATION ----
$stages = [];
$stageRes = $conn->query("SELECT * FROM leave_approval_stages ORDER BY stage_order ASC");
while ($stageRes && $row = $stageRes->fetch_assoc()) {
    $stages[] = $row;
}

$targetColumn = null;
$isValidatingRole = false;

foreach ($stages as $stage) {
    // Dynamically checks roles like "manager", "general manager", or "operations manager"
    if (strtolower(trim($stage['role_allowed'])) === $userRole) {
        
        // Assert dependent prerequisite rules match state context
        if (!empty($stage['prerequisite_column'])) {
            $preCol = $stage['prerequisite_column'];
            $expectedPreVal = strtolower(trim($stage['prerequisite_value']));
            
            // Look up what that exact leave request row reads right now
            $currentPreVal = isset($requestData[$preCol]) ? strtolower(trim($requestData[$preCol])) : '';
            
            if ($currentPreVal !== $expectedPreVal) {
                echo json_encode([
                    'status' => 'error', 
                    'message' => "Workflow Blocker: This request must be verified at step '{$stage['stage_name']}' before your account role can sign off."
                ]);
                exit;
            }
        }
        
        $targetColumn = $stage['checking_column'];
        $isValidatingRole = true;
        break; 
    }
}

// Administrative Fail-safe Override Row
if (!$isValidatingRole && in_array($userRole, ['admin', 'superadmin'])) {
    // If Admin is interacting manually, target the master structural state field column directly
    $targetColumn = 'hr_status'; 
    $isValidatingRole = true;
}

if (!$isValidatingRole || empty($targetColumn)) {
    echo json_encode(['status' => 'error', 'message' => 'Access Denied: Your corporate account role does not hold active verification clearance at this milestone phase.']);
    exit;
}

$statusString = ($actionType === 'APPROVE') ? 'Approved' : 'Rejected';

// Execute the dynamic update query securely
$updateQuery = "UPDATE leave_requests SET {$targetColumn} = ? WHERE id = ?";
$updateStmt = $conn->prepare($updateQuery);
$updateStmt->bind_param("si", $statusString, $requestId);

if ($updateStmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => "Request target column '{$targetColumn}' successfully set to '{$statusString}'."]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Fatal Exception: Failed updating backend validation metrics matrix.']);
}
$updateStmt->close();
exit;