<?php

require_once __DIR__ . '/config.php';

require_admin_login();

// --- API ENDPOINT FOR CHECKING NEW REQUESTS (AJAX) ---
if (isset($_GET['check_new_requests'])) {
    header('Content-Type: application/json');
    try {
        $stmt = $pdo->query("SELECT MAX(id) as max_id FROM recharges");
        $result = $stmt->fetch();
        echo json_encode(['max_id' => (int)$result['max_id']]);
    } catch (Exception $e) {
        echo json_encode(['max_id' => 0]);
    }
    exit;
}

// Handle POST actions
if (is_post()) {
    verify_csrf();

    // --- UPDATE STATUS LOGIC ---
    if (isset($_POST['update_status'])) {
        $rid = (int)($_POST['rid'] ?? 0);
        $status = $_POST['status'] ?? 'pending';

        if ($status === 'completed') $status = 'approved';
        if ($status === 'cancelled') $status = 'rejected';

        if ($status === 'approved') {
            try {
                $pdo->beginTransaction();

                $stmt = $pdo->prepare("SELECT user_id, amount, status, txn_id FROM recharges WHERE id = ?");
                $stmt->execute([$rid]);
                $recharge = $stmt->fetch();

                if ($recharge && $recharge['status'] === 'pending') {
                    $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM recharges WHERE txn_id = ? AND status = 'approved' AND id != ?");
                    $stmtCheck->execute([$recharge['txn_id'], $rid]);
                    $exists = $stmtCheck->fetchColumn();

                    if ($exists > 0) {
                        $pdo->rollBack();
                        $stmt = $pdo->prepare("UPDATE recharges SET status = 'rejected' WHERE id = ?");
                        $stmt->execute([$rid]);
                        set_flash("Duplicate Transaction ID! Request rejected automatically.", "danger");
                    } else {
                        $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                        $stmt->execute([$recharge['amount'], $recharge['user_id']]);

                        $stmt = $pdo->prepare("UPDATE recharges SET status = 'approved' WHERE id = ?");
                        $stmt->execute([$rid]);

                        $pdo->commit();
                        set_flash("Recharge #" . h($rid) . " approved successfully.", "success");
                    }
                } else {
                    $pdo->rollBack();
                    set_flash("Already processed or invalid request.", "warning");
                }
            } catch (Exception $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                set_flash("Database error: " . $e->getMessage(), "danger");
            }
        } else {
            $stmt = $pdo->prepare("UPDATE recharges SET status = ? WHERE id = ?");
            $stmt->execute([$status, $rid]);
            set_flash("Recharge #" . h($rid) . " status updated to " . h($status) . ".", "success");
        }
        redirect('recharges.php');
    }
}

// --- SEARCH & FETCH LOGIC ---
$search = trim($_GET['search'] ?? '');
$params = [];
$where_clause = "";

if ($search !== '') {
    $where_clause = " WHERE u.email LIKE ? ";
    $params[] = "%$search%";
}

$sql = "SELECT r.*, u.email 
        FROM recharges r 
        JOIN users u ON u.id = r.user_id 
        $where_clause
        ORDER BY r.status = 'pending' DESC, r.id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$recharges_all = $stmt->fetchAll();

$total_approved_amount = 0;
if ($search !== '') {
    $sql_sum = "SELECT SUM(r.amount) as total FROM recharges r JOIN users u ON u.id = r.user_id WHERE u.email LIKE ? AND r.status = 'approved'";
    $stmt_sum = $pdo->prepare($sql_sum);
    $stmt_sum->execute(["%$search%"]);
    $total_approved_amount = $stmt_sum->fetchColumn() ?? 0;
}

require_once 'header.php';
?>

<style>
    :root {
        --brand-color: #230133;
        --brand-hover: #3b0354;
    }
    .text-brand { color: var(--brand-color) !important; }
    .bg-brand { background-color: var(--brand-color) !important; color: white; }
    
    .btn-brand {
        background-color: var(--brand-color);
        color: white;
        border: none;
        transition: 0.3s;
    }
    .btn-brand:hover {
        background-color: var(--brand-hover);
        color: white;
    }

    .card-header-brand {
        background-color: white;
        border-bottom: 2px solid var(--brand-color);
    }

    .table thead th {
        background-color: var(--brand-color);
        color: white;
        border: none;
    }

    .border-left-brand {
        border-left: 0.25rem solid var(--brand-color) !important;
    }

    .badge-pending { background-color: #ffc107; color: #000; }
    .badge-approved { background-color: #198754; color: #fff; }
    .badge-rejected { background-color: #dc3545; color: #fff; }
</style>

<div class="d-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-brand fw-bold">Recharge Management</h1>
</div>

<?php show_flash(); ?>

<div class="row mb-4">
    <div class="col-md-6">
        <form method="get" class="d-flex">
            <input type="text" name="search" class="form-control me-2 border-brand" placeholder="Search by User Email..." value="<?php echo h($search); ?>">
            <button type="submit" class="btn btn-brand">Search</button>
            <?php if ($search !== ''): ?>
                <a href="recharges.php" class="btn btn-secondary ms-2">Reset</a>
            <?php endif; ?>
        </form>
    </div>
    
    <?php if ($search !== ''): ?>
    <div class="col-md-6 mt-3 mt-md-0">
        <div class="card border-left-brand shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-brand text-uppercase mb-1">Total Approved (Search)</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">৳ <?php echo number_format($total_approved_amount, 2); ?></div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-cash-coin fs-2 text-brand opacity-25"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<div class="card shadow-sm mb-4">
    <div class="card-header card-header-brand py-3">
        <h6 class="m-0 fw-bold text-brand"><i class="bi bi-credit-card-fill me-2"></i>Recent Recharge Requests</h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User Email</th>
                        <th>Amount</th>
                        <th>TXN ID</th>
                        <th>Date</th>
                        <th>Status</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($recharges_all)): ?>
                        <tr><td colspan="7" class="text-center text-muted p-4">No recharges found.</td></tr>
                    <?php else: foreach ($recharges_all as $r): ?>
                        <tr>
                            <td>#<?php echo $r['id']; ?></td>
                            <td class="fw-bold"><?php echo h($r['email']); ?></td>
                            <td class="text-brand fw-bold">৳ <?php echo number_format($r['amount'], 2); ?></td>
                            <td><code class="text-dark"><?php echo h($r['txn_id']); ?></code></td>
                            <td class="small"><?php echo date("d M, Y h:i A", strtotime($r['created_at'])); ?></td>
                            <td>
                                <?php
                                $status = strtolower($r['status']);
                                $cls = "badge-{$status}";
                                echo "<span class='badge {$cls}'>" . h(ucfirst($status)) . "</span>";
                                ?>
                            </td>
                            <td class="text-center">
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-brand dropdown-toggle" type="button" data-bs-toggle="dropdown" <?php if($r['status'] !== 'pending') echo 'disabled'; ?>>
                                        Manage
                                    </button>
                                    <ul class="dropdown-menu shadow">
                                        <li>
                                            <form method="post">
                                                <?php csrf_field(); ?>
                                                <input type="hidden" name="rid" value="<?php echo $r['id']; ?>">
                                                <input type="hidden" name="status" value="approved">
                                                <button type="submit" name="update_status" class="dropdown-item text-success fw-bold"><i class="bi bi-check2-circle me-2"></i>Approve</button>
                                            </form>
                                        </li>
                                        <li>
                                            <form method="post">
                                                <?php csrf_field(); ?>
                                                <input type="hidden" name="rid" value="<?php echo $r['id']; ?>">
                                                <input type="hidden" name="status" value="rejected">
                                                <button type="submit" name="update_status" class="dropdown-item text-danger fw-bold"><i class="bi bi-x-circle me-2"></i>Reject</button>
                                            </form>
                                        </li>
                                    </ul>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if ("Notification" in window) {
        if (Notification.permission !== "granted" && Notification.permission !== "denied") {
            Notification.requestPermission();
        }
    }

    let lastKnownId = <?php 
        $stmtMax = $pdo->query("SELECT MAX(id) FROM recharges");
        echo (int)$stmtMax->fetchColumn(); 
    ?>;

    setInterval(function() {
        fetch(window.location.pathname + '?check_new_requests=1')
            .then(response => response.json())
            .then(data => {
                if (data.max_id > lastKnownId) {
                    lastKnownId = data.max_id;
                    if (Notification.permission === "granted") {
                        let n = new Notification("নতুন রিচার্জ রিকোয়েস্ট!", {
                            body: "প্যানেলে নতুন পেমেন্ট এসেছে, চেক করুন।",
                            icon: "https://cdn-icons-png.flaticon.com/512/1077/1077114.png"
                        });
                        n.onclick = () => { window.focus(); location.reload(); };
                    }
                }
            });
    }, 5000); 
});
</script>

<?php require_once 'footer.php'; ?>