<?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);
}

/* STATUS LIST */
$allowedStatuses = [
    'Pending',
    'Processing',
    'Successful',
    'Failed'
];

/* 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);
    $stmt->execute();
    $stmt->close();

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

/* REFUND - 80% */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['refund'])) {
    $id = (int)($_POST['id'] ?? 0);

    $q = $conn->prepare("SELECT id, user, price, status, refunded FROM validation_requests WHERE id=? LIMIT 1");
    $q->bind_param("i", $id);
    $q->execute();
    $row = $q->get_result()->fetch_assoc();
    $q->close();

    if ($row && strtolower((string)$row['status']) === 'failed' && (int)$row['refunded'] === 0) {
        $user = (string)$row['user'];
        $price = (float)$row['price'];
        $statusBeforeRefund = (string)$row['status'];
        $refundPercent = 80.00;
        $refundAmount = round($price * 0.80, 2);
        $note = '80% refund for failed validation request';

        $conn->begin_transaction();

        try {
            $bal = $conn->prepare("UPDATE balance SET amount = amount + ? WHERE user = ?");
            $bal->bind_param("ds", $refundAmount, $user);
            $bal->execute();
            $bal->close();

            $upd = $conn->prepare("UPDATE validation_requests SET refunded = 1 WHERE id = ?");
            $upd->bind_param("i", $id);
            $upd->execute();
            $upd->close();

            $ins = $conn->prepare("
                INSERT INTO refund_transactions
                (validation_request_id, user, original_amount, refund_percent, refund_amount, request_status, note)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $ins->bind_param(
                "isdddss",
                $id,
                $user,
                $price,
                $refundPercent,
                $refundAmount,
                $statusBeforeRefund,
                $note
            );
            $ins->execute();
            $ins->close();

            $conn->commit();
        } catch (Throwable $e) {
            $conn->rollback();
        }
    }

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

/* FETCH */
$res = $conn->query("SELECT * FROM validation_requests ORDER BY id DESC");

/* STATS */
$stats = [
    'today' => ['count' => 0, 'spent' => 0],
    'week'  => ['count' => 0, 'spent' => 0],
    'month' => ['count' => 0, 'spent' => 0],
    'total' => ['count' => 0, 'spent' => 0],
];

$statsSql = "
    SELECT
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) AS today_count,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN price ELSE 0 END) AS today_spent,

        SUM(CASE WHEN YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1) THEN 1 ELSE 0 END) AS week_count,
        SUM(CASE WHEN YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1) THEN price ELSE 0 END) AS week_spent,

        SUM(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE()) THEN 1 ELSE 0 END) AS month_count,
        SUM(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE()) THEN price ELSE 0 END) AS month_spent,

        COUNT(*) AS total_count,
        SUM(price) AS total_spent
    FROM validation_requests
";

$statsRes = $conn->query($statsSql);

if ($statsRes instanceof mysqli_result) {
    $s = $statsRes->fetch_assoc();

    if ($s) {
        $stats['today']['count'] = (int)($s['today_count'] ?? 0);
        $stats['today']['spent'] = (float)($s['today_spent'] ?? 0);

        $stats['week']['count'] = (int)($s['week_count'] ?? 0);
        $stats['week']['spent'] = (float)($s['week_spent'] ?? 0);

        $stats['month']['count'] = (int)($s['month_count'] ?? 0);
        $stats['month']['spent'] = (float)($s['month_spent'] ?? 0);

        $stats['total']['count'] = (int)($s['total_count'] ?? 0);
        $stats['total']['spent'] = (float)($s['total_spent'] ?? 0);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Validation Admin</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">
<div class="max-w-7xl mx-auto p-6">

    <h1 class="text-3xl font-bold mb-6">📋 Validation Dashboard</h1>

    <!-- STATS -->
    <div class="grid md:grid-cols-4 gap-4 mb-6">

        <div class="bg-blue-600 p-5 rounded-xl shadow">
            <div class="text-lg font-semibold mb-2">Today</div>
            <div class="text-sm">Today Count: <?= $stats['today']['count'] ?></div>
            <div class="text-sm">Today Spent: ₦<?= naira($stats['today']['spent']) ?></div>
        </div>

        <div class="bg-green-600 p-5 rounded-xl shadow">
            <div class="text-lg font-semibold mb-2">Weekly</div>
            <div class="text-sm">Weekly Count: <?= $stats['week']['count'] ?></div>
            <div class="text-sm">Weekly Spent: ₦<?= naira($stats['week']['spent']) ?></div>
        </div>

        <div class="bg-purple-600 p-5 rounded-xl shadow">
            <div class="text-lg font-semibold mb-2">Monthly</div>
            <div class="text-sm">Monthly Count: <?= $stats['month']['count'] ?></div>
            <div class="text-sm">Monthly Spent: ₦<?= naira($stats['month']['spent']) ?></div>
        </div>

        <div class="bg-orange-600 p-5 rounded-xl shadow">
            <div class="text-lg font-semibold mb-2">Total</div>
            <div class="text-sm">Total Count: <?= $stats['total']['count'] ?></div>
            <div class="text-sm">Total Spent: ₦<?= naira($stats['total']['spent']) ?></div>
        </div>

    </div>

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

            <tbody>
            <?php while($r = $res->fetch_assoc()): ?>
                <tr class="border-b border-gray-700 hover:bg-white/5 transition">
                    <td class="p-3"><?= h($r['user']) ?></td>
                    <td><?= h($r['nin']) ?></td>

                    <td class="text-green-400 font-semibold">
                        ₦<?= naira($r['price']) ?>
                    </td>

                    <td>
                        <?php
                        $s = strtolower((string)$r['status']);

                        if ($s === 'successful') {
                            echo "<span class='px-2 py-1 bg-green-500/20 text-green-400 rounded-full text-xs'>Successful</span>";
                        } elseif ($s === 'failed') {
                            echo "<span class='px-2 py-1 bg-red-500/20 text-red-400 rounded-full text-xs'>Failed</span>";
                        } elseif ($s === 'processing') {
                            echo "<span class='px-2 py-1 bg-blue-500/20 text-blue-400 rounded-full text-xs'>Processing</span>";
                        } else {
                            echo "<span class='px-2 py-1 bg-yellow-500/20 text-yellow-400 rounded-full text-xs'>Pending</span>";
                        }
                        ?>
                    </td>

                    <td>
                        <?php if ((int)$r['refunded'] === 1): ?>
                            <span class="text-green-400 text-xs">Refunded 80%</span>

                        <?php elseif (strtolower((string)$r['status']) === 'failed'): ?>
                            <form method="post" onsubmit="return confirm('Refund 80% for this failed request?');">
                                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                <button name="refund" class="bg-red-500 px-3 py-1 rounded text-xs hover:bg-red-600">
                                    Refund 80%
                                </button>
                            </form>

                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>

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

                            <select name="status" class="w-full p-1 rounded bg-black/30 text-xs">
                                <option value="Pending" <?= strtolower((string)$r['status']) === 'pending' ? 'selected' : '' ?>>Pending</option>
                                <option value="Processing" <?= strtolower((string)$r['status']) === 'processing' ? 'selected' : '' ?>>Processing</option>
                                <option value="Successful" <?= strtolower((string)$r['status']) === 'successful' ? 'selected' : '' ?>>Successful</option>
                                <option value="Failed" <?= strtolower((string)$r['status']) === 'failed' ? 'selected' : '' ?>>Failed</option>
                            </select>

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

                            <button
                                name="update"
                                class="w-full bg-blue-600 hover:bg-blue-700 text-xs p-1 rounded"
                            >
                                Update
                            </button>
                        </form>
                    </td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>

</div>
</body>
</html>
