<?php
/**
 * loan_request_script.php
 * Automated Transaction Processing Engine Pipeline
 */

// 1. Establish strict JSON streaming protocol context 
header('Content-Type: application/json; charset=utf-8');

require '../config.php';
if (session_status() === PHP_SESSION_NONE && !headers_sent()) { session_start(); }
session_write_close();

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

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

// ========================================================
// UNIVERSAL AGGREGATE INPUT LAYER PARSER (HYBRID FIX)
// ========================================================
$inputData = [];
if (!empty($_POST)) { 
    $inputData = $_POST; 
}
$rawPayload = file_get_contents('php://input');
if (!empty($rawPayload)) {
    $decoded = json_decode($rawPayload, true);
    if (is_array($decoded)) { 
        $inputData = array_merge($inputData, $decoded); 
    }
}
if (!empty($_GET)) { 
    $inputData = array_merge($inputData, $_GET); 
}
// ========================================================

// 3. Validation Matrices Verification
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.',
        'debug_received_payload' => $inputData
    ]);
    exit;
}

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

if ($requestId <= 0 || !in_array($actionType, ['APPROVE', 'REJECT', 'DELETE'])) {
    echo json_encode(['status' => 'error', 'message' => 'Validation Failure: Invalid argument matrices passed.']);
    exit;
}

// 4. ROUTE: DELETE Engine Action (Administrative Purge)
if ($actionType === 'DELETE') {
    if (!in_array($userRole, ['admin', 'superadmin', 'hr'])) {
        echo json_encode(['status' => 'error', 'message' => 'Privilege Violation: Access denied to administrative structural deletion tools.']);
        exit;
    }

    $delStmt = $conn->prepare("DELETE FROM employee_loans WHERE id = ?");
    $delStmt->bind_param("i", $requestId);
    
    if ($delStmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Record entry purged completely from master tables successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Database exception encountered executing purge statement.']);
    }
    $delStmt->close();
    exit;
}

// 5. ROUTE: APPROVE / REJECT Workflow Matrix Core Routing
$loanQuery = $conn->prepare("SELECT * FROM employee_loans WHERE id = ? LIMIT 1");
$loanQuery->bind_param("i", $requestId);
$loanQuery->execute();
$requestData = $loanQuery->get_result()->fetch_assoc();
$loanQuery->close();

if (!$requestData) {
    echo json_encode(['status' => 'error', 'message' => 'Record Execution Mistrack: Targeted corporate loan entry does not exist.']);
    exit;
}

// Build structural casing safety map
$realColumns = array_keys($requestData);
$realColumnMap = [];
foreach ($realColumns as $col) { 
    $realColumnMap[strtolower($col)] = $col; 
}

$statusKey = $realColumnMap['status'] ?? 'status';
$currentStatusValue = !empty($requestData[$statusKey]) ? trim($requestData[$statusKey]) : 'Pending';

// Block changes if workflow is already finalized
if (in_array(strtolower($currentStatusValue), ['active', 'closed', 'rejected'])) {
    echo json_encode([
        'status' => 'error', 
        'message' => "Workflow Closed: This record is finalized as '{$currentStatusValue}' and cannot be altered."
    ]);
    exit;
}

// Pull active dynamic operational system engine configuration rules
$stages = [];
$stageRes = $conn->query("SELECT * FROM loan_approval_stages ORDER BY stage_order ASC");
while ($stageRes && $row = $stageRes->fetch_assoc()) {
    $stages[] = $row;
}

if (empty($stages)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Pipeline Fault: No authorization stages found. Define steps in configuration panel first.'
    ]);
    exit;
}

$targetColumn = null;
$isValidatingRole = false;

// Evaluate structural constraints and prerequisites per step configuration
foreach ($stages as $stage) {
    if (strtolower(trim($stage['role_allowed'])) === $userRole) {
        
        // Execute dynamic prerequisite structural gate rule evaluation
        if (!empty($stage['prerequisite_column'])) {
            $preColLower = strtolower(trim($stage['prerequisite_column']));
            $preCol = $realColumnMap[$preColLower] ?? $stage['prerequisite_column'];
            $expectedPreVal = strtolower(trim($stage['prerequisite_value']));
            $currentPreVal = isset($requestData[$preCol]) ? strtolower(trim($requestData[$preCol])) : '';
            
            if ($currentPreVal !== $expectedPreVal) {
                echo json_encode([
                    'status' => 'error', 
                    'message' => "Workflow Blocker: Requires stage '{$stage['prerequisite_column']}' to read '{$stage['prerequisite_value']}' first."
                ]);
                exit;
            }
        }
        
        $chkColLower = strtolower(trim($stage['checking_column']));
        $targetColumn = $realColumnMap[$chkColLower] ?? $stage['checking_column'];
        $isValidatingRole = true;
        break; 
    }
}

// Fallback Administrative override framework tracking
if (!$isValidatingRole && in_array($userRole, ['admin', 'superadmin'])) {
    $targetColumn = $realColumnMap['hr_status'] ?? 'status';
    $isValidatingRole = true;
}

if (!$isValidatingRole || empty($targetColumn)) {
    echo json_encode(['status' => 'error', 'message' => 'Authorization Guard Violation: Current system configuration maps no operational signature rights to your role at this phase.']);
    exit;
}

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

// Begin transactional atomic processing
$conn->begin_transaction();

try {
    $updateQueryString = "UPDATE employee_loans SET `{$targetColumn}` = ? WHERE id = ?";
    $updateStmt = $conn->prepare($updateQueryString);
    $updateStmt->bind_param("si", $newStateString, $requestId);
    $updateStmt->execute();
    $updateStmt->close();

    // 6. DYNAMIC AUTOMATION: Evaluate and advance workflow global state engine
    $freshLoanQuery = $conn->prepare("SELECT * FROM employee_loans WHERE id = ? LIMIT 1");
    $freshLoanQuery->bind_param("i", $requestId);
    $freshLoanQuery->execute();
    $freshData = $freshLoanQuery->get_result()->fetch_assoc();
    $freshLoanQuery->close();
    
    $totalStagesCount = count($stages);
    $approvedStagesCount = 0;
    $hasAnyRejection = false;

    foreach ($stages as $stg) {
        $cNameLower = strtolower(trim($stg['checking_column']));
        $cName = $realColumnMap[$cNameLower] ?? $stg['checking_column'];
        
        // Handle values case-insensitively for complete safety
        $currentVal = isset($freshData[$cName]) ? ucfirst(strtolower(trim($freshData[$cName]))) : '';
        
        if ($currentVal === 'Approved') { 
            $approvedStagesCount++; 
        } elseif ($currentVal === 'Rejected') { 
            $hasAnyRejection = true; 
        }
    }

    // Determine parent state upgrades
    $finalMasterState = 'Pending';
    if ($hasAnyRejection) {
        $finalMasterState = 'Rejected';
    } elseif ($totalStagesCount > 0 && $approvedStagesCount === $totalStagesCount) {
        $finalMasterState = 'Active'; // All configured stages are "Approved"!
    }

    // Safely apply changes to master index status column
    if ($finalMasterState !== 'Pending' && isset($realColumnMap['status'])) {
        $masterTarget = $realColumnMap['status'];
        $masterStmt = $conn->prepare("UPDATE employee_loans SET `{$masterTarget}` = ? WHERE id = ?");
        $masterStmt->bind_param("si", $finalMasterState, $requestId);
        $masterStmt->execute();
        $masterStmt->close();
    }

    $conn->commit();
    
    $userMsg = ($actionType === 'APPROVE') 
        ? "Pipeline signature registered! Verification logged as 'Approved'." 
        : "Workflow breakdown warning: Entry explicitly flag-marked as Rejected.";
        
    echo json_encode(['status' => 'success', 'message' => $userMsg]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => 'Critical Transaction Rollback Exception: ' . $e->getMessage()]);
}
exit;