<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'leave_script.php';
require '../config.php'; // Ensure database connection is active

// 1. Role verification gate
if (!isset($_SESSION['role'])) {
    die("Access Denied: Session unauthorized.");
}
$userRole = strtolower($_SESSION['role']);
$username = $_SESSION['username'] ?? 'User';
$isPrivilegedUser = in_array($userRole, ['hr', 'admin', 'superadmin']);

/*
|--------------------------------------------------------------------------
| DYNAMIC WORKFLOW CONFIGURATION ENGINE
|--------------------------------------------------------------------------
*/
// Fetch all stages configured in your dynamic schema setup
$allStages = [];
$stageOrderMap = [];
$stageRes = $conn->query("SELECT * FROM leave_approval_stages ORDER BY stage_order ASC");
if ($stageRes) {
    while ($sRow = $stageRes->fetch_assoc()) {
        $allStages[] = $sRow;
        $stageOrderMap[$sRow['checking_column']] = $sRow;
    }
}

// Find the specific step assigned to the currently logged-in user role
$myAssignedStage = null;
foreach ($allStages as $stage) {
    if (strtolower($stage['role_allowed']) === $userRole) {
        $myAssignedStage = $stage;
        break; // Found the active validation row for this user context
    }
}

// Block entry if the user's role isn't part of the approval configuration rule matrix and isn't administrative
if (!$myAssignedStage && !$isPrivilegedUser) {
    die("Access Denied: Your assigned role (" . htmlspecialchars($userRole) . ") does not have verification clearance.");
}

/*
|--------------------------------------------------------------------------
| DYNAMIC APPROVAL & PURGE ACTIONS INTERCEPTOR
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $leaveId = intval($_POST['leave_id']);
    $action  = $_POST['action']; // Expected values: 'approve', 'reject', 'purge'
    
    // 1. PURGE ENGINE ACTION (Administrative Purge Layer)
    if ($action === 'purge') {
        if (!$isPrivilegedUser) {
            header("Location: leave_approval.php?err=" . urlencode("Privilege Violation: Access denied to administrative deletion tools."));
            exit;
        }
        
        $delStmt = $conn->prepare("DELETE FROM leave_requests WHERE id = ?");
        $delStmt->bind_param("i", $leaveId);
        
        if ($delStmt->execute()) {
            header("Location: leave_approval.php?success=" . urlencode("Leave request entry completely purged from the system."));
        } else {
            header("Location: leave_approval.php?err=" . urlencode("Database exception encountered executing delete statement."));
        }
        $delStmt->close();
        exit;
    }
    
    // 2. APPROVAL/REJECTION STAGE ACTION
    if (in_array($action, ['approve', 'reject'])) {
        // Determine target column: either explicit target from request (for privileged users) or assigned stage column
        $targetColumn = '';
        if (!empty($_POST['target_column'])) {
            $targetColumn = $_POST['target_column'];
        } elseif ($myAssignedStage) {
            $targetColumn = $myAssignedStage['checking_column'];
        }

        // Validate that target column exists within valid defined stages
        $validColumns = array_column($allStages, 'checking_column');
        if (!in_array($targetColumn, $validColumns)) {
            header("Location: leave_approval.php?err=" . urlencode("Invalid workflow stage column targeted."));
            exit;
        }

        $statusValue = ($action === 'approve') ? 'Approved' : 'Rejected';
        
        // Fetch the leave record to verify date validity
        $checkLeaveQuery = $conn->query("SELECT start_date FROM leave_requests WHERE id = $leaveId");
        if ($checkLeaveQuery && $checkLeaveQuery->num_rows > 0) {
            $leaveRow = $checkLeaveQuery->fetch_assoc();
            // Block non-privileged users from approving expired timeline requests
            if (!$isPrivilegedUser && strtotime($leaveRow['start_date']) < strtotime(date('Y-m-d')) && $action === 'approve') {
                header("Location: leave_approval.php?err=" . urlencode("Validation Blocked: You cannot approve a leave request whose scheduled start date has already passed."));
                exit;
            }
        }

        // Dynamically update the specific stage column
        $stmt = $conn->prepare("
            UPDATE leave_requests 
            SET {$targetColumn} = ?, updated_at = NOW() 
            WHERE id = ?
        ");
        $stmt->bind_param("si", $statusValue, $leaveId);
        $stmt->execute();
        $stmt->close();
        
        /*
        |--------------------------------------------------------------------------
        | FINAL STEP DETECTOR & BALANCING LEDGER ACCOUNTING
        |--------------------------------------------------------------------------
        | If this was the last step in the setup table, deduction operations execute.
        | */
        $lastStage = end($allStages);
        if ($lastStage && $lastStage['checking_column'] === $targetColumn && $statusValue === 'Approved') {
            
            $leave = $conn->query("SELECT * FROM leave_requests WHERE id = $leaveId")->fetch_assoc();
            if ($leave) {
                $employeeId  = $leave['employee_id'];
                $leaveTypeId = $leave['leave_type_id'];
                $days        = intval($leave['total_days']);
                $year        = date('Y', strtotime($leave['start_date']));

                $check = $conn->query("
                    SELECT * FROM leave_balances 
                    WHERE employee_id = $employeeId AND leave_type_id = $leaveTypeId AND year = $year
                ");

                if ($check->num_rows) {
                    $conn->query("
                        UPDATE leave_balances 
                        SET used_days = used_days + $days, remaining_days = remaining_days - $days 
                        WHERE employee_id = $employeeId AND leave_type_id = $leaveTypeId AND year = $year
                    ");
                } else {
                    $type = $conn->query("SELECT days_allowed FROM leave_types WHERE id = $leaveTypeId")->fetch_assoc();
                    $allocated = intval($type['days_allowed'] ?? 0);
                    $remaining = $allocated - $days;

                    $conn->query("
                        INSERT INTO leave_balances (employee_id, leave_type_id, year, allocated_days, used_days, remaining_days) 
                        VALUES ($employeeId, $leaveTypeId, $year, $allocated, $days, $remaining)
                    ");
                }
            }
        }
        
        header("Location: leave_approval.php?success=" . urlencode("Record status updated successfully."));
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| DATA EXTRACTION ENGINE (DYNAMIC FILTER PIPELINE)
|--------------------------------------------------------------------------
*/
$requests = [];

if ($userRole === 'manager' && $myAssignedStage) {
    // 1. STRICT DEPARTMENTAL FILTER FOR MANAGERS: Only see their department's pending step
    $checkingCol    = $myAssignedStage['checking_column'];
    $prereqCol      = $myAssignedStage['prerequisite_column'];
    $prereqVal      = $myAssignedStage['prerequisite_value'];
    
    $query = "
        SELECT lr.*, lt.name AS leave_type, e.name AS employee_name, d.name AS department
        FROM leave_requests lr
        LEFT JOIN leave_types lt ON lt.id = lr.leave_type_id
        LEFT JOIN employees e ON e.id = lr.employee_id
        LEFT JOIN departments d ON d.id = e.department_id
        WHERE lr.{$checkingCol} = 'Pending'
          AND e.department_id = (SELECT department_id FROM employees WHERE id = " . intval($currentEmployeeId) . " LIMIT 1)
    ";
    
    if (!empty($prereqCol)) {
        $query .= " AND lr.{$prereqCol} = '" . $conn->real_escape_string($prereqVal) . "'";
    }
    
    $query .= " ORDER BY lr.created_at DESC";
    $res = $conn->query($query);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $requests[] = $row;
        }
    }
} else {
    // 2. GLOBAL OVERVIEW FOR HR, SUPERADMIN, ADMIN, ETC.
    $res = $conn->query("
        SELECT lr.*, lt.name AS leave_type, e.name AS employee_name, d.name AS department
        FROM leave_requests lr
        LEFT JOIN leave_types lt ON lt.id = lr.leave_type_id
        LEFT JOIN employees e ON e.id = lr.employee_id
        LEFT JOIN departments d ON d.id = e.department_id
        ORDER BY lr.created_at DESC
    ");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $requests[] = $row;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Approvals - HR System</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">
        
        <?php include '../components/sidebar.php'; ?>

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Toggle Side Area Menu">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">Authorization Portal</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Leave Pipelines</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 leading-tight"><?= htmlspecialchars($username); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($userRole ?: 'Staff'); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

                <?php if (!empty($_GET['success'])): ?>
                <div class="bg-emerald-50 border border-emerald-300 text-emerald-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">✅</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-emerald-950">Operation Successful</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight"><?= htmlspecialchars($_GET['success']) ?></p>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($_GET['err'])): ?>
                <div class="bg-rose-50 border border-rose-300 text-rose-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">❌</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-rose-950">Validation Error Enforced</h3>
                        <p class="text-[11px] text-rose-700 font-semibold leading-tight"><?= htmlspecialchars($_GET['err']) ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Active Scope Requests</p>
                                <h4 class="text-2xl font-black tracking-tight text-slate-950"><?= count($requests); ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Total entries awaiting dynamic rule evaluation.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-indigo-50 border border-indigo-200 flex items-center justify-center text-sm shrink-0">📋</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm hover:border-slate-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Clearance Target Matrix</p>
                                <h4 class="text-base font-black tracking-tight text-slate-950 mt-1 uppercase"><?= $myAssignedStage ? htmlspecialchars($myAssignedStage['stage_name']) : 'Admin Scope' ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Your explicit verification clearance context layer.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 flex items-center justify-center text-sm shrink-0">🔑</div>
                        </div>
                    </div>

                    <div class="bg-gradient-to-br from-slate-900 to-indigo-950 border border-slate-800 rounded-xl p-4 shadow-sm text-white sm:col-span-2 lg:col-span-1 flex flex-col justify-between">
                        <div class="flex items-center justify-between gap-4">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-black text-indigo-300 uppercase tracking-widest">Workflow Schema</p>
                                <h4 class="text-xs font-bold text-slate-100">Dynamic Active Engine Rules</h4>
                            </div>
                            <div class="text-lg">⚡</div>
                        </div>
                        <p class="text-[10px] text-slate-300 font-semibold mt-2.5 leading-tight">System validation contains <?= count($allStages) ?> absolute pipeline checkpoints sequentially enforced.</p>
                    </div>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    
                    <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Awaiting Verification Queue</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Detailed evaluation pipelines for tracking verification processes.</p>
                        </div>
                        <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">
                            <?= count($requests); ?> Loaded
                        </span>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[1000px] border-collapse">
                            <thead>
                                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                                    <th class="p-3 text-left w-[220px]">Employee</th>
                                    <th class="p-3 text-left">Department</th>
                                    <th class="p-3 text-left">Classification</th>
                                    <th class="p-3 text-center">Duration</th>
                                    <th class="p-3 text-center">Interval Timeline</th>
                                    <?php foreach ($allStages as $stg): ?>
                                        <th class="p-3 text-center"><?= htmlspecialchars($stg['stage_name']) ?> Status</th>
                                    <?php endforeach; ?>
                                    <th class="p-3 text-right pr-6">Administrative Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">

                            <?php if (empty($requests)): ?>
                            <tr>
                                <td colspan="<?= 6 + count($allStages) ?>" class="text-center py-12">
                                    <div class="flex flex-col items-center justify-center space-y-2">
                                        <div class="text-3xl">📭</div>
                                        <h4 class="text-xs font-extrabold text-slate-800">No Target Match Logs Found</h4>
                                        <p class="text-[10px] text-slate-600 max-w-xs">No records currently require your step validation clearance.</p>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>

                            <?php foreach ($requests as $row): ?>
                            <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                <td class="p-3 whitespace-nowrap">
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 text-slate-700 flex items-center justify-center font-black text-xs select-none">
                                            <?= strtoupper(substr($row['employee_name'] ?? 'E', 0, 1)); ?>
                                        </div>
                                        <div class="space-y-0.5">
                                            <p class="font-extrabold text-slate-900 leading-tight"><?= htmlspecialchars($row['employee_name'] ?? 'Unknown'); ?></p>
                                            <p class="text-[9px] text-slate-500 uppercase tracking-wider font-black">ID Log Record</p>
                                        </div>
                                    </div>
                                </td>

                                <td class="p-3 whitespace-nowrap text-left font-black text-slate-500 text-[10px] uppercase tracking-wide">
                                    <?= htmlspecialchars($row['department'] ?? 'N/A') ?>
                                </td>

                                <td class="p-3 whitespace-nowrap text-left">
                                    <span class="bg-slate-100 border border-slate-300 text-slate-700 px-2 py-0.5 rounded font-black text-[10px]">
                                        <?= htmlspecialchars($row['leave_type'] ?? 'General') ?>
                                    </span>
                                </td>

                                <td class="p-3 whitespace-nowrap text-center">
                                    <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">
                                        <?= $row['total_days'] ?> days
                                    </span>
                                </td>

                                <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                    <?= $row['start_date'] ?> <span class="text-slate-400 mx-1">➔</span> <?= $row['end_date'] ?>
                                </td>
                                
                                <?php foreach ($allStages as $stg): 
                                    $colName = $stg['checking_column'];
                                    $valStatus = $row[$colName] ?? 'Pending';
                                    
                                    $badgeClass = 'bg-amber-50 text-amber-900 border-amber-300';
                                    if ($valStatus === 'Approved') $badgeClass = 'bg-emerald-50 text-emerald-800 border-emerald-300';
                                    if ($valStatus === 'Rejected') $badgeClass = 'bg-rose-50 text-rose-900 border-rose-300';
                                ?>
                                    <td class="p-3 text-center whitespace-nowrap">
                                        <span class="inline-block px-2 py-1 border rounded-md font-black text-[10px] min-w-[85px] text-center <?= $badgeClass ?>">
                                            <?= htmlspecialchars($valStatus) ?>
                                        </span>
                                    </td>
                                <?php endforeach; ?>

                                <td class="p-3 text-right pr-6 whitespace-nowrap">
                                    <div class="inline-flex items-center gap-2">
                                        <?php 
                                        $today = strtotime(date('Y-m-d'));
                                        $startDatePassed = (strtotime($row['start_date']) < $today);
                                        $endDatePassed = (strtotime($row['end_date']) < $today);
                                        
                                        $isFullyApproved = true;
                                        $firstPendingCol = null;
                                        foreach ($allStages as $stg) {
                                            $currCol = $stg['checking_column'];
                                            if (($row[$currCol] ?? 'Pending') !== 'Approved') {
                                                $isFullyApproved = false;
                                                if (!$firstPendingCol && ($row[$currCol] ?? 'Pending') === 'Pending') {
                                                    $firstPendingCol = $currCol;
                                                }
                                            }
                                        }

                                        // Determine active evaluation state
                                        $isPendingForUser = false;
                                        $activeTargetCol = '';

                                        if ($isPrivilegedUser) {
                                            if ($firstPendingCol !== null) {
                                                $isPendingForUser = true;
                                                $activeTargetCol = $firstPendingCol;
                                            }
                                        } elseif ($myAssignedStage) {
                                            $myCol = $myAssignedStage['checking_column'];
                                            if (($row[$myCol] ?? 'Pending') === 'Pending') {
                                                $isPendingForUser = true;
                                                $activeTargetCol = $myCol;
                                            }
                                        }

                                        if ($isFullyApproved && $endDatePassed): ?>
                                            <span class="bg-emerald-50 text-emerald-800 border border-emerald-300 px-2.5 py-1 rounded-md font-black text-[10px] uppercase tracking-wide">
                                                ✅ Completed
                                            </span>
                                        <?php elseif ($isPendingForUser): 
                                            if ($startDatePassed && !$isPrivilegedUser): ?>
                                                <span class="bg-rose-50 text-rose-900 border border-rose-300 px-2.5 py-1 rounded-md font-black text-[10px] uppercase tracking-wide">
                                                    ⚠️ Window Expired
                                                </span>
                                            <?php else: ?>
                                                <form method="POST" class="inline-flex gap-1.5">
                                                    <input type="hidden" name="leave_id" value="<?= $row['id'] ?>">
                                                    <input type="hidden" name="target_column" value="<?= htmlspecialchars($activeTargetCol) ?>">
                                                    <button type="submit" name="action" value="approve" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white px-2.5 py-1 rounded-md font-bold text-[10px] border border-slate-950">
                                                        Approve
                                                    </button>
                                                    <button type="submit" name="action" value="reject" class="bg-white hover:bg-stone-50 border border-slate-300 text-slate-700 active:scale-[0.98] transition px-2.5 py-1 rounded-md font-bold text-[10px]">
                                                        Reject
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="text-[10px] text-slate-400 font-extrabold italic pr-1">Processed / Inactive</span>
                                        <?php endif; ?>

                                        <?php if ($isPrivilegedUser): ?>
                                            <form method="POST" onsubmit="return confirm('Are you sure you want to completely purge this leave request? This action cannot be undone.');" class="inline-block">
                                                <input type="hidden" name="leave_id" value="<?= $row['id'] ?>">
                                                <button type="submit" name="action" value="purge" class="bg-rose-50 hover:bg-rose-100 text-rose-900 border border-rose-300 active:scale-[0.98] transition px-2.5 py-1 rounded-md font-bold text-[10px]">
                                                    Purge
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>
        </div>
    </div>

    <script src="../components/sidebar.js"></script>
    <script>
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        if(sidebar) sidebar.classList.toggle('-translate-x-full');
        if(overlay) overlay.classList.toggle('hidden');
    }
    </script>
</body>
</html>