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

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

$conn = new mysqli("localhost", "nassrrkx_Asovtu", "nassrrkx_Asovtu", "nassrrkx_Asovtu");
if ($conn->connect_error) {
    die("DB Error");
}

$conn->set_charset("utf8mb4");

/* HELPERS */
function h($v){
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

function naira($v){
    return number_format((float)($v ?? 0), 2);
}

function isAjaxRequest(): bool {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

function getStatusBadgeHtml(string $status): string {
    $s = strtolower(trim($status));

    if ($s === 'processing') {
        return "<span class='px-3 py-1 bg-blue-500/20 text-blue-400 rounded-full text-xs font-semibold'>Processing</span>";
    } elseif ($s === 'in progress') {
        return "<span class='px-3 py-1 bg-orange-500/20 text-orange-400 rounded-full text-xs font-semibold'>In Progress</span>";
    } else {
        return "<span class='px-3 py-1 bg-yellow-500/20 text-yellow-400 rounded-full text-xs font-semibold'>Pending</span>";
    }
}

function getDashboardStats(mysqli $conn): array {
    $stats = [
        'pending' => 0,
        'in_progress' => 0,
        'processing' => 0
    ];

    $sql = "
        SELECT
            SUM(CASE WHEN LOWER(TRIM(status)) = 'pending' THEN 1 ELSE 0 END) AS pending_count,
            SUM(CASE WHEN LOWER(TRIM(status)) = 'in progress' THEN 1 ELSE 0 END) AS in_progress_count,
            SUM(CASE WHEN LOWER(TRIM(status)) = 'processing' THEN 1 ELSE 0 END) AS processing_count
        FROM validation_requests
    ";

    $res = $conn->query($sql);

    if ($res instanceof mysqli_result) {
        $row = $res->fetch_assoc();

        if ($row) {
            $stats['pending'] = (int)($row['pending_count'] ?? 0);
            $stats['in_progress'] = (int)($row['in_progress_count'] ?? 0);
            $stats['processing'] = (int)($row['processing_count'] ?? 0);
        }
    }

    return $stats;
}

function renderStatsCards(array $stats): string {
    ob_start();
    ?>
    <div class="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-6" id="stats-container">

        <div class="bg-yellow-600/90 p-5 rounded-2xl shadow-lg">
            <div class="text-lg font-bold mb-2">Total Pending</div>
            <div class="text-3xl font-extrabold"><?= (int)$stats['pending'] ?></div>
        </div>

        <div class="bg-orange-600/90 p-5 rounded-2xl shadow-lg">
            <div class="text-lg font-bold mb-2">Total In Progress</div>
            <div class="text-3xl font-extrabold"><?= (int)$stats['in_progress'] ?></div>
        </div>

        <div class="bg-blue-600/90 p-5 rounded-2xl shadow-lg">
            <div class="text-lg font-bold mb-2">Total Processing</div>
            <div class="text-3xl font-extrabold"><?= (int)$stats['processing'] ?></div>
        </div>

    </div>
    <?php
    return ob_get_clean();
}

function fetchValidationRows(mysqli $conn, string $searchNin = ''): array {
    $rows = [];

    $statusFilter = "
        LOWER(TRIM(status)) IN ('pending', 'in progress', 'processing')
    ";

    if ($searchNin !== '') {
        $like = "%" . $searchNin . "%";
        $sql = "SELECT * FROM validation_requests
                WHERE $statusFilter
                AND nin LIKE ?
                ORDER BY id DESC";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $like);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res instanceof mysqli_result) {
            while ($row = $res->fetch_assoc()) {
                $rows[] = $row;
            }
        }
        $stmt->close();
    } else {
        $sql = "SELECT * FROM validation_requests
                WHERE $statusFilter
                ORDER BY id DESC";

        $res = $conn->query($sql);

        if ($res instanceof mysqli_result) {
            while ($row = $res->fetch_assoc()) {
                $rows[] = $row;
            }
        }
    }

    return $rows;
}

function renderSearchInfo(string $searchNin, int $count): string {
    if ($searchNin === '') {
        return '';
    }

    return '
        <div class="mt-3 text-sm text-gray-300">
            Showing ' . $count . ' result(s) for NIN:
            <span class="text-white font-semibold">' . h($searchNin) . '</span>
        </div>
    ';
}

function renderTableRows(array $rows, string $searchNin = ''): string {
    ob_start();

    if (!empty($rows)):
        foreach ($rows as $r):
            ?>
            <tr class="border-b border-gray-700 hover:bg-white/5 transition" data-row-id="<?= (int)$r['id'] ?>">
                <td class="p-3"><?= h($r['user']) ?></td>
                <td class="p-3"><?= h($r['nin']) ?></td>
                <td class="p-3"><?= h($r['type'] ?? '') ?></td>
                <td class="p-3 text-green-400 font-semibold">₦<?= naira($r['price']) ?></td>
                <td class="p-3 status-cell"><?= getStatusBadgeHtml((string)$r['status']) ?></td>

                <td class="p-3">
                    <form method="post" class="space-y-2 update-form">
                        <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">

                        <select name="status" class="w-full p-2 rounded-lg bg-black/30 text-xs border border-gray-600">
                            <option value="Pending" <?= strtolower((string)$r['status']) === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="In Progress" <?= strtolower((string)$r['status']) === 'in progress' ? 'selected' : '' ?>>In Progress</option>
                            <option value="Processing" <?= strtolower((string)$r['status']) === 'processing' ? 'selected' : '' ?>>Processing</option>
                        </select>

                        <textarea
                            name="reply"
                            placeholder="Reply..."
                            class="w-full p-2 rounded-lg bg-black/30 text-xs border border-gray-600"
                        ><?= h($r['reply'] ?? '') ?></textarea>

                        <button
                            type="submit"
                            name="update"
                            class="w-full bg-blue-600 hover:bg-blue-700 text-xs p-2 rounded-lg font-semibold"
                        >
                            Update
                        </button>
                    </form>
                </td>
            </tr>
            <?php
        endforeach;
    else:
        ?>
        <tr>
            <td colspan="6" class="p-6 text-center text-gray-300">
                No pending, in progress, or processing requests found<?= $searchNin !== '' ? ' for this NIN search.' : '.' ?>
            </td>
        </tr>
        <?php
    endif;

    return ob_get_clean();
}

/* STATUS LIST */
$allowedStatuses = [
    'Pending',
    'In Progress',
    'Processing'
];

/* UPDATE */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
    $id = (int)($_POST['id'] ?? 0);
    $status = trim((string)($_POST['status'] ?? 'Pending'));
    $reply = trim((string)($_POST['reply'] ?? ''));

    if (!in_array($status, $allowedStatuses, true)) {
        $status = 'Pending';
    }

    $stmt = $conn->prepare("UPDATE validation_requests SET status=?, reply=? WHERE id=?");
    $stmt->bind_param("ssi", $status, $reply, $id);
    $ok = $stmt->execute();
    $stmt->close();

    if (isAjaxRequest()) {
        $stats = getDashboardStats($conn);

        header('Content-Type: application/json');
        echo json_encode([
            'success' => $ok,
            'message' => $ok ? 'Request updated successfully.' : 'Update failed.',
            'status_badge' => getStatusBadgeHtml($status),
            'stats_html' => renderStatsCards($stats)
        ]);
        exit;
    }

    header("Location: " . $_SERVER['REQUEST_URI']);
    exit;
}

/* SEARCH */
$searchNin = trim((string)($_GET['search_nin'] ?? ''));

/* AJAX SEARCH RESPONSE */
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isAjaxRequest()) {
    $rows = fetchValidationRows($conn, $searchNin);

    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'tbody_html' => renderTableRows($rows, $searchNin),
        'search_info_html' => renderSearchInfo($searchNin, count($rows))
    ]);
    exit;
}

/* FETCH */
$rows = fetchValidationRows($conn, $searchNin);

/* STATS */
$stats = getDashboardStats($conn);
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pending / In Progress / Processing</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-gradient-to-br from-slate-900 via-blue-900 to-slate-800 text-white min-h-screen">
<div class="max-w-7xl mx-auto p-6">

    <h1 class="text-3xl font-bold mb-6">📋 Pending / In Progress / Processing</h1>

    <div id="toast"
         class="hidden fixed top-5 right-5 z-50 min-w-[220px] max-w-sm px-4 py-3 rounded-lg shadow-lg text-sm font-semibold transition-all duration-300 opacity-0 -translate-y-2">
    </div>

    <!-- STATS -->
    <?= renderStatsCards($stats) ?>

    <!-- SEARCH -->
    <div class="bg-white/10 backdrop-blur-xl rounded-2xl p-4 mb-6 border border-white/10">
        <form method="get" id="searchForm" class="flex flex-col md:flex-row gap-3 md:items-center">
            <div class="flex-1">
                <label class="block text-sm text-gray-300 mb-1">Search by NIN</label>
                <input
                    type="text"
                    id="search_nin"
                    name="search_nin"
                    value="<?= h($searchNin) ?>"
                    placeholder="Enter NIN..."
                    class="w-full p-3 rounded-lg bg-black/30 text-white border border-gray-600 outline-none focus:border-blue-400"
                >
            </div>

            <div class="flex gap-2 md:self-end">
                <button
                    type="submit"
                    id="searchBtn"
                    class="bg-blue-600 hover:bg-blue-700 px-5 py-3 rounded-lg text-sm font-semibold"
                >
                    Search
                </button>

                <button
                    type="button"
                    id="clearSearchBtn"
                    class="bg-gray-600 hover:bg-gray-700 px-5 py-3 rounded-lg text-sm font-semibold"
                >
                    Clear
                </button>
            </div>
        </form>

        <div id="search-info">
            <?= renderSearchInfo($searchNin, count($rows)) ?>
        </div>
    </div>

    <!-- TABLE -->
    <div class="bg-white/10 backdrop-blur-xl rounded-2xl overflow-x-auto border border-white/10">
        <table class="min-w-full text-sm">
            <thead class="border-b border-gray-700 text-gray-300">
                <tr>
                    <th class="p-3 text-left">User</th>
                    <th class="p-3 text-left">NIN</th>
                    <th class="p-3 text-left">Type</th>
                    <th class="p-3 text-left">Price</th>
                    <th class="p-3 text-left">Status</th>
                    <th class="p-3 text-left">Action</th>
                </tr>
            </thead>

            <tbody id="table-body">
                <?= renderTableRows($rows, $searchNin) ?>
            </tbody>
        </table>
    </div>

</div>

<script>
function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');

    toast.textContent = message;
    toast.classList.remove(
        'hidden',
        'bg-green-600',
        'bg-red-600',
        'bg-orange-600',
        'text-white',
        'opacity-0',
        '-translate-y-2'
    );

    if (type === 'success') {
        toast.classList.add('bg-green-600', 'text-white');
    } else if (type === 'error') {
        toast.classList.add('bg-red-600', 'text-white');
    } else {
        toast.classList.add('bg-orange-600', 'text-white');
    }

    toast.classList.add('opacity-100', 'translate-y-0');

    clearTimeout(toast.hideTimeout);
    toast.hideTimeout = setTimeout(() => {
        toast.classList.remove('opacity-100', 'translate-y-0');
        toast.classList.add('opacity-0', '-translate-y-2');

        setTimeout(() => {
            toast.classList.add('hidden');
        }, 300);
    }, 2500);
}

function updateStatsHtml(html) {
    const oldStats = document.getElementById('stats-container');
    if (!oldStats || !html) return;

    const wrapper = document.createElement('div');
    wrapper.innerHTML = html.trim();
    const newStats = wrapper.querySelector('#stats-container');

    if (newStats) {
        oldStats.replaceWith(newStats);
    }
}

function bindUpdateForms() {
    document.querySelectorAll('.update-form').forEach(form => {
        if (form.dataset.bound === '1') return;
        form.dataset.bound = '1';

        form.addEventListener('submit', async function(e) {
            e.preventDefault();

            const row = form.closest('tr');
            const statusCell = row.querySelector('.status-cell');
            const submitBtn = form.querySelector('button[name="update"]');
            const formData = new FormData(form);
            formData.append('update', '1');

            submitBtn.disabled = true;
            submitBtn.textContent = 'Updating...';

            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    statusCell.innerHTML = data.status_badge;

                    if (data.stats_html) {
                        updateStatsHtml(data.stats_html);
                    }

                    showToast(data.message || 'Request updated successfully.', 'success');
                } else {
                    showToast(data.message || 'Update failed.', 'error');
                }
            } catch (error) {
                showToast('Network error occurred.', 'error');
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = 'Update';
            }
        });
    });
}

function bindSearchForm() {
    const form = document.getElementById('searchForm');
    const input = document.getElementById('search_nin');
    const searchBtn = document.getElementById('searchBtn');
    const clearBtn = document.getElementById('clearSearchBtn');
    const tableBody = document.getElementById('table-body');
    const searchInfo = document.getElementById('search-info');

    let debounceTimer = null;

    async function runSearch(value = '') {
        const trimmed = value.trim();
        const params = new URLSearchParams();

        if (trimmed !== '') {
            params.set('search_nin', trimmed);
        }

        const url = window.location.pathname + (params.toString() ? '?' + params.toString() : '');

        searchBtn.disabled = true;
        searchBtn.textContent = 'Searching...';

        try {
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            const data = await response.json();

            if (data.success) {
                tableBody.innerHTML = data.tbody_html;
                searchInfo.innerHTML = data.search_info_html || '';
                history.replaceState(null, '', url);
                bindUpdateForms();
            } else {
                showToast('Search failed.', 'error');
            }
        } catch (error) {
            showToast('Network error occurred.', 'error');
        } finally {
            searchBtn.disabled = false;
            searchBtn.textContent = 'Search';
        }
    }

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        runSearch(input.value);
    });

    input.addEventListener('input', function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            runSearch(input.value);
        }, 400);
    });

    clearBtn.addEventListener('click', function() {
        input.value = '';
        runSearch('');
    });
}

bindUpdateForms();
bindSearchForm();
</script>
</body>
</html>
