<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Complete Administrative Report</title>
    <script src="https://my-perspolis.com/storage/app/public/3.4.17"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-50 text-gray-800 font-sans min-h-screen flex flex-col justify-center">

<div id="loginOverlay" class="max-w-md mx-auto p-8 bg-white rounded-xl shadow-sm border border-gray-200 w-full mx-4 transition-all duration-300">
    <div class="text-center">
        <h2 class="text-2xl font-bold text-gray-900">Admin Authentication</h2>
        <p class="text-xs text-gray-500 mt-1">Please enter the access key to view performance reports.</p>
    </div>

    <div class="mt-6 space-y-4">
        <div>
            <label for="adminPassword" class="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1">Password</label>
            <input type="password" id="adminPassword" placeholder="••••••••••••"
                   class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:border-blue-500 transition">
            <p id="errorMessage" class="text-xs text-red-500 mt-1 hidden font-medium">Incorrect password. Please try again.</p>
        </div>

        <button id="loginBtn" class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition font-medium text-sm shadow-sm">
            Access Dashboard
        </button>
    </div>
</div>


<div id="mainDashboardContent" class="hidden p-8 max-w-7xl mx-auto space-y-8 w-full animate-fadeIn">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
            <h1 class="text-3xl font-bold text-gray-900">Academy Performance Report</h1>
            <p class="text-gray-500 mt-1">Real-time overview of enrollments, pack allocations, and collected IRT revenue.</p>
        </div>

        <div class="flex items-center gap-3 self-end sm:self-auto">
            <div class="bg-white border border-gray-200 rounded-lg px-3 py-1.5 flex items-center gap-2 shadow-sm">
                <span class="text-xs font-medium text-gray-500 flex items-center gap-1">
                    <svg class="w-3.5 h-3.5 text-blue-500 animate-spin hidden" id="refreshSpinner" 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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                    Refresh:
                </span>
                <select id="autoRefreshSelect" class="text-xs text-gray-700 bg-transparent font-semibold focus:outline-none cursor-pointer">
                    <option value="0">Off</option>
                    <option value="15">Every 15s</option>
                    <option value="30">Every 30s</option>
                    <option value="60">Every 1m</option>
                    <option value="300">Every 5m</option>
                </select>
                <span id="countdownDisplay" class="text-xs font-mono text-gray-400 w-6 text-right hidden"></span>
            </div>

            <button onclick="window.print()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-sm font-medium shadow-sm">
                Export / Print Report
            </button>

            <button id="logoutBtn" title="Lock Dashboard" class="border border-gray-200 text-gray-500 p-2 rounded-lg hover:bg-red-50 hover:text-red-600 hover:border-red-200 transition shadow-sm">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
            </button>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100 border-l-4 border-l-blue-500">
            <div class="text-sm font-medium text-gray-500 uppercase">Total Active Enrollments</div>
            <div class="mt-2 text-3xl font-bold text-gray-900 animate-counter" data-target="{{ $totalActiveEnrollments }}">
                {{ number_format($totalActiveEnrollments) }}
            </div>
            <div class="text-xs text-gray-400 mt-1">Students currently assigned to packs</div>
        </div>

        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100 border-l-4 border-l-emerald-500">
            <div class="text-sm font-medium text-gray-500 uppercase">Total Collected Revenue</div>
            <div class="mt-2 flex items-baseline gap-1">
                <span class="text-3xl font-bold text-emerald-600 animate-counter" data-target="{{ $totalPaid }}">
                    {{ number_format($totalPaid) }}
                </span>
                <span class="text-sm font-bold text-gray-400">IRT</span>
            </div>
            <div class="text-xs text-gray-400 mt-1">Status: Success only</div>
        </div>

        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100 border-l-4 border-l-amber-500">
            <div class="text-sm font-medium text-gray-500 uppercase">Total Discounts Applied</div>
            <div class="mt-2 flex items-baseline gap-1">
                <span class="text-3xl font-bold text-amber-600 animate-counter" data-target="{{ $totalDiscount }}">
                    {{ number_format($totalDiscount) }}
                </span>
                <span class="text-sm font-bold text-gray-400">IRT</span>
            </div>
            <div class="text-xs text-gray-400 mt-1">Platform-wide promotions & gifts</div>
        </div>
    </div>

    <div>
        <h3 class="text-lg font-semibold text-gray-700 mb-4">Revenue by Gateway / Method</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            @foreach(['online' => 'Online Gateway', 'bnpl' => 'Buy Now Pay Later', 'wallet' => 'User Wallet', 'gift_full' => 'Gift Full'] as $key => $label)
                <div class="bg-white p-5 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-xs font-bold text-gray-400 uppercase tracking-wider">{{ $label }}</div>
                    <div class="mt-2 text-xl font-bold text-gray-800">
                        {{ number_format($methodBreakdown[$key]['total'] ?? 0) }} <span class="text-xs text-gray-400">IRT</span>
                    </div>
                    <div class="mt-1 text-xs text-gray-500 font-medium">
                        {{ number_format($methodBreakdown[$key]['count'] ?? 0) }} transactions
                    </div>
                </div>
            @endforeach
        </div>
    </div>

    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
        <h3 class="text-lg font-semibold text-gray-700 mb-4">Day-by-Day Successful Revenue Trend</h3>
        <div class="relative h-80">
            <canvas id="dayByDayChart"></canvas>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="p-6 border-b border-gray-100">
            <h3 class="text-lg font-semibold text-gray-700">Active Students & Allocation Roster</h3>
            <p class="text-xs text-gray-500 mt-1">Displays users mapped to their purchased Packs, exact weekly Schedules, and extra add-on Products.</p>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead>
                <tr class="bg-gray-50 text-gray-500 text-xs font-semibold uppercase tracking-wider border-b border-gray-100">
                    <th class="py-3 px-6">Student Info</th>
                    <th class="py-3 px-6">Assigned Pack</th>
                    <th class="py-3 px-6">Weekly Schedule</th>
                    <th class="py-3 px-6">Extra Products Purchased</th>
                </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 text-sm">
                @forelse($registeredUsers as $student)
                    <tr class="hover:bg-gray-50 transition">
                        <td class="py-4 px-6">
                            <div class="font-bold text-gray-900">{{ $student->student_name }}</div>
                            <div class="text-xs text-gray-500 font-mono">{{ $student->phone }}</div>
                            @if($student->national_id)
                                <div class="text-xs text-gray-400 mt-0.5">ID: {{ $student->national_id }}</div>
                            @endif
                        </td>
                        <td class="py-4 px-6">
                            <span class="inline-block bg-blue-50 text-blue-700 font-semibold px-2.5 py-1 rounded-md text-xs">
                                {{ $student->pack_name }}
                            </span>
                            <div class="text-xs text-gray-500 mt-1 font-medium">
                                Base: {{ number_format($student->pack_price) }} IRT
                            </div>
                        </td>
                        <td class="py-4 px-6 text-xs text-gray-600 leading-relaxed max-w-xs">
                            {{ $student->schedule_details ?: 'No schedule assigned yet' }}
                        </td>
                        <td class="py-4 px-6">
                            @if($student->products->count() > 0)
                                <div class="space-y-1">
                                    @foreach($student->products as $item)
                                        <div class="text-xs bg-gray-100 px-2 py-1 rounded inline-flex items-center gap-2">
                                            <span class="font-medium text-gray-700">{{ $item->name }}</span>
                                            <span class="text-gray-400 font-mono">({{ number_format($item->price) }} IRT)</span>
                                        </div>
                                    @endforeach
                                </div>
                            @else
                                <span class="text-xs text-gray-400 italic">None</span>
                            @endif
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="4" class="text-center py-8 text-gray-400 italic">
                            No active student registrations found matching your filter criteria.
                        </td>
                    </tr>
                @endforelse
                </tbody>
            </table>
        </div>
    </div>

</div>

<style>
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .animate-fadeIn {
        animation: fadeIn 0.4s ease-out forwards;
    }
    /* Hide layout when printing so only the report shows */
    @media print {
        #loginOverlay { display: none !important; }
        #mainDashboardContent { display: block !important; }
        body { background-color: white !important; }
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {

        // --- AUTHENTICATION LOGIC ---
        const passKey = "perspolis2026";
        const authStorageKey = "dashboard_access_granted";

        const loginOverlay = document.getElementById('loginOverlay');
        const mainDashboardContent = document.getElementById('mainDashboardContent');
        const adminPasswordInput = document.getElementById('adminPassword');
        const errorMessage = document.getElementById('errorMessage');
        const loginBtn = document.getElementById('loginBtn');
        const logoutBtn = document.getElementById('logoutBtn');

        // Check if unlocked already
        if (localStorage.getItem(authStorageKey) === "true") {
            unlockDashboard();
        }

        function unlockDashboard() {
            loginOverlay.classList.add('hidden');
            mainDashboardContent.classList.remove('hidden');
            document.body.classList.remove('justify-center'); // Resets centering for main UI
            initDashboardComponents(); // Starts charts and auto-refresh only after logging in
        }

        function handleLogin() {
            if (adminPasswordInput.value === passKey) {
                localStorage.setItem(authStorageKey, "true");
                errorMessage.classList.add('hidden');
                unlockDashboard();
            } else {
                errorMessage.classList.remove('hidden');
                adminPasswordInput.value = "";
                adminPasswordInput.focus();
            }
        }

        loginBtn.addEventListener('click', handleLogin);
        adminPasswordInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') handleLogin();
        });

        // Allow user to manually lock the screen
        logoutBtn.addEventListener('click', function() {
            localStorage.removeItem(authStorageKey);
            window.location.reload();
        });


        // --- INITIALIZE DASHBOARD ONLY WHEN AUTHENTICATED ---
        function initDashboardComponents() {

            // --- Auto Refresh Logic ---
            const refreshSelect = document.getElementById('autoRefreshSelect');
            const countdownDisplay = document.getElementById('countdownDisplay');
            const refreshSpinner = document.getElementById('refreshSpinner');

            let refreshIntervalId = null;
            let countdownIntervalId = null;

            const savedInterval = localStorage.getItem('dashboard_auto_refresh') || '0';
            refreshSelect.value = savedInterval;

            function startRefreshTimer(seconds) {
                clearInterval(refreshIntervalId);
                clearInterval(countdownIntervalId);
                refreshSpinner.classList.add('hidden');
                countdownDisplay.classList.add('hidden');

                if (seconds <= 0) return;

                let timeLeft = seconds;
                countdownDisplay.classList.remove('hidden');
                refreshSpinner.classList.remove('hidden');
                countdownDisplay.innerText = `${timeLeft}s`;

                countdownIntervalId = setInterval(() => {
                    timeLeft--;
                    countdownDisplay.innerText = `${timeLeft}s`;
                    if (timeLeft <= 0) {
                        countdownDisplay.innerText = '...';
                    }
                }, 1000);

                refreshIntervalId = setTimeout(() => {
                    window.location.reload();
                }, seconds * 1000);
            }

            refreshSelect.addEventListener('change', function() {
                const val = parseInt(this.value);
                localStorage.setItem('dashboard_auto_refresh', val);
                startRefreshTimer(val);
            });

            startRefreshTimer(parseInt(savedInterval));


            // --- Smooth Animated Number Counters ---
            const counters = document.querySelectorAll('.animate-counter');
            const speed = 40;

            counters.forEach(counter => {
                const target = +counter.getAttribute('data-target');
                const increment = target / speed;

                const updateCount = () => {
                    const current = +counter.innerText.replace(/,/g, '');

                    if (current < target) {
                        const nextVal = Math.ceil(current + increment);
                        counter.innerText = (nextVal > target ? target : nextVal).toLocaleString();
                        setTimeout(updateCount, 25);
                    } else {
                        counter.innerText = target.toLocaleString();
                    }
                };

                if (target > 0) {
                    counter.innerText = '0';
                    updateCount();
                }
            });


            // --- Interactive Day-by-Day Chart Generation ---
            const ctx = document.getElementById('dayByDayChart').getContext('2d');
            const chartDates = @json($dayByDayDates);
            const chartRevenues = @json($dayByDayRevenue);

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: chartDates,
                    datasets: [{
                        label: 'Daily Revenue (IRT)',
                        data: chartRevenues,
                        borderColor: 'rgb(59, 130, 246)',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.3,
                        pointBackgroundColor: 'rgb(37, 99, 235)',
                        pointRadius: 4,
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let val = context.raw || 0;
                                    return ' Revenue: ' + val.toLocaleString() + ' IRT';
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return value.toLocaleString() + ' IRT';
                                }
                            },
                            grid: { color: 'rgba(243, 244, 246, 1)' }
                        },
                        x: {
                            grid: { display: false }
                        }
                    }
                }
            });

        }

    });
</script>
</body>
</html>
