<?php
require_once "config.php";
session_start();

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die(json_encode(["status" => "error", "message" => "Database connection error."]));
}

$conn->set_charset("utf8mb4");

function session_alive(int $timeout): bool {
    if (empty($_SESSION['auth_logged_in']) || empty($_SESSION['auth_last_activity'])) {
        return false;
    }
    if ((time() - (int)$_SESSION['auth_last_activity']) > $timeout) {
        $_SESSION = [];
        session_destroy();
        return false;
    }
    $_SESSION['auth_last_activity'] = time();
    return true;
}

if (!session_alive(1200)) {
    if (isset($_GET['api'])) {
        die(json_encode(["status" => "unauthorized"]));
    }
    header("Location: admin_login.php");
    exit;
}

$role = $_SESSION['auth_role'] ?? '';

if ($role !== 'admin') {
    if (isset($_GET['api'])) {
        die(json_encode(["status" => "error", "message" => "Only admin can access ShuvoPays."]));
    }
    die("<!DOCTYPE html><html><head><title>Access Denied</title><meta name='viewport' content='width=device-width, initial-scale=1.0'></head><body style='font-family:system-ui; display:grid; place-items:center; min-height:100vh; margin:0; background:#f8fafc; padding:20px;'><div style='text-align:center; padding:32px; background:#fff; border-radius:16px; box-shadow:0 10px 15px -3px rgba(0,0,0,0.1); max-width:420px; width:100%;'><h2 style='color:#be123c; margin-top:0;'>Access Denied</h2><p style='color:#334155;'>Only admin can manage ShuvoPays.</p><a href='index.php' style='display:inline-block; margin-top:16px; padding:10px 20px; background:#4f46e5; color:#fff; text-decoration:none; border-radius:8px; font-weight:600;'>Return Dashboard</a></div></body></html>");
    exit;
}

function json_out(array $data): void {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data);
    exit;
}

if (isset($_GET['api'])) {
    $action = is_string($_GET['api']) ? $_GET['api'] : '';

    if ($action === 'fetch') {
        $limit = 50;
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $offset = ($page - 1) * $limit;
        
        // --- Filters ---
        $gatewayFilter = isset($_GET['gateway']) ? $_GET['gateway'] : 'all';
        $searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';

        $whereClause = "WHERE 1=1";
        $params = [];
        $types = "";

        if ($gatewayFilter !== 'all') {
            $whereClause .= " AND Gateway = ?";
            $params[] = $gatewayFilter;
            $types .= "s";
        }

        if (!empty($searchQuery)) {
            $whereClause .= " AND (trnxid LIKE ? OR sender LIKE ?)";
            $searchParam = "%{$searchQuery}%";
            $params[] = $searchParam;
            $params[] = $searchParam;
            $types .= "ss";
        }
        // --------------

        // Count Query
        $countSql = "SELECT COUNT(id) AS total FROM ShuvoPays " . $whereClause;
        $countStmt = $conn->prepare($countSql);
        if ($types) {
            $countStmt->bind_param($types, ...$params);
        }
        $countStmt->execute();
        $totalRows = (int)($countStmt->get_result()->fetch_assoc()['total'] ?? 0);
        $totalPages = max(1, (int)ceil($totalRows / $limit));
        $countStmt->close();

        // Main Query
        $sql = "SELECT id, `from`, sender, amount, trnxid, Gateway, Method, status, created_at FROM ShuvoPays $whereClause ORDER BY id DESC LIMIT ? OFFSET ?";
        $stmt = $conn->prepare($sql);
        
        $fetchTypes = $types . "ii";
        $fetchParams = array_merge($params, [$limit, $offset]);
        
        $stmt->bind_param($fetchTypes, ...$fetchParams);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        $stmt->close();
        
        json_out(["status" => "success", "data" => $data, "totalPages" => $totalPages, "currentPage" => $page]);
    }

    if ($action === 'get' && isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $stmt = $conn->prepare("SELECT id, `from`, sender, amount, trnxid, Gateway, Method, status FROM ShuvoPays WHERE id = ?");
        if (!$stmt) json_out(["status" => "error", "message" => "Failed to prepare query."]);
        
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        if ($row) {
            json_out(["status" => "success", "data" => $row]);
        }
        json_out(["status" => "error", "message" => "Record not found."]);
    }

    if (($action === 'create' || $action === 'update') && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $Gateway = trim($_POST['Gateway'] ?? '');
        $amount = trim($_POST['amount'] ?? '');
        $trnxid = trim($_POST['trnxid'] ?? '');
        $sender = trim($_POST['sender'] ?? '');
        $method = "Add Money";
        $status = "0";
        $from = $Gateway;

        if ($Gateway === '') json_out(["status" => "error", "message" => "Gateway is required."]);
        if ($amount === '') json_out(["status" => "error", "message" => "Amount is required."]);
        if ($trnxid === '') json_out(["status" => "error", "message" => "TRX ID is required."]);
        if ($sender === '') json_out(["status" => "error", "message" => "Sender number is required."]);

        $created_at = date("Y-m-d h:i A");

        if ($action === 'create') {
            $stmt = $conn->prepare("INSERT INTO ShuvoPays (`from`, sender, amount, trnxid, Gateway, Method, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            if (!$stmt) json_out(["status" => "error", "message" => "Failed to prepare insert query."]);
            $stmt->bind_param("ssssssss", $from, $sender, $amount, $trnxid, $Gateway, $method, $status, $created_at);
            if ($stmt->execute()) { $stmt->close(); json_out(["status" => "success", "message" => "Record created successfully."]); }
            $error = $stmt->error; $stmt->close();
            json_out(["status" => "error", "message" => $error ?: "Failed to create record."]);
        }

        if ($id <= 0) json_out(["status" => "error", "message" => "Invalid ID for update."]);
        $stmt = $conn->prepare("UPDATE ShuvoPays SET `from`=?, sender=?, amount=?, trnxid=?, Gateway=?, Method=?, status=? WHERE id=?");
        if (!$stmt) json_out(["status" => "error", "message" => "Failed to prepare update query."]);
        $stmt->bind_param("sssssssi", $from, $sender, $amount, $trnxid, $Gateway, $method, $status, $id);
        if ($stmt->execute()) { $stmt->close(); json_out(["status" => "success", "message" => "Record updated successfully."]); }
        $error = $stmt->error; $stmt->close();
        json_out(["status" => "error", "message" => $error ?: "Failed to update record."]);
    }

    if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) json_out(["status" => "error", "message" => "Invalid ID."]);
        $stmt = $conn->prepare("DELETE FROM ShuvoPays WHERE id = ?");
        if (!$stmt) json_out(["status" => "error", "message" => "Failed to prepare delete query."]);
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) { $stmt->close(); json_out(["status" => "success", "message" => "Record deleted successfully."]); }
        $error = $stmt->error; $stmt->close();
        json_out(["status" => "error", "message" => $error ?: "Failed to delete record."]);
    }

    if ($action === 'delete_all_success' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $sql = "DELETE FROM ShuvoPays WHERE status='1'";
        if ($conn->query($sql)) {
            json_out(["status" => "success", "message" => "All success records deleted successfully."]);
        } else {
            json_out(["status" => "error", "message" => "Failed to delete all success records."]);
        }
    }

    json_out(["status" => "error", "message" => "Invalid API action."]);
}

function generateRandomSender(): string {
    $prefixes = ['017', '018', '013'];
    $prefix = $prefixes[array_rand($prefixes)];
    $suffix = '';
    for ($i = 0; $i < 8; $i++) {
        $suffix .= mt_rand(0, 9);
    }
    return $prefix . $suffix;
}
require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>ShuvoPays Management</title>
    <style>
        :root { --slate-50: #f8fafc; --slate-100: #f1f5f9; --slate-200: #e2e8f0; --slate-300: #cbd5e1; --slate-400: #94a3b8; --slate-500: #64748b; --slate-600: #475569; --slate-700: #334155; --slate-800: #1e293b; --slate-900: #0f172a; --primary: #4f46e5; --primary-light: #eeebff; --emerald-500: #10b981; --rose-500: #f43f5e; --white: #fff; --shadow-sm: 0 1px 2px rgba(0,0,0,0.05); --radius-md: 12px; --radius-lg: 18px; }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', system-ui, sans-serif; }
        html, body { height: 100%; }
        body { background: var(--slate-50); color: var(--slate-900); display: flex; min-height: 100vh; overflow: hidden; -webkit-overflow-scrolling: touch; }
        .sidebar { width: 280px; background: var(--white); border-right: 1px solid var(--slate-200); display: flex; flex-direction: column; flex-shrink: 0; z-index: 10; }
        .sidebar-brand { padding: 24px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--slate-100); }
        .brand-logo { width: 42px; height: 42px; background: linear-gradient(135deg, var(--primary), #818cf8); border-radius: var(--radius-md); display: grid; place-items: center; color: var(--white); font-weight: 800; font-size: 20px; flex-shrink: 0; }
        .brand-text h2 { font-size: 16px; font-weight: 700; color: var(--slate-800); }
        .brand-text p { font-size: 12px; color: var(--slate-500); margin-top: 2px; }
        .sidebar-menu { padding: 18px 16px; flex-grow: 1; overflow-y: auto; }
        .menu-item { display: flex; align-items: center; gap: 12px; padding: 12px 14px; color: var(--slate-600); text-decoration: none; font-weight: 600; font-size: 14px; border-radius: 10px; margin-bottom: 8px; transition: 0.2s ease; }
        .menu-item.active, .menu-item:hover { background: var(--primary-light); color: var(--primary); }
        .main-content { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; min-width: 0; }
        .header { padding: 20px 28px; background: var(--white); border-bottom: 1px solid var(--slate-200); display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
        .header h1 { font-size: 22px; font-weight: 800; color: var(--slate-800); letter-spacing: -0.4px; }
        .header-actions { display: flex; gap: 10px; flex-wrap: wrap; }
        .btn-add { background: var(--primary); color: white; border: none; padding: 10px 16px; border-radius: 10px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; box-shadow: var(--shadow-sm); }
        .btn-danger { background: var(--rose-500); color: white; border: none; padding: 10px 16px; border-radius: 10px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; box-shadow: var(--shadow-sm); }
        
        /* Filter & Search Bar */
        .controls-bar { display: flex; justify-content: space-between; align-items: center; padding: 20px 28px 0 28px; gap: 16px; flex-wrap: wrap; }
        .tabs { display: flex; gap: 10px; overflow-x: auto; scrollbar-width: none; padding-bottom: 4px; }
        .tabs::-webkit-scrollbar { display: none; }
        .tab-btn { background: var(--white); border: 1px solid var(--slate-200); padding: 8px 16px; font-size: 13px; font-weight: 700; color: var(--slate-600); cursor: pointer; border-radius: 10px; transition: 0.2s; box-shadow: var(--shadow-sm); white-space: nowrap; }
        .tab-btn.active { background: var(--primary-light); color: var(--primary); border-color: var(--primary-light); }
        .tab-btn:hover:not(.active) { background: var(--slate-50); }
        .search-box { position: relative; width: 300px; flex-shrink: 0; }
        .search-box input { width: 100%; padding: 10px 14px 10px 38px; border: 1px solid var(--slate-300); border-radius: 10px; font-size: 14px; outline: none; transition: 0.2s; }
        .search-box input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.12); }
        .search-icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: var(--slate-400); width: 18px; height: 18px; pointer-events: none; }

        .content-body { padding: 20px 28px 28px; overflow: hidden; flex-grow: 1; display: flex; flex-direction: column; min-height: 0; }
        .table-container { background: var(--white); border: 1px solid var(--slate-200); border-radius: var(--radius-lg); box-shadow: var(--shadow-sm); display: flex; flex-direction: column; flex-grow: 1; overflow: hidden; min-height: 0; }
        .table-scroll { flex-grow: 1; overflow-y: auto; min-height: 0; -webkit-overflow-scrolling: touch; }
        table { width: 100%; border-collapse: collapse; text-align: left; }
        thead th { background: var(--slate-50); font-weight: 700; color: var(--slate-600); text-transform: uppercase; font-size: 11px; letter-spacing: 0.8px; padding: 15px 14px; position: sticky; top: 0; z-index: 2; border-bottom: 1px solid var(--slate-200); }
        td { padding: 14px; border-bottom: 1px solid var(--slate-100); font-size: 13px; vertical-align: middle; }
        tbody tr:hover { background: #fafafa; }
        .badge { display: inline-block; padding: 5px 10px; border-radius: 9999px; font-size: 11px; font-weight: 800; line-height: 1; }
        .badge-success { background: #ecfdf5; color: #059669; }
        .badge-failed { background: #fff1f2; color: #e11d48; }
        .action-btns { display: flex; gap: 6px; flex-wrap: wrap; }
        .btn-icon { border: none; background: none; cursor: pointer; padding: 8px; border-radius: 8px; transition: 0.2s; }
        .btn-edit:hover { background: #e0e7ff; color: var(--primary); }
        .btn-delete:hover { background: #ffe4e6; color: var(--rose-500); }
        .pagination-container { padding: 14px 18px; display: flex; justify-content: space-between; align-items: center; gap: 12px; border-top: 1px solid var(--slate-200); background: var(--white); flex-wrap: wrap; }
        .page-btn { padding: 8px 14px; border: 1px solid var(--slate-200); background: var(--white); border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: 700; }
        .page-btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .modal { display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.45); z-index: 1000; justify-content: center; align-items: center; padding: 16px; }
        .modal.active { display: flex; }
        .modal-content { background: white; border-radius: var(--radius-lg); padding: 24px; width: 100%; max-width: 480px; max-height: 92vh; overflow-y: auto; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); -webkit-overflow-scrolling: touch; }
        .modal-header { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 20px; }
        .modal-header h2 { font-size: 20px; }
        .form-group { margin-bottom: 14px; }
        .form-group label { display: block; font-weight: 700; margin-bottom: 6px; font-size: 13px; color: var(--slate-700); }
        .form-group input, .form-group select { width: 100%; padding: 11px 12px; border: 1px solid var(--slate-300); border-radius: 10px; font-size: 14px; outline: none; background: #fff; }
        .form-group input:focus, .form-group select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.12); }
        .form-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
        .btn { padding: 10px 18px; border: none; border-radius: 10px; font-weight: 700; cursor: pointer; }
        .btn-primary { background: var(--primary); color: white; }
        .btn-secondary { background: var(--slate-200); color: var(--slate-700); }
        .toast-container { position: fixed; bottom: 18px; right: 18px; z-index: 2000; display: flex; flex-direction: column; gap: 10px; max-width: calc(100vw - 36px); }
        .toast { padding: 14px 18px; border-radius: 12px; color: #fff; font-size: 14px; font-weight: 600; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
        .toast.success { background: #10b981; }
        .toast.error { background: #f43f5e; }
        .mobile-list { display: none; }
        .txn-card { background: #fff; border: 1px solid var(--slate-200); border-radius: 18px; padding: 14px; box-shadow: var(--shadow-sm); margin-bottom: 12px; }
        .txn-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 10px; }
        .txn-id { font-size: 14px; font-weight: 800; color: var(--slate-800); }
        .txn-meta { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; }
        .txn-field { background: var(--slate-50); border: 1px solid var(--slate-200); border-radius: 12px; padding: 10px; min-width: 0; }
        .txn-label { font-size: 11px; color: var(--slate-500); text-transform: uppercase; font-weight: 700; margin-bottom: 4px; }
        .txn-value { font-size: 13px; font-weight: 700; color: var(--slate-800); word-break: break-word; }
        .txn-actions { display: flex; gap: 8px; margin-top: 12px; }
        .txn-actions .btn-icon { flex: 1; justify-content: center; display: inline-flex; padding: 12px; border: 1px solid var(--slate-200); background: #fff; }
        .warning-modal { text-align: center; }
        .warning-icon { width: 48px; height: 48px; background: #fef3c7; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; color: #d97706; margin-bottom: 16px; }
        
        @media (max-width: 1024px) { .sidebar { width: 84px; } .brand-text, .menu-item span { display: none; } .sidebar-brand { justify-content: center; } .sidebar-menu { padding-inline: 10px; } .menu-item { justify-content: center; } .header, .content-body, .controls-bar { padding-left: 18px; padding-right: 18px; } }
        @media (max-width: 768px) { body { flex-direction: column; overflow: auto; height: auto; min-height: 100dvh; } .sidebar { width: 100%; border-right: none; border-bottom: 1px solid var(--slate-200); flex-direction: row; align-items: center; overflow-x: auto; } .sidebar-brand { border-bottom: none; padding: 14px 16px; flex-shrink: 0; } .sidebar-menu { display: flex; gap: 8px; padding: 12px 12px 12px 0; overflow-x: auto; white-space: nowrap; flex-grow: 1; } .menu-item { margin-bottom: 0; padding: 10px 12px; flex-shrink: 0; border: 1px solid transparent; } .main-content { overflow: visible; height: auto; } .header { padding: 14px 16px; align-items: flex-start; } .header h1 { font-size: 18px; } .header-actions { width: 100%; flex-direction: column; } .btn-add, .btn-danger { width: 100%; justify-content: center; } .controls-bar { flex-direction: column; padding: 14px 16px 0 16px; align-items: stretch;} .search-box { width: 100%; } .content-body { padding: 14px 16px 18px; overflow: visible; height: auto; } .table-container { overflow: visible; height: auto; } .table-scroll { display: none; overflow: visible; } .mobile-list { display: block; overflow: visible; } .pagination-container { flex-direction: column; align-items: stretch; } .pagination-container > span, .pagination-container > div { width: 100%; text-align: center; } #pageBtns { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; } .modal-content { padding: 18px; max-height: 94vh; } .txn-meta { grid-template-columns: 1fr; } .toast-container { left: 12px; right: 12px; max-width: none; } }
    </style>
</head>
<body>
<div class="sidebar">
    <div class="sidebar-brand">
        <div class="brand-logo">Z</div>
        <div class="brand-text"><h2> Engine</h2><p>Management System</p></div>
    </div>
    <div class="sidebar-menu">
        <a href="index.php" class="menu-item">Dashboard</a>
        <a href="UserInfo.php" class="menu-item">User Info</a>
        <a href="gift_requests.php" class="menu-item">Gift Requests</a>
        <a href="shop_topup.php" class="menu-item">Shop TopUP</a>
        <a href="product_orders.php" class="menu-item">Product Orders</a>
        <a href="#" class="menu-item active">ShuvoPays</a>
    </div>
</div>

<div class="main-content">
    <div class="header">
        <h1>ShuvoPays Transactions</h1>
        <div class="header-actions">
            <button class="btn-danger" onclick="deleteAllSuccess()">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                Delete All Success
            </button>
            <button class="btn-add" onclick="openModal()">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 4.5v15m7.5-7.5h-15"/></svg>
                Add New
            </button>
        </div>
    </div>

    <!-- Filters & Search -->
    <div class="controls-bar">
        <div class="tabs">
            <button class="tab-btn active" onclick="setGateway('all', this)">All</button>
            <button class="tab-btn" onclick="setGateway('bKash', this)">bKash</button>
            <button class="tab-btn" onclick="setGateway('Nagad', this)">Nagad</button>
            <button class="tab-btn" onclick="setGateway('rocket', this)">Rocket</button>
            <button class="tab-btn" onclick="setGateway('upay', this)">Upay</button>
        </div>
        <div class="search-box">
            <svg class="search-icon" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
            <input type="text" id="searchInput" placeholder="Search by TRX ID or Sender..." onkeyup="handleSearch(event)">
        </div>
    </div>

    <div class="content-body">
        <div class="table-container">
            <div class="table-scroll" id="desktopTableWrap">
                <table id="dataTable">
                    <thead><tr><th>ID</th><th>Gateway</th><th>Amount</th><th>TRX</th><th>Sender</th><th>Status</th><th>Created</th><th>Actions</th></tr></thead>
                    <tbody id="dataBody"></tbody>
                </table>
            </div>
            <div class="mobile-list" id="mobileList"></div>
            <div class="pagination-container" id="pagination" style="display:none;"><span id="pageInfo"></span><div id="pageBtns"></div></div>
        </div>
    </div>
</div>

<div class="modal" id="modal">
    <div class="modal-content">
        <div class="modal-header"><h2 id="modalTitle">Add New Record</h2><button onclick="closeModal()" style="background:none;border:none;font-size:28px;cursor:pointer;line-height:1;">&times;</button></div>
        <form id="recordForm">
            <input type="hidden" id="recordId" name="id"><input type="hidden" name="Method" value="Add Money"><input type="hidden" name="status" value="0">
            <div class="form-group"><label>Gateway *</label><select name="Gateway" required><option value="">Select Gateway</option><option value="bKash">bKash</option><option value="Nagad">Nagad</option><option value="rocket">rocket</option><option value="upay">upay</option></select></div>
            <div class="form-group"><label>Amount *</label><input name="amount" type="number" step="any" placeholder="e.g. 1000" required></div>
            <div class="form-group"><label>Transaction ID (TRX) *</label><input name="trnxid" placeholder="TRX ID" required></div>
            <div class="form-group"><label>Sender Number *</label><input name="sender" id="senderInput" placeholder="01XXXXXXXXX" maxlength="11" required></div>
            <div class="form-actions"><button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button><button type="submit" class="btn btn-primary">Save</button></div>
        </form>
    </div>
</div>

<div class="modal" id="warningModal">
    <div class="modal-content warning-modal">
        <div class="warning-icon"><svg width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/></svg></div>
        <h3 style="margin-bottom:12px;color:var(--slate-800);">Delete All Success Records?</h3>
        <p style="color:var(--slate-500);margin-bottom:24px;font-size:14px;">This will permanently delete all records with status "Success". This action cannot be undone.</p>
        <div class="form-actions" style="justify-content:center;"><button class="btn btn-secondary" onclick="closeWarningModal()">Cancel</button><button class="btn btn-danger" onclick="confirmDeleteAll()">Delete All</button></div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
    let currentPage = 1;
    let currentGateway = 'all';
    let currentSearch = '';
    let searchTimeout = null;
    
    const modal = document.getElementById('modal');
    const warningModal = document.getElementById('warningModal');
    const form = document.getElementById('recordForm');

    function showToast(msg, type='success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.textContent = msg;
        container.appendChild(toast);
        setTimeout(() => toast.remove(), 3000);
    }

    function esc(v) { return String(v ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;'); }

    // --- Search & Filter Logic ---
    function setGateway(gw, btn) {
        currentGateway = gw;
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        loadData(1);
    }

    function handleSearch(e) {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentSearch = e.target.value.trim();
            loadData(1);
        }, 300); // 300ms debounce
    }
    // ----------------------------

    function loadData(page = 1) {
        currentPage = page;
        const url = `?api=fetch&page=${page}&gateway=${currentGateway}&search=${encodeURIComponent(currentSearch)}&t=${Date.now()}`;
        
        fetch(url).then(res => res.json()).then(res => {
            if (res.status === 'success') { 
                renderTable(res.data); 
                renderMobileList(res.data); 
                renderPagination(res.totalPages, res.currentPage); 
            } else {
                showToast(res.message || 'Failed to load data', 'error');
            }
        }).catch(() => showToast('Connection error.', 'error'));
    }

    function renderTable(data) {
        const tbody = document.getElementById('dataBody');
        if (!data || data.length === 0) { tbody.innerHTML = `<tr><td colspan="8" style="text-align:center;padding:40px;color:var(--slate-500);font-weight:600;">No records found.</td></tr>`; return; }
        tbody.innerHTML = data.map(item => {
            const isSuccess = String(item.status) === '1';
            return `<tr><td>${esc(item.id)}</td><td><span style="font-weight:700;color:var(--slate-700);">${esc(item.Gateway || '-')}</span></td><td>৳ <span style="font-weight:800;">${esc(item.amount || '0')}</span></td><td style="font-family:monospace;color:var(--slate-600);">${esc(item.trnxid || '-')}</td><td>${esc(item.sender || '-')}</td><td><span class="badge ${isSuccess ? 'badge-success' : 'badge-failed'}">${isSuccess ? 'Success' : 'Failed'}</span></td><td style="color:var(--slate-500);font-size:12px;">${esc(item.created_at || '-')}</td><td><div class="action-btns"><button class="btn-icon btn-edit" onclick="editRecord(${item.id})" title="Edit"><svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg></button><button class="btn-icon btn-delete" onclick="deleteRecord(${item.id})" title="Delete"><svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg></button></div></td></tr>`;
        }).join('');
    }

    function renderMobileList(data) {
        const wrap = document.getElementById('mobileList');
        if (!data || data.length === 0) { wrap.innerHTML = `<div class="txn-card" style="text-align:center;color:var(--slate-500);padding:26px 14px;font-weight:600;">No records found.</div>`; return; }
        wrap.innerHTML = data.map(item => {
            const isSuccess = String(item.status) === '1';
            return `<div class="txn-card"><div class="txn-top"><div><div class="txn-id">#${esc(item.id)} · ${esc(item.Gateway || '-')}</div><div style="font-size:12px;color:var(--slate-500);margin-top:4px;">${esc(item.created_at || '-')}</div></div><span class="badge ${isSuccess ? 'badge-success' : 'badge-failed'}">${isSuccess ? 'Success' : 'Failed'}</span></div><div class="txn-meta"><div class="txn-field"><div class="txn-label">Amount</div><div class="txn-value">৳ ${esc(item.amount || '0')}</div></div><div class="txn-field"><div class="txn-label">TRX</div><div class="txn-value" style="font-family:monospace;">${esc(item.trnxid || '-')}</div></div><div class="txn-field"><div class="txn-label">Sender</div><div class="txn-value">${esc(item.sender || '-')}</div></div></div><div class="txn-actions"><button class="btn-icon btn-edit" onclick="editRecord(${item.id})">Edit</button><button class="btn-icon btn-delete" onclick="deleteRecord(${item.id})">Delete</button></div></div>`;
        }).join('');
    }

    function renderPagination(totalPages, current) {
        const pag = document.getElementById('pagination');
        if (totalPages <= 1) { pag.style.display = 'none'; return; }
        pag.style.display = 'flex';
        document.getElementById('pageInfo').textContent = `Page ${current} of ${totalPages}`;
        document.getElementById('pageBtns').innerHTML = `<button class="page-btn" onclick="loadData(${current - 1})" ${current <= 1 ? 'disabled' : ''}>Previous</button><button class="page-btn" onclick="loadData(${current + 1})" ${current >= totalPages ? 'disabled' : ''}>Next</button>`;
    }

    function openModal(id = null) {
        form.reset();
        document.getElementById('recordId').value = '';
        document.getElementById('modalTitle').textContent = 'Add New Record';
        if (!id) document.getElementById('senderInput').value = '<?php echo generateRandomSender(); ?>';
        modal.classList.add('active');
        if (id) {
            fetch(`?api=get&id=${id}`).then(r => r.json()).then(res => {
                if (res.status === 'success') {
                    document.getElementById('recordId').value = res.data.id;
                    document.getElementById('modalTitle').textContent = 'Edit Record';
                    for (const field in res.data) { if (form.elements[field]) form.elements[field].value = res.data[field]; }
                } else showToast(res.message || 'Record not found', 'error');
            }).catch(() => showToast('Failed to open record.', 'error'));
        }
    }

    function closeModal() { modal.classList.remove('active'); }
    function closeWarningModal() { warningModal.classList.remove('active'); }

    function deleteAllSuccess() { warningModal.classList.add('active'); }

    function confirmDeleteAll() {
        closeWarningModal();
        fetch('?api=delete_all_success', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
            .then(r => r.json()).then(res => {
                showToast(res.message || 'Done', res.status === 'success' ? 'success' : 'error');
                if (res.status === 'success') loadData(1);
            }).catch(() => showToast('Connection error.', 'error'));
    }

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        const id = document.getElementById('recordId').value;
        const url = id ? '?api=update' : '?api=create';
        fetch(url, { method: 'POST', body: new FormData(form) }).then(r => r.json()).then(res => {
            showToast(res.message || 'Done', res.status === 'success' ? 'success' : 'error');
            if (res.status === 'success') { closeModal(); loadData(currentPage); }
        }).catch(() => showToast('Connection error.', 'error'));
    });

    function editRecord(id) { openModal(id); }

    function deleteRecord(id) {
        if (!confirm('Are you sure?')) return;
        fetch('?api=delete', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'id=' + encodeURIComponent(id) })
            .then(r => r.json()).then(res => {
                showToast(res.message || 'Done', res.status === 'success' ? 'success' : 'error');
                if (res.status === 'success') loadData(currentPage);
            }).catch(() => showToast('Connection error.', 'error'));
    }

    window.addEventListener('load', () => loadData(1));
</script>
</body>
</html>