<?php
/*
|--------------------------------------------------------------------------
| DYNAMIC DATA RETRIEVAL MATRIX
|--------------------------------------------------------------------------
*/
// Loop configuration structures passed down from index scope context 
// or fetched fallback models if context isolation is needed.
if (!isset($allStages) || empty($allStages)) {
    $allStages = [];
    $stageRes = $conn->query("SELECT * FROM leave_approval_stages ORDER BY stage_order ASC");
    if ($stageRes) {
        while ($sRow = $stageRes->fetch_assoc()) {
            $allStages[] = $sRow;
        }
    }
}

// Find the specific step assigned to the currently logged-in user role matrix context
$myAssignedStage = null;
$userRole = strtolower($_SESSION['role'] ?? 'staff');
foreach ($allStages as $stage) {
    if (strtolower($stage['role_allowed']) === $userRole) {
        $myAssignedStage = $stage;
        break;
    }
}

// Categorize requests dynamically using the multi-stage matrix columns
$pendingRequests = array_filter($requests, function($r) use ($allStages) {
    $isRejected = false;
    $hasPending = false;
    
    foreach ($allStages as $stg) {
        $status = strtolower($r[$stg['checking_column']] ?? 'pending');
        if ($status === 'rejected') {
            $isRejected = true;
        }
        if ($status === 'pending') {
            $hasPending = true;
        }
    }
    // It belongs in pending only if no stage has rejected it, and at least one stage is pending
    return !$isRejected && $hasPending;
});

$rejectedRequests = array_filter($requests, function($r) use ($allStages) {
    foreach ($allStages as $stg) {
        if (strtolower($r[$stg['checking_column']] ?? '') === 'rejected') {
            return true; // Any single structural rejection pushes this to the rejection archive
        }
    }
    return false;
});
?>

<div id="status-alert-container" class="hidden transition-all duration-300 mt-6">
    <div id="status-alert-body" class="p-4 rounded-xl text-sm font-semibold flex items-center justify-between shadow-sm border">
        <span id="status-alert-message"></span>
        <button onclick="document.getElementById('status-alert-container').classList.add('hidden')" class="text-xs opacity-60 hover:opacity-100 font-bold transition ml-4">✕</button>
    </div>
</div>

<div class="bg-white border border-slate-200/80 rounded-xl shadow-sm overflow-hidden mt-6">
    <div class="border-b border-slate-200 bg-white px-4">
        <nav class="flex space-x-6" aria-label="Tabs">
            <button onclick="switchStatusTab('pending-panel', this)" class="status-tab-btn border-b-2 border-[#10b981] text-[#10b981] py-4 px-1 font-semibold text-sm transition tracking-tight">
                Pending Leaves (<?= count($pendingRequests) ?>)
            </button>
            <button onclick="switchStatusTab('rejected-panel', this)" class="status-tab-btn border-b-2 border-transparent text-slate-400 hover:text-slate-600 py-4 px-1 font-medium text-sm transition tracking-tight">
                Rejected Leaves (<?= count($rejectedRequests) ?>)
            </button>
        </nav>
    </div>

    <div class="p-4 border-b border-slate-100 bg-slate-50/40 flex flex-col sm:flex-row items-center justify-between gap-4">
        <div class="flex flex-wrap items-center gap-2 w-full sm:w-auto">
            <div class="relative w-full sm:w-64">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-slate-400">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                </span>
                <input type="text" placeholder="Search..." class="w-full pl-9 pr-4 py-2 bg-white border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-[#10b981]/20 focus:outline-none">
            </div>
            <button class="bg-[#10b981] hover:bg-[#0f9f6e] text-white px-4 py-2 rounded-xl text-sm font-medium transition shadow-sm flex items-center gap-1">
                Search
            </button>
        </div>

        <div class="flex items-center gap-2 shrink-0 self-end sm:self-auto">
            <span class="text-xs text-slate-400 font-medium">Per Page:</span>
            <select class="bg-white border border-slate-200 text-slate-700 text-xs font-semibold p-2 rounded-lg focus:outline-none">
                <option>10</option>
                <option>25</option>
                <option>50</option>
            </select>
        </div>
    </div>

    <div id="pending-panel" class="status-panel-view block overflow-x-auto custom-scrollbar">
        <table class="w-full min-w-[1000px] border-collapse text-left text-sm text-slate-600">
            <thead>
                <tr class="bg-slate-50 border-b border-slate-200 text-slate-400 text-xs font-bold uppercase tracking-wider">
                    <th class="p-4 w-12 text-center">#</th>
                    <th class="p-4 w-[220px]">Employee</th>
                    <th class="p-4">Leave Type</th>
                    <th class="p-4 text-center">Duration</th>
                    <th class="p-4 text-center">Interval Timeline</th>
                    <?php foreach ($allStages as $stg): ?>
                        <th class="p-4 text-center text-xs font-bold text-slate-400 uppercase tracking-wider"><?= htmlspecialchars($stg['stage_name']) ?></th>
                    <?php endforeach; ?>
                    <th class="p-4 w-36 text-center">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php if (empty($pendingRequests)): ?>
                    <tr class="no-data-row"><td colspan="<?= 6 + count($allStages) ?>" class="p-8 text-center text-slate-400 font-medium">No pending leave applications found matching your criteria.</td></tr>
                <?php else: $idx = 1; foreach ($pendingRequests as $req): 
                    $ltLower = strtolower(trim($req['leave_type'] ?? ''));
                    $dotColor = $colorMap[$ltLower]['dot'] ?? 'bg-indigo-400';
                ?>
                    <tr id="request-row-<?= $req['id'] ?>" class="hover:bg-slate-50/50 transition">
                        <td class="p-4 text-center font-mono text-slate-400"><?= $idx++ ?></td>
                        <td class="p-4">
                            <div class="flex items-center gap-3">
                                <div class="w-8 h-8 rounded-full bg-gradient-to-tr from-emerald-100 to-teal-200 text-teal-700 flex items-center justify-center font-bold text-[11px] uppercase whitespace-nowrap">
                                    <?= substr($req['employee_name'] ?? 'E', 0, 2) ?>
                                </div>
                                <div class="leading-tight">
                                    <div class="font-bold text-slate-800"><?= htmlspecialchars($req['employee_name'] ?? 'Unknown Profile') ?></div>
                                    <div class="text-[11px] text-slate-400 font-semibold uppercase tracking-wide"><?= htmlspecialchars($req['department'] ?? 'Staff') ?></div>
                                </div>
                            </div>
                        </td>
                        <td class="p-4 font-medium text-slate-700">
                            <span class="inline-flex items-center gap-2">
                                <span class="w-2.5 h-2.5 rounded-full <?= $dotColor ?>"></span>
                                <?= htmlspecialchars($req['leave_type'] ?? 'General Leave') ?>
                            </span>
                        </td>
                        <td class="p-4 text-center font-black text-indigo-600 bg-indigo-50/20"><?= $req['total_days'] ?? '1' ?> <span class="text-[10px] font-normal text-slate-400">Days</span></td>
                        <td class="p-4 text-center font-mono text-xs text-slate-500 whitespace-nowrap">
                            <?= $req['start_date'] ?> <span class="text-slate-300 mx-0.5">➔</span> <?= $req['end_date'] ?>
                        </td>
                        
                        <?php foreach ($allStages as $stg): 
                            $colName = $stg['checking_column'];
                            $valStatus = $req[$colName] ?? 'Pending';
                            $badgeClass = 'bg-amber-100 text-amber-700 border-amber-200';
                            if ($valStatus === 'Approved') $badgeClass = 'bg-green-100 text-green-700 border-green-200';
                            if ($valStatus === 'Rejected') $badgeClass = 'bg-red-100 text-red-700 border-red-200';
                        ?>
                            <td class="p-4 text-center">
                                <span class="inline-block px-2.5 py-0.5 border rounded-full text-[11px] font-extrabold <?= $badgeClass ?>">
                                    <?= htmlspecialchars($valStatus) ?>
                                </span>
                            </td>
                        <?php endforeach; ?>

                        <td class="p-4 text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button type="button" class="p-1.5 text-blue-500 hover:bg-blue-50 rounded-lg transition" title="View details">👁</button>
                                
                                <?php if ($myAssignedStage && ($req[$myAssignedStage['checking_column']] ?? 'Pending') === 'Pending'): ?>
                                    <button type="button" onclick="executeWorkflowAction(<?= $req['id'] ?>, 'APPROVE')" class="p-1.5 text-emerald-500 hover:bg-emerald-50 rounded-lg transition font-bold" title="Approve Step">✓</button>
                                    <button type="button" onclick="executeWorkflowAction(<?= $req['id'] ?>, 'REJECT')" class="p-1.5 text-rose-500 hover:bg-rose-50 rounded-lg transition font-bold" title="Reject Step">✕</button>
                                <?php endif; ?>
                                
                                <?php if (in_array($userRole, ['admin', 'superadmin', 'hr'])): ?>
                                    <button type="button" onclick="executeWorkflowAction(<?= $req['id'] ?>, 'DELETE')" class="p-1.5 text-slate-400 hover:bg-slate-100 rounded-lg transition" title="Delete record">🗑</button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <div id="rejected-panel" class="status-panel-view hidden overflow-x-auto custom-scrollbar">
        <table class="w-full min-w-[1000px] border-collapse text-left text-sm text-slate-600">
            <thead>
                <tr class="bg-slate-50 border-b border-slate-200 text-slate-400 text-xs font-bold uppercase tracking-wider">
                    <th class="p-4 w-12 text-center">#</th>
                    <th class="p-4 w-[220px]">Employee</th>
                    <th class="p-4">Leave Type</th>
                    <th class="p-4 text-center">Duration</th>
                    <th class="p-4 text-center">Interval Timeline</th>
                    <?php foreach ($allStages as $stg): ?>
                        <th class="p-4 text-center text-xs font-bold text-slate-400 uppercase tracking-wider"><?= htmlspecialchars($stg['stage_name']) ?></th>
                    <?php endforeach; ?>
                    <th class="p-4 w-36 text-center">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php if (empty($rejectedRequests)): ?>
                    <tr class="no-data-row"><td colspan="<?= 6 + count($allStages) ?>" class="p-8 text-center text-slate-400 font-medium">No rejected leave records on account data.</td></tr>
                <?php else: $idx = 1; foreach ($rejectedRequests as $req): 
                    $ltLower = strtolower(trim($req['leave_type'] ?? ''));
                    $dotColor = $colorMap[$ltLower]['dot'] ?? 'bg-indigo-400';
                ?>
                    <tr id="request-row-<?= $req['id'] ?>" class="hover:bg-slate-50/50 transition">
                        <td class="p-4 text-center font-mono text-slate-400"><?= $idx++ ?></td>
                        <td class="p-4">
                            <div class="flex items-center gap-3">
                                <div class="w-8 h-8 rounded-full bg-gradient-to-tr from-slate-100 to-slate-200 text-slate-600 flex items-center justify-center font-bold text-[11px] uppercase whitespace-nowrap">
                                    <?= substr($req['employee_name'] ?? 'E', 0, 2) ?>
                                </div>
                                <div class="leading-tight">
                                    <div class="font-bold text-slate-800"><?= htmlspecialchars($req['employee_name'] ?? 'Unknown Profile') ?></div>
                                    <div class="text-[11px] text-slate-400 font-semibold uppercase tracking-wide"><?= htmlspecialchars($req['department'] ?? 'Staff') ?></div>
                                </div>
                            </div>
                        </td>
                        <td class="p-4 font-medium text-slate-700">
                            <span class="inline-flex items-center gap-2">
                                <span class="w-2.5 h-2.5 rounded-full <?= $dotColor ?>"></span>
                                <?= htmlspecialchars($req['leave_type'] ?? 'General Leave') ?>
                            </span>
                        </td>
                        <td class="p-4 text-center font-black text-slate-600 bg-slate-100/40"><?= $req['total_days'] ?? '1' ?> <span class="text-[10px] font-normal text-slate-400">Days</span></td>
                        <td class="p-4 text-center font-mono text-xs text-slate-500 whitespace-nowrap">
                            <?= $req['start_date'] ?> <span class="text-slate-300 mx-0.5">➔</span> <?= $req['end_date'] ?>
                        </td>
                        
                        <?php foreach ($allStages as $stg): 
                            $colName = $stg['checking_column'];
                            $valStatus = $req[$colName] ?? 'Pending';
                            $badgeClass = 'bg-amber-100 text-amber-700 border-amber-200';
                            if ($valStatus === 'Approved') $badgeClass = 'bg-green-100 text-green-700 border-green-200';
                            if ($valStatus === 'Rejected') $badgeClass = 'bg-red-100 text-red-700 border-red-200';
                        ?>
                            <td class="p-4 text-center">
                                <span class="inline-block px-2.5 py-0.5 border rounded-full text-[11px] font-extrabold <?= $badgeClass ?>">
                                    <?= htmlspecialchars($valStatus) ?>
                                </span>
                            </td>
                        <?php endforeach; ?>

                        <td class="p-4 text-center">
                            <div class="flex items-center justify-center gap-2">
                                <button type="button" class="p-1.5 text-blue-500 hover:bg-blue-50 rounded-lg transition">👁</button>
                                <?php if (in_array($userRole, ['admin', 'superadmin', 'hr'])): ?>
                                    <button type="button" onclick="executeWorkflowAction(<?= $req['id'] ?>, 'DELETE')" class="p-1.5 text-slate-400 hover:bg-slate-100 rounded-lg transition" title="Delete record">🗑</button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function switchStatusTab(panelId, element) {
    document.querySelectorAll('.status-panel-view').forEach(panel => panel.classList.add('hidden'));
    document.querySelectorAll('.status-tab-btn').forEach(btn => {
        btn.classList.remove('border-[#10b981]', 'text-[#10b981]', 'font-semibold');
        btn.classList.add('border-transparent', 'text-slate-400', 'font-medium');
    });
    document.getElementById(panelId).classList.remove('hidden');
    element.classList.remove('border-transparent', 'text-slate-400', 'font-medium');
    element.classList.add('border-b-2', 'border-[#10b981]', 'text-[#10b981]', 'font-semibold');
}

function displayBannerAlert(isSuccess, messageString) {
    const container = document.getElementById('status-alert-container');
    const body = document.getElementById('status-alert-body');
    const msgElement = document.getElementById('status-alert-message');
    
    msgElement.textContent = messageString;
    if (isSuccess) {
        body.className = "p-4 rounded-xl text-sm font-semibold flex items-center justify-between shadow-sm border bg-emerald-50 border-emerald-200 text-emerald-800";
    } else {
        body.className = "p-4 rounded-xl text-sm font-semibold flex items-center justify-between shadow-sm border bg-rose-50 border-rose-200 text-rose-800";
    }
    container.classList.remove('hidden');
    container.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function executeWorkflowAction(id, actionType) {
    if (actionType === 'DELETE' && !confirm('Are you sure you want to permanently delete this leave application entry?')) {
        return;
    }
    
    const formData = new FormData();
    // Match exact POST param expected by the workspace action interceptor block
    formData.append('leave_id', id);
    formData.append('action', actionType.toLowerCase());

    // Routing dynamically back to the controller handling the operations stack
    fetch('index.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (response.redirected) {
            // Handle HTTP redirect explicitly if the application returns raw headers
            window.location.href = response.url;
            return;
        }
        displayBannerAlert(true, "Operation verified successfully. Reloading view context...");
        const targetRow = document.getElementById(`request-row-${id}`);
        if (targetRow) {
            targetRow.style.opacity = '0';
            setTimeout(() => { targetRow.remove(); }, 300);
        }
        setTimeout(() => { window.location.reload(); }, 800);
    })
    .catch(error => {
        displayBannerAlert(false, "System Failure: Unable to complete operation request routing.");
        console.error(error);
    });
}
</script>