<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
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']));

// Checking both standard POST and JSON raw payloads to prevent stream drops
$inputData = $_POST;
if (empty($inputData)) {
    $rawPayload = file_get_contents('php://input');
    $decoded = json_decode($rawPayload, true);
    if (is_array($decoded)) { $inputData = $decoded; }
}

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

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

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

// Fetch Target Data Matrix Row from employee_loans
$reqStmt = $conn->prepare("SELECT * FROM employee_loans 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 employee_loans WHERE id = ?");
    $delStmt->bind_param("i", $requestId);
    if ($delStmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Loan 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 loan_approval_stages ORDER BY stage_order ASC");
while ($stageRes && $row = $stageRes->fetch_assoc()) {
    $stages[] = $row;
}

$targetColumn = null;
$isValidatingRole = false;

foreach ($stages as $stage) {
    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 loan 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 milestone step '{$stage['stage_name']}' before your account role can sign off."
                ]);
                exit;
            }
        }
        
        $targetColumn = preg_replace('/[^a-zA-Z0-9_]/', '', $stage['checking_column']);
        $isValidatingRole = true;
        break; 
    }
}

// Administrative Fail-safe Override Row
if (!$isValidatingRole && in_array($userRole, ['admin', 'superadmin'])) {
    $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 with safely wrapped backticks
$updateQuery = "UPDATE employee_loans SET `{$targetColumn}` = ? WHERE id = ?";
$updateStmt = $conn->prepare($updateQuery);
$updateStmt->bind_param("si", $statusString, $requestId);

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