<?php
require_once "config.php";


session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'httponly' => true
]);
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_Product_Read, Shop_Product_Edit, Shop_Product_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_Product_Read'] ?? '')) === 'yes' || $row['Shop_Product_Read'] == 1);
            $canEdit = (strtolower(trim($row['Shop_Product_Edit'] ?? '')) === 'yes' || $row['Shop_Product_Edit'] == 1);
            $canDelete = (strtolower(trim($row['Shop_Product_Delete'] ?? '')) === 'yes' || $row['Shop_Product_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') {
        $limit = 10;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        if ($page < 1) $page = 1;
        $offset = ($page - 1) * $limit;

        $countQuery = $conn->query("SELECT COUNT(id) as total FROM products");
        $totalRows = $countQuery->fetch_assoc()['total'];
        $totalPages = ceil($totalRows / $limit);

        $sql = "SELECT * FROM products ORDER BY id DESC LIMIT ? OFFSET ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $limit, $offset);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        $stmt->close();
        
        echo json_encode([
            "status" => "success", 
            "data" => $data, 
            "totalPages" => $totalPages, 
            "currentPage" => $page
        ]);
        exit;
    }

    if ($action === 'fetch_images') {
        $product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        $sql = "SELECT * FROM product_images WHERE product_id = ? ORDER BY id DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $product_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        $stmt->close();
        
        echo json_encode(["status" => "success", "data" => $data]);
        exit;
    }

    if ($action === 'process' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $type = strtolower(trim($_POST['type'] ?? ''));
        
        if (in_array($type, ['add', 'edit', 'add_image']) && !$canEdit) {
            echo json_encode(["status" => "error", "message" => "Edit/Add permission denied."]);
            exit;
        }
        
        if (in_array($type, ['delete', 'delete_image']) && !$canDelete) {
            echo json_encode(["status" => "error", "message" => "Delete permission denied."]);
            exit;
        }

        try {
            if ($type === 'add' || $type === 'edit') {
                $id = (int)($_POST['id'] ?? 0);
                $title = trim($_POST['title'] ?? '');
                $amount = (float)($_POST['amount'] ?? 0);
                $discount = (float)($_POST['discount'] ?? 0);
                $description = trim($_POST['description'] ?? '');
                $stock = (int)($_POST['stock'] ?? 0);
                $sold = (int)($_POST['sold'] ?? 0);
                $image_link = trim($_POST['image_link'] ?? '');
                $DeliveryFree = trim($_POST['DeliveryFree'] ?? '');
                $home_delivery = trim($_POST['home_delivery'] ?? 'No');

                if ($title === '') throw new Exception("Title cannot be empty.");

                if ($type === 'add') {
                    $stmt = $conn->prepare("INSERT INTO products (title, amount, discount, description, stock, sold, image_link, DeliveryFree, home_delivery) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("sddsiisss", $title, $amount, $discount, $description, $stock, $sold, $image_link, $DeliveryFree, $home_delivery);
                    if (!$stmt->execute()) throw new Exception("Failed to add product.");
                    $stmt->close();
                    $msg = "Product added successfully.";
                } else {
                    $stmt = $conn->prepare("UPDATE products SET title=?, amount=?, discount=?, description=?, stock=?, sold=?, image_link=?, DeliveryFree=?, home_delivery=? WHERE id=?");
                    $stmt->bind_param("sddsiisssi", $title, $amount, $discount, $description, $stock, $sold, $image_link, $DeliveryFree, $home_delivery, $id);
                    if (!$stmt->execute()) throw new Exception("Failed to update product.");
                    $stmt->close();
                    $msg = "Product updated successfully.";
                }
                echo json_encode(["status" => "success", "message" => $msg]);

            } elseif ($type === 'delete') {
                $id = (int)($_POST['id'] ?? 0);
                $conn->begin_transaction();
                try {
                    $stmt = $conn->prepare("DELETE FROM product_images WHERE product_id = ?");
                    $stmt->bind_param("i", $id);
                    $stmt->execute();
                    $stmt->close();

                    $stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
                    $stmt->bind_param("i", $id);
                    if (!$stmt->execute()) throw new Exception("Failed to delete product.");
                    $stmt->close();

                    $conn->commit();
                    echo json_encode(["status" => "success", "message" => "Product and associated images deleted."]);
                } catch (Exception $e) {
                    $conn->rollback();
                    throw $e;
                }

            } elseif ($type === 'add_image') {
                $product_id = (int)($_POST['product_id'] ?? 0);
                $image_link = trim($_POST['image_link'] ?? '');
                if ($product_id === 0 || $image_link === '') throw new Exception("Invalid input.");

                $stmt = $conn->prepare("INSERT INTO product_images (product_id, image_link) VALUES (?, ?)");
                $stmt->bind_param("is", $product_id, $image_link);
                if (!$stmt->execute()) throw new Exception("Failed to add image.");
                $stmt->close();
                echo json_encode(["status" => "success", "message" => "Image added successfully."]);

            } elseif ($type === 'delete_image') {
                $image_id = (int)($_POST['image_id'] ?? 0);
                $stmt = $conn->prepare("DELETE FROM product_images WHERE id = ?");
                $stmt->bind_param("i", $image_id);
                if (!$stmt->execute()) throw new Exception("Failed to delete image.");
                $stmt->close();
                echo json_encode(["status" => "success", "message" => "Image deleted successfully."]);

            } else {
                throw new Exception("Invalid action type.");
            }
        } catch (Exception $e) {
            echo json_encode(["status" => "error", "message" => $e->getMessage()]);
        }
        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 this page.</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-300: #cbd5e1;
            --slate-500: #64748b; --slate-700: #334155; --slate-900: #0f172a;
            --primary: #4f46e5; --primary-light: #eeebff; --primary-hover: #4338ca;
            --emerald-500: #10b981; --emerald-600: #059669;
            --rose-500: #f43f5e; --rose-600: #e11d48;
            --blue-500: #3b82f6; --blue-600: #2563eb;
            --amber-500: #f59e0b; --amber-600: #d97706;
            --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; z-index: 10; }
        .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; transition: all 0.2s; }
        .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; color: var(--slate-900); }
        
        .btn-primary { background: var(--primary); color: var(--white); padding: 10px 20px; border-radius: 8px; font-weight: 600; font-size: 14px; border: none; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: 0.2s; }
        .btn-primary:hover { background: var(--primary-hover); }

        .content-body { padding: 40px; overflow-y: auto; flex-grow: 1; }
        
        .table-container { background: var(--white); border: 1px solid var(--slate-200); border-radius: var(--radius-lg); box-shadow: var(--shadow-sm); overflow-x: auto; display: flex; flex-direction: column;}
        table { width: 100%; border-collapse: collapse; text-align: left; }
        th, td { padding: 16px 20px; border-bottom: 1px solid var(--slate-100); font-size: 14px; vertical-align: top; }
        th { background: var(--slate-50); font-weight: 600; color: var(--slate-700); text-transform: uppercase; font-size: 12px; letter-spacing: 0.5px; }
        tbody tr:hover { background: var(--slate-50); }
        
        .product-img { width: 48px; height: 48px; border-radius: 8px; object-fit: cover; background: var(--slate-100); border: 1px solid var(--slate-200); flex-shrink: 0; }
        .prod-info { display: flex; gap: 12px; }
        .prod-title { font-weight: 700; color: var(--slate-900); font-size: 14px; margin-bottom: 4px; }
        .prod-desc { font-size: 12px; color: var(--slate-500); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }

        .stat-block { font-size: 13px; color: var(--slate-700); }
        .stat-block strong { color: var(--slate-900); }

        .action-btns { display: flex; gap: 8px; justify-content: flex-end; }
        .btn-action { border: none; background: none; cursor: pointer; border-radius: 8px; padding: 8px; transition: 0.2s; display: inline-flex; align-items: center; justify-content: center; color: var(--white); }
        .btn-action svg { width: 16px; height: 16px; }
        .btn-action:disabled { opacity: 0.5; cursor: not-allowed; }
        .btn-action.view-btn { background: var(--blue-500); }
        .btn-action.view-btn:hover:not(:disabled) { background: var(--blue-600); transform: translateY(-2px); }
        .btn-action.edit-btn { background: var(--amber-500); }
        .btn-action.edit-btn:hover:not(:disabled) { background: var(--amber-600); transform: translateY(-2px); }
        .btn-action.delete-btn { background: var(--slate-700); }
        .btn-action.delete-btn:hover:not(:disabled) { background: var(--slate-900); transform: translateY(-2px); }

        .pagination-container { padding: 20px; display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--slate-100); background: var(--white); border-bottom-left-radius: var(--radius-lg); border-bottom-right-radius: var(--radius-lg); }
        .pagination-info { font-size: 13px; color: var(--slate-500); }
        .pagination-controls { display: flex; gap: 6px; }
        .page-btn { padding: 6px 12px; border: 1px solid var(--slate-200); background: var(--white); color: var(--slate-700); border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; transition: 0.2s; }
        .page-btn:hover:not(:disabled) { background: var(--slate-50); border-color: var(--slate-300); }
        .page-btn.active { background: var(--primary); color: var(--white); border-color: var(--primary); }
        .page-btn:disabled { opacity: 0.5; cursor: not-allowed; }

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

        .toast-container { position: fixed; bottom: 24px; right: 24px; z-index: 1000; display: flex; flex-direction: column; gap: 10px; }
        .toast { padding: 14px 20px; border-radius: 10px; color: #fff; font-size: 14px; font-weight: 600; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); animation: slideIn 0.3s ease forwards; display: flex; align-items: center; gap: 10px; }
        .toast.success { background: var(--emerald-500); }
        .toast.error { background: var(--rose-500); }
        @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }

        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.6); display: none; place-items: center; z-index: 100; backdrop-filter: blur(4px); }
        .modal { background: var(--white); width: 90%; max-width: 650px; border-radius: var(--radius-lg); box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); overflow: hidden; position: relative; }
        
        .modal-scrollview { max-height: 85vh; overflow-y: auto; -webkit-overflow-scrolling: touch; }
        .modal-scrollview::-webkit-scrollbar { width: 6px; }
        .modal-scrollview::-webkit-scrollbar-track { background: var(--slate-50); }
        .modal-scrollview::-webkit-scrollbar-thumb { background: var(--slate-300); border-radius: 10px; }

        .modal-header { padding: 20px 24px; border-bottom: 1px solid var(--slate-200); display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; background: var(--white); z-index: 10; }
        .modal-header h3 { font-size: 18px; font-weight: 700; color: var(--slate-900); }
        .modal-close { background: none; border: none; color: var(--slate-500); cursor: pointer; transition: 0.2s; padding: 6px; border-radius: 6px; }
        .modal-close:hover { background: var(--slate-100); color: var(--rose-500); }
        
        .modal-body { padding: 24px; }
        
        .form-group { margin-bottom: 16px; }
        .form-group label { display: block; font-size: 13px; font-weight: 600; color: var(--slate-700); margin-bottom: 6px; }
        .form-control { width: 100%; padding: 10px 14px; border: 1px solid var(--slate-300); border-radius: 8px; font-size: 14px; color: var(--slate-900); outline: none; transition: border-color 0.2s; }
        .form-control:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-light); }
        select.form-control { appearance: none; background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e"); background-repeat: no-repeat; background-position: right 12px center; background-size: 16px; padding-right: 40px; }
        textarea.form-control { resize: vertical; min-height: 80px; }
        .form-row { display: flex; gap: 16px; }
        .form-row .form-group { flex: 1; }

        .modal-footer { padding: 20px 24px; background: var(--slate-50); border-top: 1px solid var(--slate-200); display: flex; justify-content: flex-end; gap: 12px; }
        .btn-secondary { background: var(--white); color: var(--slate-700); padding: 12px 24px; border-radius: 8px; font-weight: 600; font-size: 14px; border: 1px solid var(--slate-300); cursor: pointer; transition: all 0.2s; }
        .btn-secondary:hover { background: var(--slate-100); color: var(--slate-900); }
        .btn-save { background: linear-gradient(135deg, var(--primary), var(--blue-600)); color: var(--white); padding: 12px 24px; border-radius: 8px; font-weight: 600; font-size: 14px; border: none; cursor: pointer; transition: all 0.2s; box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3); }
        .btn-save:hover:not(:disabled) { background: linear-gradient(135deg, var(--primary-hover), var(--blue-600)); transform: translateY(-1px); box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4); }
        .btn-save:disabled { opacity: 0.6; cursor: not-allowed; box-shadow: none; }

        .image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 16px; margin-top: 20px; }
        .image-item { border: 1px solid var(--slate-200); border-radius: 8px; overflow: hidden; background: var(--slate-50); position: relative; }
        .image-item img { width: 100%; height: 120px; object-fit: cover; display: block; }
        .image-item .img-overlay { position: absolute; top:0; left:0; right:0; padding: 6px; display: flex; justify-content: flex-end; background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent); }
        .image-item .img-delete { background: var(--rose-500); color: white; border: none; width: 24px; height: 24px; border-radius: 4px; cursor: pointer; display: grid; place-items: center; }
        .image-item .img-delete:hover { background: var(--rose-600); }
        .no-images { text-align: center; color: var(--slate-500); padding: 40px; font-weight: 600; font-size: 14px; border: 1px dashed var(--slate-300); border-radius: 8px; margin-top: 20px; }
        .add-img-box { display: flex; gap: 10px; margin-bottom: 20px; background: var(--slate-50); padding: 16px; border-radius: 8px; border: 1px solid var(--slate-200); }
        .add-img-box input { flex: 1; }

        @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; flex-wrap: wrap; gap: 10px; } .content-body { padding: 20px; } .form-row { flex-direction: column; gap: 0; } }
        @media (max-width: 480px) { 
            .modal-footer { flex-direction: column; gap: 12px; }
            .btn-secondary { order: 2; width: 100%; }
            .btn-save { order: 1; width: 100%; }
            .add-img-box { flex-direction: column; }
        }
    </style>
</head>
<body>


<div class="main-content">
    <div class="header">
        <div class="header-title">
            <h1>Shop TopUP Products</h1>
        </div>
        <?php if ($canEdit): ?>
        <button class="btn-primary" onclick="openProductModal('add')">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:20px;height:20px;"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" /></svg>
            Add New Product
        </button>
        <?php endif; ?>
    </div>
    
    <div class="content-body">
        <div class="table-container" id="dataTableWrap">
            <div class="loader" id="loader">Loading products...</div>
            <table id="dataTable" style="display: none;">
                <thead>
                    <tr>
                        <th>ID & Product</th>
                        <th>Pricing & Delivery</th>
                        <th>Stock & Sold</th>
                        <th>Created At</th>
                        <th style="text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody id="dataBody"></tbody>
            </table>
            
            <div class="pagination-container" id="paginationControls" style="display: none;">
                <div class="pagination-info" id="pageInfo">Showing Page 1</div>
                <div class="pagination-controls" id="pageBtns"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal-overlay" id="productModalOverlay">
    <div class="modal">
        <div class="modal-scrollview">
            <div class="modal-header">
                <h3 id="modalTitle">Add Product</h3>
                <button class="modal-close" type="button" onclick="closeProductModal()">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:24px;height:24px;"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
                </button>
            </div>
            <form id="productForm" onsubmit="saveProduct(event)">
                <div class="modal-body">
                    <input type="hidden" id="p_id" name="id" value="0">
                    <input type="hidden" id="p_type" name="type" value="add">
                    
                    <div class="form-group">
                        <label>Product Title</label>
                        <input type="text" id="p_title" name="title" class="form-control" required placeholder="Enter product title">
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Amount (Regular Price)</label>
                            <input type="number" step="0.01" id="p_amount" name="amount" class="form-control" value="0">
                        </div>
                        <div class="form-group">
                            <label>Discount</label>
                            <input type="number" step="0.01" id="p_discount" name="discount" class="form-control" value="0">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Stock</label>
                            <input type="number" id="p_stock" name="stock" class="form-control" value="0">
                        </div>
                        <div class="form-group">
                            <label>Sold</label>
                            <input type="number" id="p_sold" name="sold" class="form-control" value="0">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Delivery Charge</label>
                            <input type="text" id="p_DeliveryFree" name="DeliveryFree" class="form-control" placeholder="e.g. 50TK, Free">
                        </div>
                        <div class="form-group">
                            <label>Home Delivery</label>
                            <select id="p_home_delivery" name="home_delivery" class="form-control">
                                <option value="No">No</option>
                                <option value="Yes">Yes</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Main Image Link</label>
                        <input type="url" id="p_image_link" name="image_link" class="form-control" placeholder="https://...">
                    </div>

                    <div class="form-group" style="margin-bottom:0;">
                        <label>Description</label>
                        <textarea id="p_description" name="description" class="form-control" placeholder="Enter product details..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-secondary" onclick="closeProductModal()">Cancel</button>
                    <button type="submit" class="btn-save" id="saveBtn">Save Product</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal-overlay" id="imageModalOverlay">
    <div class="modal">
        <div class="modal-scrollview">
            <div class="modal-header">
                <h3>Product Images</h3>
                <button class="modal-close" type="button" onclick="closeImageModal()">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:24px;height:24px;"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
                </button>
            </div>
            <div class="modal-body">
                <?php if ($canEdit): ?>
                <div class="add-img-box">
                    <input type="hidden" id="img_product_id" value="0">
                    <input type="url" id="new_image_link" class="form-control" placeholder="New image URL...">
                    <button class="btn-save" onclick="addImage()">Add Image</button>
                </div>
                <?php endif; ?>
                <div id="modalImagesBody"></div>
            </div>
        </div>
    </div>
</div>

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

<script>
    const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
    const canDelete = <?= $canDelete ? 'true' : 'false' ?>;
    let currentPage = 1;
    let productsData = [];

    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        let icon = type === 'success' 
            ? `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:20px;height:20px;"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>` 
            : `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:20px;height:20px;"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3Z" /></svg>`;
        toast.innerHTML = `${icon} <span>${message}</span>`;
        container.appendChild(toast);
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    function loadData(page = 1) {
        currentPage = page;
        const loader = document.getElementById('loader');
        const table = document.getElementById('dataTable');
        const pagination = document.getElementById('paginationControls');

        fetch(`?api=fetch&page=${page}&t=${Date.now()}`)
            .then(res => res.json())
            .then(res => {
                loader.style.display = 'none';
                if (res.status === 'success') {
                    productsData = res.data;
                    renderTable(productsData);
                    renderPagination(res.totalPages, res.currentPage);
                    table.style.display = 'table';
                    pagination.style.display = res.totalPages > 1 ? 'flex' : 'none';
                } else {
                    loader.style.display = 'block';
                    loader.innerHTML = `<span style="color:var(--rose-500)">${res.message}</span>`;
                }
            })
            .catch(err => {
                loader.style.display = 'block';
                loader.innerHTML = `<span style="color:var(--rose-500)">Failed to load data.</span>`;
            });
    }

    function renderPagination(totalPages, current) {
        const info = document.getElementById('pageInfo');
        const btns = document.getElementById('pageBtns');
        info.textContent = `Page ${current} of ${totalPages}`;
        btns.innerHTML = '';
        let prevBtn = document.createElement('button');
        prevBtn.className = 'page-btn';
        prevBtn.textContent = 'Prev';
        prevBtn.disabled = (current === 1);
        prevBtn.onclick = () => loadData(current - 1);
        btns.appendChild(prevBtn);
        let nextBtn = document.createElement('button');
        nextBtn.className = 'page-btn';
        nextBtn.textContent = 'Next';
        nextBtn.disabled = (current === totalPages || totalPages === 0);
        nextBtn.onclick = () => loadData(current + 1);
        btns.appendChild(nextBtn);
    }

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

        if (data.length === 0) {
            tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding: 40px; color:var(--slate-500);">No products found.</td></tr>`;
            return;
        }

        data.forEach(item => {
            let actionsHtml = `<div class="action-btns">`;
            
            actionsHtml += `
                <button class="btn-action view-btn" onclick="openImageModal(${item.id})" title="Images">
                    <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="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" /></svg>
                </button>`;

            if (canEdit) {
                actionsHtml += `
                    <button class="btn-action edit-btn" onclick="openProductModal('edit', ${item.id})" 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.652L6.832 19.82a4.5 4.5 0 0 1-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 0 1 1.13-1.897L16.863 4.487Zm0 0L19.5 7.125" /></svg>
                    </button>`;
            }

            if (canDelete) {
                actionsHtml += `
                    <button class="btn-action delete-btn" onclick="deleteProduct(${item.id}, this)" 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 imgHtml = item.image_link ? `<img src="${item.image_link}" class="product-img" alt="IMG">` : `<div class="product-img" style="display:grid;place-items:center;font-size:10px;color:#cbd5e1">N/A</div>`;
            let delFree = item.DeliveryFree ? `<span style="color:var(--amber-600);font-weight:600;">${item.DeliveryFree}</span>` : `<span style="color:var(--slate-500);">N/A</span>`;
            let homeDel = item.home_delivery === 'Yes' ? `<span style="color:var(--emerald-600);font-weight:600;">Yes</span>` : `<span style="color:var(--slate-500);">No</span>`;

            let tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <div class="prod-info">
                        ${imgHtml}
                        <div>
                            <div class="prod-title">#${item.id} - ${item.title || 'No Title'}</div>
                            <div class="prod-desc" title="${item.description || ''}">${item.description || '-'}</div>
                        </div>
                    </div>
                </td>
                <td>
                    <div class="stat-block">Amt: <strong>${item.amount || '0'}</strong></div>
                    <div class="stat-block">Dis: <strong>${item.discount || '0'}</strong></div>
                    <div class="stat-block">Charge: ${delFree}</div>
                    <div class="stat-block">Home Del: ${homeDel}</div>
                </td>
                <td>
                    <div class="stat-block">Stock: <strong>${item.stock || '0'}</strong></div>
                    <div class="stat-block">Sold: <strong>${item.sold || '0'}</strong></div>
                </td>
                <td style="font-size:13px; color:var(--slate-500);">${item.created_at || '-'}</td>
                <td>${actionsHtml}</td>
            `;
            tbody.appendChild(tr);
        });
    }

    function openProductModal(type, id = 0) {
        const overlay = document.getElementById('productModalOverlay');
        const form = document.getElementById('productForm');
        document.getElementById('modalTitle').textContent = type === 'add' ? 'Add New Product' : 'Edit Product';
        document.getElementById('p_type').value = type;
        document.getElementById('p_id').value = id;

        if (type === 'edit') {
            const item = productsData.find(p => p.id == id);
            if (item) {
                document.getElementById('p_title').value = item.title || '';
                document.getElementById('p_amount').value = item.amount || 0;
                document.getElementById('p_discount').value = item.discount || 0;
                document.getElementById('p_stock').value = item.stock || 0;
                document.getElementById('p_sold').value = item.sold || 0;
                document.getElementById('p_image_link').value = item.image_link || '';
                document.getElementById('p_description').value = item.description || '';
                document.getElementById('p_DeliveryFree').value = item.DeliveryFree || '';
                document.getElementById('p_home_delivery').value = item.home_delivery || 'No';
            }
        } else {
            form.reset();
            document.getElementById('p_type').value = 'add';
            document.getElementById('p_id').value = 0;
            document.getElementById('p_DeliveryFree').value = '';
            document.getElementById('p_home_delivery').value = 'No';
        }
        overlay.style.display = 'grid';
    }

    function closeProductModal() {
        document.getElementById('productModalOverlay').style.display = 'none';
        document.getElementById('productForm').reset();
    }

    function saveProduct(e) {
        e.preventDefault();
        const form = document.getElementById('productForm');
        const btn = document.getElementById('saveBtn');
        const formData = new FormData(form);
        
        btn.disabled = true;
        btn.textContent = 'Saving...';

        fetch('?api=process', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            btn.disabled = false;
            btn.textContent = 'Save Product';
            if (res.status === 'success') {
                showToast(res.message, 'success');
                closeProductModal();
                loadData(currentPage);
            } else {
                showToast(res.message, 'error');
            }
        })
        .catch(err => {
            btn.disabled = false;
            btn.textContent = 'Save Product';
            showToast('Connection error.', 'error');
        });
    }

    function deleteProduct(id, btn) {
        if (!confirm('Are you sure you want to permanently delete this product and its images?')) return;
        if (btn) btn.disabled = true;
        const formData = new FormData();
        formData.append('id', id);
        formData.append('type', 'delete');
        fetch('?api=process', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message, 'success');
                loadData(currentPage);
            } else {
                showToast(res.message, 'error');
                if (btn) btn.disabled = false;
            }
        }).catch(() => { showToast('Connection error.', 'error'); if (btn) btn.disabled = false; });
    }

    function openImageModal(productId) {
        document.getElementById('img_product_id').value = productId;
        if(document.getElementById('new_image_link')) document.getElementById('new_image_link').value = '';
        document.getElementById('imageModalOverlay').style.display = 'grid';
        loadImages(productId);
    }

    function closeImageModal() {
        document.getElementById('imageModalOverlay').style.display = 'none';
        document.getElementById('modalImagesBody').innerHTML = '';
    }

    function loadImages(productId) {
        const body = document.getElementById('modalImagesBody');
        body.innerHTML = `<div style="text-align:center; padding:20px; color:var(--slate-500);">Loading images...</div>`;
        fetch(`?api=fetch_images&id=${productId}&t=${Date.now()}`)
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                if (res.data.length === 0) {
                    body.innerHTML = `<div class="no-images">No additional images found.</div>`;
                    return;
                }
                let gridHtml = `<div class="image-grid">`;
                res.data.forEach(img => {
                    let delBtn = canDelete ? `<button class="img-delete" onclick="deleteImage(${img.id})" title="Delete"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" style="width:14px;height:14px;"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg></button>` : '';
                    gridHtml += `
                        <div class="image-item">
                            <img src="${img.image_link}" alt="Img">
                            <div class="img-overlay">${delBtn}</div>
                        </div>`;
                });
                gridHtml += `</div>`;
                body.innerHTML = gridHtml;
            } else {
                body.innerHTML = `<div class="no-images" style="border-color:var(--rose-500); color:var(--rose-500);">Failed to load images.</div>`;
            }
        }).catch(() => {
            body.innerHTML = `<div class="no-images" style="border-color:var(--rose-500); color:var(--rose-500);">Connection error.</div>`;
        });
    }

    function addImage() {
        const pid = document.getElementById('img_product_id').value;
        const link = document.getElementById('new_image_link').value;
        if (!link) { showToast('Please enter an image link', 'error'); return; }
        
        const formData = new FormData();
        formData.append('type', 'add_image');
        formData.append('product_id', pid);
        formData.append('image_link', link);

        fetch('?api=process', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message, 'success');
                document.getElementById('new_image_link').value = '';
                loadImages(pid);
            } else {
                showToast(res.message, 'error');
            }
        }).catch(() => showToast('Connection error.', 'error'));
    }

    function deleteImage(imgId) {
        if (!confirm('Delete this image?')) return;
        const pid = document.getElementById('img_product_id').value;
        const formData = new FormData();
        formData.append('type', 'delete_image');
        formData.append('image_id', imgId);

        fetch('?api=process', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message, 'success');
                loadImages(pid);
            } else {
                showToast(res.message, 'error');
            }
        }).catch(() => showToast('Connection error.', 'error'));
    }

    window.onclick = function(event) {
        if (event.target === document.getElementById('productModalOverlay')) closeProductModal();
        if (event.target === document.getElementById('imageModalOverlay')) closeImageModal();
    }

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