<?php
/**
 * Stripe Payments Dashboard — Admin (with Summary Stats)
 */

ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../../error.log');
error_reporting(E_ALL);

session_start();

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

// Stripe Library - Your specified path
require_once __DIR__ . '/../author/lib/stripe-php/init.php';

// Set Stripe API Key
\Stripe\Stripe::setApiKey('sk_test_51MUPOkSDX9TVziH564g36z2EmlJ6plKjGrHu0P8Ve9Brv4cjnHyQOPUDHBR2iNYHpUa8NVhYzRDCqNbp32JKUGGz006wKK475m');

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stripe Payments — Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <style>
        body { font-family:'Roboto',sans-serif; }
        .sidebar { width:250px; background:#2d3748; color:white; }
        .content { margin-left:250px; }
        .stat-card {
            transition: transform 0.2s;
        }
        .stat-card:hover {
            transform: translateY(-4px);
        }
        .sbadge { 
            display:inline-flex; align-items:center; gap:5px; 
            padding:4px 12px; border-radius:9999px; font-size:12px; font-weight:600; 
        }
        .sb-succeeded { background:rgba(16,185,129,.15); color:#059669; }
        .sb-failed    { background:rgba(239,68,68,.15); color:#dc2626; }
        .sb-pending   { background:rgba(245,158,11,.15); color:#d97706; }
        
        table { border-collapse: collapse; }
        th, td { padding: 14px 16px; }
        tr:hover { background-color: #f8fafc; }
        body.dark tr:hover { background-color: #374151; }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900">

<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content p-6" id="content">

    <!-- Topbar -->
    <div class="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4 mt-5 flex items-center justify-between sticky top-0 z-10 shadow-sm rounded-xl mb-6">
        <div class="flex items-center gap-3">
            <h1 class="text-2xl font-semibold text-gray-800 dark:text-white flex items-center gap-3">
                <i class="fas fa-credit-card text-blue-600"></i>
                Stripe Payments Overview
            </h1>
        </div>
        <button onclick="window.location.reload()" 
                class="flex items-center gap-2 px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition">
            <i class="fas fa-sync-alt"></i> Refresh
        </button>
    </div>

    <?php
    $totalReceived = 0;      // Successful amount (in smallest unit)
    $totalRefunded = 0;
    $completedCount = 0;
    $totalInitiated = 0;
    $chargesData = [];

    try {
        $charges = \Stripe\Charge::all([
            'limit' => 100,   // Increase if needed (max 100 per request)
        ]);

        foreach ($charges->data as $charge) {
            $totalInitiated++;

            if ($charge->status === 'succeeded') {
                $completedCount++;
                $totalReceived += $charge->amount;
            }

            if ($charge->amount_refunded > 0) {
                $totalRefunded += $charge->amount_refunded;
            }

            $chargesData[] = $charge;   // Store for table below
        }

        $currency = !empty($chargesData) ? strtoupper($chargesData[0]->currency) : 'USD';
        $formattedTotal = number_format($totalReceived / 100, 2);
        $formattedRefunded = number_format($totalRefunded / 100, 2);
        $successRate = $totalInitiated > 0 ? round(($completedCount / $totalInitiated) * 100, 1) : 0;

    } catch (\Stripe\Exception\ApiErrorException $e) {
        echo '<div class="p-6 bg-red-50 border border-red-200 text-red-700 rounded-xl mb-6">'.
             '<strong>Stripe Error:</strong> ' . htmlspecialchars($e->getMessage()) . '</div>';
        $chargesData = [];
    } catch (Exception $e) {
        echo '<div class="p-6 bg-red-50 border border-red-200 text-red-700 rounded-xl mb-6">'.
             '<strong>Error:</strong> ' . htmlspecialchars($e->getMessage()) . '</div>';
        $chargesData = [];
    }
    ?>

    <!-- Summary Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
        <div class="stat-card bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">Total Received</p>
                    <p class="text-3xl font-bold text-emerald-600 dark:text-emerald-400 mt-2">
                        <?= $formattedTotal ?> <span class="text-lg"><?= $currency ?></span>
                    </p>
                </div>
                <i class="fas fa-hand-holding-dollar text-4xl text-emerald-500 opacity-80"></i>
            </div>
            <p class="text-xs text-gray-400 mt-4">From successful payments</p>
        </div>

        <div class="stat-card bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">Completed Payments</p>
                    <p class="text-3xl font-bold text-gray-800 dark:text-white mt-2"><?= $completedCount ?></p>
                </div>
                <i class="fas fa-check-circle text-4xl text-emerald-500 opacity-80"></i>
            </div>
            <p class="text-xs text-gray-400 mt-4">Succeeded charges</p>
        </div>

        <div class="stat-card bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">Initiated Payments</p>
                    <p class="text-3xl font-bold text-gray-800 dark:text-white mt-2"><?= $totalInitiated ?></p>
                </div>
                <i class="fas fa-play-circle text-4xl text-blue-500 opacity-80"></i>
            </div>
            <p class="text-xs text-gray-400 mt-4">Total charges created</p>
        </div>

        <div class="stat-card bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">Refunded Amount</p>
                    <p class="text-3xl font-bold text-red-600 dark:text-red-400 mt-2">
                        <?= $formattedRefunded ?> <span class="text-lg"><?= $currency ?></span>
                    </p>
                </div>
                <i class="fas fa-undo text-4xl text-red-500 opacity-80"></i>
            </div>
            <p class="text-xs text-gray-400 mt-4">Total amount refunded</p>
        </div>

        <div class="stat-card bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">Success Rate</p>
                    <p class="text-3xl font-bold text-gray-800 dark:text-white mt-2"><?= $successRate ?>%</p>
                </div>
                <i class="fas fa-chart-line text-4xl text-violet-500 opacity-80"></i>
            </div>
            <p class="text-xs text-gray-400 mt-4">Completed vs Initiated</p>
        </div>
    </div>

    <!-- Payments Table -->
    <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b dark:border-gray-700 flex justify-between items-center">
            <h2 class="font-semibold text-lg">Recent Payments</h2>
            <?php if (!empty($chargesData) && count($chargesData) >= 100): ?>
                <p class="text-sm text-gray-500">Showing last 100 charges</p>
            <?php endif; ?>
        </div>

        <?php if (empty($chargesData)): ?>
            <div class="p-12 text-center text-gray-500 dark:text-gray-400">
                <i class="fas fa-receipt text-5xl mb-4 opacity-50"></i>
                <p class="text-lg">No payments found.</p>
            </div>
        <?php else: ?>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-50 dark:bg-gray-700">
                        <tr>
                            <th class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Charge ID</th>
                            <th class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Date</th>
                            <th class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Amount</th>
                            <th class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Status</th>
                            <th class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Customer</th>
                            <th class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Description</th>
                            <th class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Card</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700 text-sm">
                        <?php foreach ($chargesData as $charge): 
                            $amount = number_format($charge->amount / 100, 2);
                            $statusClass = $charge->status === 'succeeded' ? 'sb-succeeded' : 
                                          ($charge->status === 'failed' ? 'sb-failed' : 'sb-pending');
                        ?>
                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700 transition">
                                <td class="font-mono text-blue-600 dark:text-blue-400"><?= htmlspecialchars($charge->id) ?></td>
                                <td class="text-gray-600 dark:text-gray-300"><?= date('d M Y • H:i', $charge->created) ?></td>
                                <td class="font-semibold">
                                    <?= $amount ?> <span class="text-xs uppercase"><?= strtoupper($charge->currency) ?></span>
                                </td>
                                <td>
                                    <span class="sbadge <?= $statusClass ?>">
                                        <?= strtoupper(htmlspecialchars($charge->status)) ?>
                                    </span>
                                </td>
                                <td class="text-gray-600 dark:text-gray-300">
                                    <?= $charge->customer ? htmlspecialchars($charge->customer) : '—' ?>
                                </td>
                                <td class="text-gray-600 dark:text-gray-300 max-w-xs truncate">
                                    <?= $charge->description ? htmlspecialchars($charge->description) : '—' ?>
                                </td>
                                <td class="text-gray-600 dark:text-gray-300">
                                    <?php if (isset($charge->payment_method_details->card)): ?>
                                        •••• <?= htmlspecialchars($charge->payment_method_details->card->last4 ?? '') ?>
                                        (<?= htmlspecialchars($charge->payment_method_details->card->brand ?? '') ?>)
                                    <?php else: ?>
                                        —
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <div class="mt-6 text-xs text-gray-400 text-center">
        Note: Showing up to 100 recent charges • Net received = Total Received - Refunded
    </div>
</div>

</body>
</html>