<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();
require '../config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$username = $_SESSION['username'] ?? 'Admin';
$role     = $_SESSION['role'] ?? 'HR Admin';

// Filter State Capture
$search        = trim($_GET['search'] ?? '');
$dept_filter   = trim($_GET['department'] ?? '');
$status_filter = trim($_GET['status'] ?? '');

// Inline Action Handler: Toggle ID Card Status (Supports both standard redirect & AJAX JSON responses)
if (isset($_GET['action']) && $_GET['action'] === 'toggle_status' && !empty($_GET['card_id'])) {
    $toggle_card_id = (int)$_GET['card_id'];
    
    // Fetch current status
    $stmt_status = $conn->prepare("SELECT status FROM id_cards WHERE id = ?");
    $stmt_status->bind_param("i", $toggle_card_id);
    $stmt_status->execute();
    $card_data = $stmt_status->get_result()->fetch_assoc();
    $stmt_status->close();

    if ($card_data) {
        $new_status = ($card_data['status'] === 'Active') ? 'Suspended' : 'Active';
        $stmt_update = $conn->prepare("UPDATE id_cards SET status = ? WHERE id = ?");
        $stmt_update->bind_param("si", $new_status, $toggle_card_id);
        $stmt_update->execute();
        $stmt_update->close();

        // If requested via AJAX, return JSON response immediately
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true, 
                'new_status' => $new_status, 
                'message' => "Card status updated to {$new_status}."
            ]);
            exit;
        }
    } else {
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Card record not found.']);
            exit;
        }
    }

    // Redirect back preserving filter state for standard non-AJAX requests
    $redirect_url = "index.php?" . http_build_query([
        'search' => $search,
        'department' => $dept_filter,
        'status' => $status_filter
    ]);
    header("Location: " . $redirect_url);
    exit;
}

// Build Search & Filter Conditions
$where_clauses = ["1=1"];
$params = [];
$types = "";

if ($search !== '') {
    $where_clauses[] = "(e.name LIKE ? OR e.employee_no LIKE ? OR c.card_number LIKE ?)";
    $search_param = "%{$search}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= "sss";
}

if ($dept_filter !== '') {
    $where_clauses[] = "(e.department_id = ? OR d.name = ?)";
    $params[] = $dept_filter;
    $params[] = $dept_filter;
    $types .= "ss";
}

if ($status_filter !== '') {
    if ($status_filter === 'Unissued') {
        $where_clauses[] = "c.id IS NULL";
    } else {
        $where_clauses[] = "c.status = ?";
        $params[] = $status_filter;
        $types .= "s";
    }
}

$where_sql = implode(" AND ", $where_clauses);

// Main Query retrieving employee records, avatars, and associated cards
$sql = "SELECT 
            e.id AS emp_id,
            e.employee_no,
            e.name,
            e.designation,
            e.department_id,
            e.avatar,
            d.name AS department_name,
            c.id AS card_id,
            c.card_number,
            c.status AS card_status,
            c.issue_date,
            c.expiry_date
        FROM employees e
        LEFT JOIN departments d ON (d.id = e.department_id OR d.name = e.department_id)
        LEFT JOIN id_cards c ON c.employee_id = e.id
        WHERE {$where_sql}
        ORDER BY e.name ASC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();

// Metrics aggregation
$total_emp     = $conn->query("SELECT COUNT(*) AS total FROM employees")->fetch_assoc()['total'] ?? 0;
$issued_cards  = $conn->query("SELECT COUNT(*) AS total FROM id_cards WHERE status = 'Active'")->fetch_assoc()['total'] ?? 0;
$pending_cards = $total_emp - $issued_cards;
$expired_cards = $conn->query("SELECT COUNT(*) AS total FROM id_cards WHERE status IN ('Expired', 'Suspended')")->fetch_assoc()['total'] ?? 0;

// Departments selection dropdown
$dept_res = $conn->query("SELECT DISTINCT id, name FROM departments ORDER BY name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ID Card Management - 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">
            
            <!-- Sticky Header -->
            <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">ID Card Management</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Credential Verification</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($role ?: '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">

                <!-- Metric Cards -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 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">Total Employees</p>
                                <h4 class="text-2xl font-black tracking-tight text-slate-950"><?= $total_emp; ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Active staff entries registered in system.</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-emerald-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 Cards</p>
                                <h4 class="text-2xl font-black tracking-tight text-emerald-950"><?= $issued_cards; ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Valid credentials currently in circulation.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-emerald-50 border border-emerald-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-amber-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">Unissued / Pending</p>
                                <h4 class="text-2xl font-black tracking-tight text-amber-950"><?= $pending_cards; ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Staff awaiting smart ID generation.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-amber-50 border border-amber-200 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 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">System Template</p>
                                <h4 class="text-xs font-bold text-slate-100">Smart PVC Configuration</h4>
                            </div>
                            <div class="text-lg">⚙️</div>
                        </div>
                        <a href="settings.php" class="mt-3.5 w-full bg-white/10 hover:bg-white/15 transition px-3 py-2 rounded-lg font-bold text-xs flex items-center justify-center gap-2 border border-white/10 active:scale-[0.98]">
                            Configure Card Layout
                        </a>
                    </div>
                </div>

                <!-- Filters -->
                <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm space-y-3">
                    <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                        <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Data Filters</h3>
                        <span class="text-[9px] font-bold text-indigo-700 uppercase">Apply search parameters</span>
                    </div>
                    <form method="get" class="grid grid-cols-1 sm:grid-cols-4 gap-3">
                        <input type="text" name="search" placeholder="Search employee, ID or card no..." value="<?= htmlspecialchars($search); ?>" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 placeholder-slate-500 font-bold">
                        
                        <select name="department" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold">
                            <option value="">All Departments</option>
                            <?php if ($dept_res): while ($d = $dept_res->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($d['id']) ?>" <?= $dept_filter == $d['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($d['name']) ?>
                                </option>
                            <?php endwhile; endif; ?>
                        </select>

                        <select name="status" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold">
                            <option value="">All Statuses</option>
                            <option value="Active" <?= $status_filter === 'Active' ? 'selected' : '' ?>>Active</option>
                            <option value="Unissued" <?= $status_filter === 'Unissued' ? 'selected' : '' ?>>Unissued</option>
                            <option value="Suspended" <?= $status_filter === 'Suspended' ? 'selected' : '' ?>>Suspended</option>
                            <option value="Expired" <?= $status_filter === 'Expired' ? 'selected' : '' ?>>Expired</option>
                        </select>

                        <button type="submit" class="w-full bg-slate-900 hover:bg-slate-800 active:scale-[0.99] transition text-white rounded-lg font-bold py-2 text-xs shadow-sm border border-slate-950">Apply Parameters</button>
                    </form>
                </div>

                <!-- Main Data Table -->
                <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">Employee ID Records</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Live credential deployment and security tracking.</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">
                            <?= $res ? $res->num_rows : 0; ?> Loaded
                        </span>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[800px] 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-[250px]">Employee Information</th>
                                    <th class="p-3 text-center">Department</th>
                                    <th class="p-3 text-center">Designation</th>
                                    <th class="p-3 text-center">Card Number</th>
                                    <th class="p-3 text-center">Metric Status</th>
                                    <th class="p-3 text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">

                            <?php if (!$res || $res->num_rows === 0): ?>
                            <tr>
                                <td colspan="6" 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">Adjust query parameters or issue new smart cards.</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>

                            <?php while ($r = $res->fetch_assoc()): 
                                $emp_no   = htmlspecialchars((string)($r['employee_no'] ?? 'N/A'));
                                $name     = htmlspecialchars((string)($r['name'] ?? 'Unassigned'));
                                $dept     = htmlspecialchars((string)($r['department_name'] ?? $r['department_id'] ?? 'General'));
                                $desig    = htmlspecialchars((string)($r['designation'] ?? 'Staff'));
                                $card_no  = htmlspecialchars((string)($r['card_number'] ?? '—'));
                                $status   = htmlspecialchars((string)($r['card_status'] ?? 'Pending'));

                                // Image Path Verification
                                $rawAvatar = !empty($r['avatar']) ? trim($r['avatar']) : '';
                                $avatarPhoto = null;

                                if (!empty($rawAvatar)) {
                                    $cleanPath = ltrim(str_replace('\\', '/', $rawAvatar), './');
                                    $serverPath = __DIR__ . '/../' . $cleanPath;
                                    if (file_exists($serverPath)) {
                                        $avatarPhoto = '../' . htmlspecialchars($cleanPath);
                                    }
                                }

                                // Fallback Initials Generation
                                $cleanStr = preg_replace('/^(mr\.|ms\.|mrs\.|dr\.|prof\.)\s+/i', '', trim($name));
                                $words    = explode(' ', $cleanStr);
                                $initials = strtoupper(substr(($words[0] ?? '') . ($words[1] ?? ''), 0, 2));
                                if (empty($initials)) $initials = 'EE';
                            ?>
                            <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                <td class="p-3 whitespace-nowrap">
                                    <div class="flex items-center gap-3">
                                        <?php if ($avatarPhoto): ?>
                                            <img src="<?= $avatarPhoto; ?>" alt="<?= $name; ?>" class="w-9 h-9 rounded-lg object-cover border border-slate-300 shadow-2xs shrink-0">
                                        <?php else: ?>
                                            <div class="w-9 h-9 rounded-lg bg-indigo-50 border border-indigo-200 text-indigo-900 flex items-center justify-center font-black text-xs select-none shrink-0">
                                                <?= $initials; ?>
                                            </div>
                                        <?php endif; ?>
                                        <div class="space-y-0.5">
                                            <p class="font-extrabold text-slate-900 leading-tight"><?=$name;?></p>
                                            <p class="text-[9px] text-indigo-700 uppercase tracking-wider font-black"><?=$emp_no;?></p>
                                        </div>
                                    </div>
                                </td>

                                <td class="p-3 text-center whitespace-nowrap">
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-black bg-stone-100 text-slate-700 border border-slate-200">
                                        <?=$dept;?>
                                    </span>
                                </td>

                                <td class="p-3 text-center whitespace-nowrap font-semibold text-slate-600 text-[11px]">
                                    <?=$desig;?>
                                </td>

                                <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                    <?=$card_no;?>
                                </td>

                                <td class="p-3 text-center whitespace-nowrap">
                                    <?php if ($status === 'Active'): ?>
                                        <span class="bg-emerald-50 text-emerald-800 border border-emerald-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Active</span>
                                    <?php elseif ($status === 'Suspended'): ?>
                                        <span class="bg-amber-50 text-amber-900 border border-amber-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Suspended</span>
                                    <?php elseif ($status === 'Expired'): ?>
                                        <span class="bg-rose-50 text-rose-900 border border-rose-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Expired</span>
                                    <?php else: ?>
                                        <span class="bg-stone-100 text-slate-700 border border-slate-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Not Issued</span>
                                    <?php endif; ?>
                                </td>

                                <td class="p-3 text-center whitespace-nowrap action-cell">
                                    <div class="flex items-center justify-center gap-2">
                                        <?php if (!empty($r['card_id'])): ?>
                                            <a href="print.php?id=<?=$r['card_id']?>" class="bg-white hover:bg-slate-100 text-slate-800 border border-slate-300 transition px-2.5 py-1 rounded font-black text-[10px] shadow-2xs">
                                                Print
                                            </a>
                                            <button onclick="toggleCardStatus(<?=$r['card_id']?>, this)" class="bg-amber-50 hover:bg-amber-100 text-amber-900 border border-amber-300 transition px-2 py-1 rounded font-black text-[10px] flex items-center gap-1">
                                                <span>Toggle</span>
                                            </button>
                                        <?php else: ?>
                                            <button onclick="generateCard(<?=$r['emp_id']?>, this)" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-900 border border-indigo-300 transition px-2.5 py-1 rounded font-black text-[10px] shadow-2xs flex items-center gap-1">
                                                <span>Generate</span>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                            <?php endif; ?>

                            </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>

    <!-- Toast Notification Overlay Container -->
    <div id="toast-container" class="fixed bottom-5 right-5 z-50 flex flex-col gap-2 pointer-events-none"></div>

    <script src="../components/sidebar.js"></script>
    <?php include '../loader_overlay.php'; ?>

    <script>
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        
        const bgColor = type === 'success' ? 'bg-slate-900 text-white border-emerald-500' : 'bg-rose-900 text-white border-rose-500';
        const icon = type === 'success' ? '✓' : '✕';
        
        toast.className = `pointer-events-auto flex items-center gap-3 px-4 py-3 rounded-xl border-l-4 shadow-xl text-xs font-bold transition-all duration-300 transform translate-y-4 opacity-0 ${bgColor}`;
        toast.innerHTML = `<span class="font-black text-sm">${icon}</span><span>${message}</span>`;
        
        container.appendChild(toast);
        
        // Trigger smooth slide-in
        setTimeout(() => {
            toast.classList.remove('translate-y-4', 'opacity-0');
        }, 10);

        // Auto removal after 3.5 seconds
        setTimeout(() => {
            toast.classList.add('opacity-0', 'translate-y-2');
            setTimeout(() => toast.remove(), 300);
        }, 3500);
    }

    async function generateCard(empId, btnElement) {
        const originalText = btnElement.innerHTML;
        btnElement.disabled = true;
        btnElement.innerHTML = `<svg class="animate-spin h-3 w-3 text-indigo-900" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg> Generating...`;

        try {
            const response = await fetch(`generate.php?employee_id=${empId}`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await response.json();

            if (data.success) {
                showToast(data.message, 'success');
                // Target parent table row
                const row = btnElement.closest('tr');
                
                // 1. Update Card Number column (4th column)
                row.querySelector('td:nth-child(4)').textContent = data.card_number;
                
                // 2. Update Status Badge column (5th column)
                row.querySelector('td:nth-child(5)').innerHTML = `<span class="bg-emerald-50 text-emerald-800 border border-emerald-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Active</span>`;
                
                // 3. Update Action Buttons column (6th column)
                btnElement.parentElement.innerHTML = `
                    <a href="print.php?id=${data.card_id}" class="bg-white hover:bg-slate-100 text-slate-800 border border-slate-300 transition px-2.5 py-1 rounded font-black text-[10px] shadow-2xs">Print</a>
                    <button onclick="toggleCardStatus(${data.card_id}, this)" class="bg-amber-50 hover:bg-amber-100 text-amber-900 border border-amber-300 transition px-2 py-1 rounded font-black text-[10px] flex items-center gap-1"><span>Toggle</span></button>
                `;
            } else {
                showToast(data.message || 'Generation failed.', 'error');
                btnElement.disabled = false;
                btnElement.innerHTML = originalText;
            }
        } catch (err) {
            showToast('Server connection error.', 'error');
            btnElement.disabled = false;
            btnElement.innerHTML = originalText;
        }
    }

    async function toggleCardStatus(cardId, btnElement) {
        const originalText = btnElement.innerHTML;
        btnElement.disabled = true;
        btnElement.innerHTML = `<svg class="animate-spin h-3 w-3 text-amber-900" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>`;

        try {
            const response = await fetch(`index.php?action=toggle_status&card_id=${cardId}`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await response.json();

            if (data.success) {
                showToast(data.message, 'success');
                const row = btnElement.closest('tr');
                const statusTd = row.querySelector('td:nth-child(5)');

                if (data.new_status === 'Active') {
                    statusTd.innerHTML = `<span class="bg-emerald-50 text-emerald-800 border border-emerald-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Active</span>`;
                } else {
                    statusTd.innerHTML = `<span class="bg-amber-50 text-amber-900 border border-amber-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Suspended</span>`;
                }
            } else {
                showToast(data.message || 'Unable to update card status.', 'error');
            }
        } catch (err) {
            showToast('Server connection error.', 'error');
        } finally {
            btnElement.disabled = false;
            btnElement.innerHTML = originalText;
        }
    }
    </script>
</body>
</html>