<?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'] ?? '';
$sess_username = $_SESSION['auth_username'] ?? '';
$sess_password = $_SESSION['auth_password'] ?? '';

$canRead = false;
$canEdit = false;
$canDelete = false;

if ($role === 'admin') {
    $canRead = true;
    $canEdit = true;
    $canDelete = true;
} elseif ($role === 'permission') {
    $stmt = $conn->prepare("SELECT Shop_TopUP_Read, Shop_TopUP_Edit, Shop_TopUP_Delete FROM `Zabbar_Admin_Permission` WHERE username = ? AND password = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("ss", $sess_username, $sess_password);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $canRead = (strtolower(trim($row['Shop_TopUP_Read'] ?? '')) === 'yes' || $row['Shop_TopUP_Read'] == 1);
            $canEdit = (strtolower(trim($row['Shop_TopUP_Edit'] ?? '')) === 'yes' || $row['Shop_TopUP_Edit'] == 1);
            $canDelete = (strtolower(trim($row['Shop_TopUP_Delete'] ?? '')) === 'yes' || $row['Shop_TopUP_Delete'] == 1);
        }
        $stmt->close();
    }
}

if (isset($_GET['api'])) {
    header('Content-Type: application/json');
    
    if (!$canRead) {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
        exit;
    }

    $action = $_GET['api'];

    if ($action === 'fetch') {
        $sql = "SELECT id, title, real_price, discount_price, image_link, stock_message, created_at FROM topup_list ORDER BY id DESC";
        $result = $conn->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        echo json_encode(["status" => "success", "data" => $data]);
        exit;
    }

    if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) {
            echo json_encode(["status" => "error", "message" => "Permission denied to add."]);
            exit;
        }

        $title = trim($_POST['title'] ?? '');
        $real_price = (float)($_POST['real_price'] ?? 0);
        $discount_price = (float)($_POST['discount_price'] ?? 0);
        $image_link = trim($_POST['image_link'] ?? '');
        $stock_message = trim($_POST['stock_message'] ?? '');
        $created_at = date("Y-m-d H:i:s");

        $stmt = $conn->prepare("INSERT INTO topup_list (title, real_price, discount_price, image_link, stock_message, created_at) VALUES (?, ?, ?, ?, ?, ?)");
        if ($stmt) {
            $stmt->bind_param("sddsss", $title, $real_price, $discount_price, $image_link, $stock_message, $created_at);
            if ($stmt->execute()) {
                echo json_encode(["status" => "success"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Failed to add topup item."]);
            }
            $stmt->close();
        } else {
            echo json_encode(["status" => "error", "message" => $conn->error]);
        }
        exit;
    }

    if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) {
            echo json_encode(["status" => "error", "message" => "Edit permission denied."]);
            exit;
        }

        $id = (int)$_POST['id'];
        $title = trim($_POST['title'] ?? '');
        $real_price = (float)($_POST['real_price'] ?? 0);
        $discount_price = (float)($_POST['discount_price'] ?? 0);
        $image_link = trim($_POST['image_link'] ?? '');
        $stock_message = trim($_POST['stock_message'] ?? '');

        $stmt = $conn->prepare("UPDATE topup_list SET title = ?, real_price = ?, discount_price = ?, image_link = ?, stock_message = ? WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("sddssi", $title, $real_price, $discount_price, $image_link, $stock_message, $id);
            if ($stmt->execute()) {
                echo json_encode(["status" => "success"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Failed to update."]);
            }
            $stmt->close();
        } else {
            echo json_encode(["status" => "error", "message" => $conn->error]);
        }
        exit;
    }

    if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canDelete) {
            echo json_encode(["status" => "error", "message" => "Delete permission denied."]);
            exit;
        }
        
        $id = (int)$_POST['id'];
        $stmt = $conn->prepare("DELETE FROM topup_list WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                echo json_encode(["status" => "success"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Failed to delete."]);
            }
            $stmt->close();
        } else {
            echo json_encode(["status" => "error", "message" => $conn->error]);
        }
        exit;
    }
    
    exit;
}

if (!$canRead) {
    die("<!DOCTYPE html><html><head><title>Access Denied</title></head><body style='font-family:system-ui; display:grid; place-items:center; height:100vh; margin:0; background:#f8fafc;'><div style='text-align:center; padding:40px; background:#fff; border-radius:16px; box-shadow:0 10px 15px -3px rgba(0,0,0,0.1);'><h2 style='color:#be123c; margin-top:0;'>Access Denied</h2><p style='color:#334155;'>You do not have permission to view topup items.</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>");
}
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">
    <title>Shop TopUP Management</title>
    <style>
        :root {
            --slate-50: #f8fafc;
            --slate-100: #f1f5f9;
            --slate-200: #e2e8f0;
            --slate-700: #334155;
            --slate-900: #0f172a;
            --primary: #4f46e5;
            --primary-light: #eeebff;
            --emerald-500: #10b981;
            --rose-500: #f43f5e;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px 0 rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.05);
            --radius-md: 12px;
            --radius-lg: 16px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', system-ui, sans-serif; }
        body { background-color: var(--slate-50); color: var(--slate-900); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 280px; background: var(--white); border-right: 1px solid var(--slate-200); display: flex; flex-direction: column; flex-shrink: 0; }
        .sidebar-brand { padding: 24px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--slate-100); }
        .brand-logo { width: 40px; height: 40px; 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; }
        .brand-text h2 { font-size: 16px; font-weight: 700; }
        .brand-text p { font-size: 12px; color: var(--slate-700); }
        .sidebar-menu { padding: 24px 16px; flex-grow: 1; overflow-y: auto; }
        .menu-item { display: flex; align-items: center; gap: 12px; padding: 12px 16px; color: var(--slate-700); text-decoration: none; font-weight: 600; font-size: 14px; border-radius: var(--radius-md); margin-bottom: 8px; }
        .menu-item.active, .menu-item:hover { background: var(--primary-light); color: var(--primary); }
        .menu-item svg { width: 20px; height: 20px; }
        
        .main-content { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; }
        .header { padding: 24px 40px; background: var(--white); border-bottom: 1px solid var(--slate-200); display: flex; justify-content: space-between; align-items: center; }
        .header-title h1 { font-size: 24px; font-weight: 800; }
        .header-actions .btn-primary { padding: 10px 20px; background: var(--primary); color: white; border-radius: 8px; font-weight: 700; cursor: pointer; border: none; font-size: 14px; display: inline-flex; align-items: center; gap: 8px; transition: 0.2s; }
        .header-actions .btn-primary:hover { background: #4338ca; }
        
        .content-body { padding: 40px; overflow-y: auto; flex-grow: 1; }
        
        .table-container { background: var(--white); border-radius: var(--radius-lg); border: 1px solid var(--slate-200); box-shadow: var(--shadow-sm); overflow-x: auto; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; text-align: left; }
        th, td { padding: 16px 24px; border-bottom: 1px solid var(--slate-100); font-size: 14px; }
        th { background: var(--slate-50); font-weight: 700; color: var(--slate-700); white-space: nowrap; }
        td { color: var(--slate-900); vertical-align: middle; font-weight: 500; }
        tr:last-child td { border-bottom: none; }
        tr:hover td { background-color: var(--slate-50); }

        .amount-badge { display: inline-flex; padding: 6px 12px; background: var(--slate-100); border-radius: 6px; font-weight: 700; color: var(--slate-900); gap: 4px; }
        .bonus-badge { display: inline-flex; padding: 6px 12px; background: #ecfdf5; border-radius: 6px; font-weight: 700; color: var(--emerald-500); gap: 4px; }
        .thumb-img { width: 44px; height: 44px; border-radius: 8px; object-fit: cover; border: 1px solid var(--slate-200); background: var(--slate-50); }

        .action-btns { display: flex; gap: 8px; }
        .icon-btn { border: none; background: none; cursor: pointer; border-radius: 8px; padding: 8px; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; }
        .icon-btn svg { width: 18px; height: 18px; }
        .icon-btn.edit { color: var(--primary); background: var(--primary-light); }
        .icon-btn.edit:hover { background: #dce0ff; transform: translateY(-2px); }
        .icon-btn.delete { color: var(--rose-500); background: #fff1f2; }
        .icon-btn.delete:hover { background: #ffe4e6; transform: translateY(-2px); }

        .modal-overlay { position: fixed; inset: 0; background: rgba(15,23,42,0.6); display: none; place-items: center; z-index: 100; backdrop-filter: blur(4px); padding: 20px; overflow-y: auto; }
        .modal { background: var(--white); width: 100%; max-width: 480px; border-radius: var(--radius-lg); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); position: relative; margin: auto; }
        .modal-header { padding: 24px; border-bottom: 1px solid var(--slate-200); display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { font-size: 18px; font-weight: 700; }
        .close-btn { background: none; border: none; cursor: pointer; color: var(--slate-700); }
        .close-btn svg { width: 24px; height: 24px; }
        .modal-body { padding: 24px; }
        
        .form-group { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
        .form-group label { font-size: 13px; font-weight: 700; color: var(--slate-700); }
        .form-control { padding: 12px 14px; border: 1px solid var(--slate-200); border-radius: 8px; font-size: 14px; outline: none; transition: 0.2s; font-family: inherit; width: 100%; }
        .form-control:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-light); }

        .modal-footer { padding: 24px; border-top: 1px solid var(--slate-200); display: flex; justify-content: flex-end; gap: 12px; background: var(--slate-50); border-radius: 0 0 var(--radius-lg) var(--radius-lg); }
        .btn { padding: 10px 20px; border-radius: 8px; font-weight: 700; cursor: pointer; border: none; transition: 0.2s; font-size: 14px; }
        .btn-cancel { background: var(--slate-200); color: var(--slate-700); }
        .btn-cancel:hover { background: var(--slate-300); }
        .btn-submit { background: var(--primary); color: white; }
        .btn-submit:hover { background: #4338ca; }

        .loader { text-align: center; padding: 40px; color: var(--slate-700); font-weight: 600; font-size: 16px; }

        @media (max-width: 1024px) { .sidebar { width: 80px; } .brand-text, .menu-item span { display: none; } }
        @media (max-width: 768px) { body { flex-direction: column; } .sidebar { width: 100%; height: auto; border-right: none; flex-direction: row; align-items: center; padding: 0 20px; } .sidebar-menu { display: flex; gap: 10px; padding: 10px 0; overflow-x: auto; } .menu-item { margin: 0; } .header { padding: 20px; } .content-body { padding: 20px; } }
    </style>
</head>
<body>



<div class="main-content">
    <div class="header">
        <div class="header-title">
            <h1>Shop TopUP List</h1>
        </div>
        <div class="header-actions">
            <?php if ($canEdit): ?>
            <button class="btn-primary" onclick="openModal('add')">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" /></svg>
                Add TopUP Product
            </button>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="content-body">
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Real Price</th>
                        <th>Discount Price</th>
                        <th>Stock Status</th>
                        <th>Created At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="dataTable">
                    <tr><td colspan="8" class="loader">Loading topup products...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal-overlay" id="formModal">
    <div class="modal">
        <div class="modal-header">
            <h3 id="modalTitle">Add TopUP Product</h3>
            <button class="close-btn" onclick="closeModal()">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
            </button>
        </div>
        <div class="modal-body">
            <form id="dataForm">
                <input type="hidden" id="f_id" name="id">
                <div class="form-group">
                    <label>Product Title</label>
                    <input type="text" class="form-control" name="title" id="f_title" placeholder="e.g. 115 Diamonds" required>
                </div>
                <div class="form-group">
                    <label>Real Price (৳)</label>
                    <input type="number" step="0.01" class="form-control" name="real_price" id="f_real_price" placeholder="e.g. 100" required>
                </div>
                <div class="form-group">
                    <label>Discount Price (৳)</label>
                    <input type="number" step="0.01" class="form-control" name="discount_price" id="f_discount_price" placeholder="e.g. 85" required>
                </div>
                <div class="form-group">
                    <label>Image Link</label>
                    <input type="url" class="form-control" name="image_link" id="f_image_link" placeholder="e.g. https://domain.com/image.png" required>
                </div>
                <div class="form-group">
                    <label>Stock Message</label>
                    <input type="text" class="form-control" name="stock_message" id="f_stock_message" placeholder="e.g. In Stock / Instant Delivery" required>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-cancel" onclick="closeModal()">Cancel</button>
            <button type="button" class="btn btn-submit" id="btnSubmit" onclick="saveData()">Save Product</button>
        </div>
    </div>
</div>

<script>
    let currentMode = 'add';
    const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
    const canDelete = <?= $canDelete ? 'true' : 'false' ?>;

    function loadData() {
        const tbody = document.getElementById('dataTable');
        fetch('?api=fetch')
            .then(async res => {
                const text = await res.text();
                try { return JSON.parse(text); } 
                catch (e) { throw new Error("Invalid response"); }
            })
            .then(res => {
                if (res.status === 'success') {
                    renderTable(res.data || []);
                } else {
                    tbody.innerHTML = `<tr><td colspan="8" class="loader" style="color:var(--rose-500)">${res.message}</td></tr>`;
                }
            })
            .catch(err => {
                console.error(err);
                tbody.innerHTML = `<tr><td colspan="8" class="loader" style="color:var(--rose-500)">Failed to load data.</td></tr>`;
            });
    }

    function renderTable(data) {
        const tbody = document.getElementById('dataTable');
        tbody.innerHTML = '';

        if (data.length === 0) {
            tbody.innerHTML = `<tr><td colspan="8" class="loader">No topup items found.</td></tr>`;
            return;
        }

        data.forEach(item => {
            let actionsHtml = '';
            if (canEdit || canDelete) {
                actionsHtml += `<div class="action-btns">`;
                if (canEdit) {
                    actionsHtml += `
                        <button class="icon-btn edit" onclick='openModal("edit", ${JSON.stringify(item).replace(/'/g, "&apos;")})' title="Edit">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10" /></svg>
                        </button>`;
                }
                if (canDelete) {
                    actionsHtml += `
                        <button class="icon-btn delete" onclick="deleteData(${item.id})" title="Delete">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" /></svg>
                        </button>`;
                }
                actionsHtml += `</div>`;
            }

            let tr = document.createElement('tr');
            tr.innerHTML = `
                <td>#${item.id}</td>
                <td><img src="${item.image_link}" class="thumb-img" alt="" onerror="this.src='data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' viewBox=\'0 0 24 24\' stroke=\'%23cbd5e1\' stroke-width=\'2\'><path stroke-linecap=\'round\' stroke-linejoin=\'round\' d=\'M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z\' /></svg>'"></td>
                <td style="font-weight:700; color:var(--slate-900);">${item.title}</td>
                <td><div class="amount-badge">৳ ${item.real_price}</div></td>
                <td><div class="bonus-badge">৳ ${item.discount_price}</div></td>
                <td><span style="font-size:13px; font-weight:600; padding:4px 8px; background-color:var(--slate-100); border-radius:4px; color:var(--slate-700);">${item.stock_message || 'N/A'}</span></td>
                <td style="color:var(--slate-700); font-size:13px;">${item.created_at || 'N/A'}</td>
                <td>${actionsHtml}</td>
            `;
            tbody.appendChild(tr);
        });
    }

    function openModal(mode, data = null) {
        currentMode = mode;
        const form = document.getElementById('dataForm');
        form.reset();

        if (mode === 'edit' && data) {
            document.getElementById('modalTitle').innerText = 'Edit TopUP Product';
            document.getElementById('f_id').value = data.id;
            document.getElementById('f_title').value = data.title || '';
            document.getElementById('f_real_price').value = data.real_price || '';
            document.getElementById('f_discount_price').value = data.discount_price || '';
            document.getElementById('f_image_link').value = data.image_link || '';
            document.getElementById('f_stock_message').value = data.stock_message || '';
        } else {
            document.getElementById('modalTitle').innerText = 'Add TopUP Product';
            document.getElementById('f_id').value = '';
        }
        
        document.getElementById('formModal').style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('formModal').style.display = 'none';
    }

    function saveData() {
        const form = document.getElementById('dataForm');
        if (!form.reportValidity()) return;

        const formData = new FormData(form);
        const btn = document.getElementById('btnSubmit');
        const originalText = btn.innerText;
        
        btn.innerText = 'Saving...';
        btn.disabled = true;

        const apiEndpoint = currentMode === 'add' ? '?api=add' : '?api=update';

        fetch(apiEndpoint, {
            method: 'POST',
            body: formData
        })
        .then(async res => {
            const text = await res.text();
            try { return JSON.parse(text); } 
            catch (e) { throw new Error("Invalid response from server."); }
        })
        .then(res => {
            if (res.status === 'success') {
                closeModal();
                loadData();
            } else {
                alert(res.message || "An error occurred.");
            }
        })
        .catch(err => {
            console.error(err);
            alert("Connection error.");
        })
        .finally(() => {
            btn.innerText = originalText;
            btn.disabled = false;
        });
    }

    function deleteData(id) {
        if (!confirm('Are you sure you want to permanently delete this product?')) return;

        const formData = new FormData();
        formData.append('id', id);

        fetch('?api=delete', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                loadData();
            } else {
                alert(res.message || "Failed to delete.");
            }
        })
        .catch(err => console.error(err));
    }

    window.onload = loadData;
</script>
</body>
</html>