<?php
session_start();

// ১. লগিন চেক (লগিন না থাকলে admin_login.php তে পাঠাবে)
if (!isset($_SESSION['admin_logged_in']) || !isset($_SESSION['admin_user']) || !isset($_SESSION['admin_pass'])) {
    header("Location: admin_login.php");
    exit;
}

// ২. ডাটাবেজ কনফিগারেশন লোড
$config_paths = ['Config.php', 'config.php', '../Config.php', '../config.php'];
$config_loaded = false;
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $config_loaded = true;
        break;
    }
}
if (!$config_loaded) die("Config file missing!");
if (!isset($conn) && isset($con)) $conn = $con;

// ৩. লাইভ পারমিশন চেক (modarator_permissions টেবিল থেকে)
$admin_user = $_SESSION['admin_user'];
$admin_pass = $_SESSION['admin_pass'];
$row = null;

$sql = "SELECT * FROM modarator_permissions WHERE username = ? LIMIT 1";
$stmt = @$conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("s", $admin_user);
    if (@$stmt->execute()) {
        $res = $stmt->get_result();
        if ($res && $res->num_rows > 0) {
            $row = $res->fetch_assoc();
        } else {
            session_unset(); session_destroy();
            header("Location: admin_login.php"); exit;
        }
    }
    $stmt->close();
}

// ৪. মূল পেজ দেখার পারমিশন (match_editing)
$can_match_editing = strtolower(trim((string)($row['match_editing'] ?? 'no'))) === 'yes';

if (!$can_match_editing) {
    die('<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>অ্যাক্সেস বাতিল</title></head><body style="margin:0;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;background:#f4f6f9;font-family:sans-serif;"><svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#ff3b30" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg><h2 style="color:#ff3b30;margin:20px 0 10px;">অ্যাক্সেস বাতিল!</h2><p style="color:#71717a;margin-bottom:20px;">আপনার এই পেজটি ব্যবহারের পারমিশন নেই।</p><button onclick="window.location.href=\'index.php\'" style="background:#007aff;color:#fff;border:none;padding:12px 24px;border-radius:10px;cursor:pointer;">ফিরে যান</button></body></html>');
}

// ৫. extra_json থেকে ক্যাটাগরিভিত্তিক (Add/Edit/Delete) পারমিশন ডিকোড করা
$extra_json_str = $row['extra_json'] ?? '{}';
$extra_perms = json_decode($extra_json_str, true);
if (!is_array($extra_perms)) $extra_perms = [];

// যেসব ক্যাটাগরিতে অন্তত একটি পারমিশন Yes আছে, সেগুলো আলাদা করা
$allowed_categories = [];
$can_add_any = false;

foreach ($extra_perms as $category_name => $perms) {
    $add = (isset($perms['Add']) && $perms['Add'] === 'Yes');
    $edit = (isset($perms['Edit']) && $perms['Edit'] === 'Yes');
    $delete = (isset($perms['Delete']) && $perms['Delete'] === 'Yes');
    
    if ($add || $edit || $delete) {
        $allowed_categories[$category_name] = [
            'Add' => $add ? 'Yes' : 'No',
            'Edit' => $edit ? 'Yes' : 'No',
            'Delete' => $delete ? 'Yes' : 'No'
        ];
    }
    if ($add) $can_add_any = true; // যদি কোনো একটি ক্যাটাগরিতেও Add পারমিশন থাকে
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Match Schedule Manager</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    
    <style>
        :root {
            --window-bg: rgba(255, 255, 255, 0.95);
            --text-main: #1e293b;
            --border-color: rgba(0, 0, 0, 0.1);
        }
        * { font-family: 'Inter', sans-serif; box-sizing: border-box; }
        body { 
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            background-attachment: fixed; min-height: 100vh; padding: 2vh 1vw; color: var(--text-main); font-size: 13px; 
        }

        .os-window {
            max-width: 1350px; margin: 0 auto; background: var(--window-bg);
            backdrop-filter: blur(20px); border-radius: 16px;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5); overflow: hidden;
        }
        .window-header {
            background: rgba(255, 255, 255, 0.6); padding: 12px 20px;
            border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center;
        }
        .traffic-lights { display: flex; gap: 8px; }
        .dot { width: 12px; height: 12px; border-radius: 50%; }
        .dot.red { background: #ff5f56; } .dot.yellow { background: #ffbd2e; } .dot.green { background: #27c93f; }
        
        .window-content { padding: 25px; }

        .os-tabs { background: rgba(0,0,0,0.05); padding: 5px; border-radius: 8px; display: inline-flex; gap: 5px; margin-bottom: 20px; }
        .os-tabs button { padding: 8px 20px; border-radius: 6px; border: none; font-weight: 600; font-size: 13px; background: transparent; color: #64748b; transition: 0.2s; }
        .os-tabs button.active { background: white; color: var(--text-main); box-shadow: 0 2px 5px rgba(0,0,0,0.05); }

        .form-label { font-weight: 600; font-size: 12px; color: #475569; margin-bottom: 5px; }
        .form-control, .form-select { font-size: 13px; border-radius: 8px; padding: 10px; border: 1px solid #cbd5e1; }
        .form-control:focus, .form-select:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
        
        .btn-theme { background: #3b82f6; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: 600; }
        .btn-theme:hover { background: #2563eb; color: white; }
        
        .section-title { font-size: 12px; text-transform: uppercase; font-weight: 700; color: #94a3b8; margin-top: 15px; margin-bottom: 10px; border-bottom: 1px dashed #cbd5e1; padding-bottom: 5px;}

        .table-custom th { background: #f8fafc; font-size: 11px; text-transform: uppercase; color: #64748b; }
        .table-custom td { vertical-align: middle; font-size: 13px; }
    </style>
</head>
<body>

<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 9999;">
    <div id="liveToast" class="toast border-0 shadow-sm" role="alert">
        <div class="toast-body fw-bold rounded" id="toastMessage" style="font-size: 13px; background: white;"></div>
    </div>
</div>

<div class="os-window">
    <div class="window-header">
        <div class="traffic-lights"><div class="dot red"></div><div class="dot yellow"></div><div class="dot green"></div></div>
        <div class="fw-bold text-secondary">Advanced Match Scheduler</div>
        <a href="index.php" class="text-primary fw-bold text-decoration-none"><i class="fas fa-home"></i> Dashboard</a>
    </div>

    <div class="window-content">
        <div class="os-tabs">
            <button class="active" onclick="switchTab('list')"><i class="fas fa-list"></i> Match List</button>
            <?php if ($can_add_any): ?>
            <button onclick="switchTab('form')" id="tabAddBtn"><i class="fas fa-plus"></i> Add Match</button>
            <?php endif; ?>
        </div>

        <div id="tab-list">
            <div class="table-responsive">
                <table class="table table-hover table-custom">
                    <thead>
                        <tr>
                            <th>ID & Match Info</th>
                            <th>Schedule Time</th>
                            <th>Fee & Prize</th>
                            <th>Players & Type</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <tr><td colspan="6" class="text-center py-4">Loading data...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div id="tab-form" style="display: none;">
            <form id="setupForm">
                <input type="hidden" name="id" id="matchId" value="0">
                
                <div class="row">
                    <div class="col-12"><div class="section-title">1. Basic Information</div></div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Match Title</label>
                        <input type="text" name="match_title" id="match_title" class="form-control" placeholder="E.g. Daily Scrims" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Match Type (Category)</label>
                        <select name="match_type" id="match_type" class="form-select" required>
                            <option value="">-- Select Match Type --</option>
                        </select>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Version</label>
                        <input type="text" name="version" id="version" class="form-control" placeholder="TPP / FPP">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Play Map</label>
                        <input type="text" name="play_map" id="play_map" class="form-control" placeholder="Bermuda / Erangel">
                    </div>

                    <div class="col-12"><div class="section-title">2. Schedule & Timing</div></div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Start Time (কখন অ্যাপে দেখাবে)</label>
                        <input type="datetime-local" name="start_time" id="start_time" class="form-control" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Match Time (ম্যাচ কখন শুরু হবে)</label>
                        <input type="datetime-local" name="match_time" id="match_time" class="form-control" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Interval (Minutes)</label>
                        <input type="number" name="interval_minute" id="interval_minute" class="form-control" placeholder="0">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Timer Settings (Optional)</label>
                        <input type="datetime-local" name="timer" id="timer" class="form-control">
                    </div>

                    <div class="col-12"><div class="section-title">3. Fee & Prize</div></div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Entry Fee (৳)</label>
                        <input type="number" step="0.01" name="entry_fee" id="entry_fee" class="form-control" placeholder="0">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Total Prize (৳)</label>
                        <input type="number" step="0.01" name="total_prize" id="total_prize" class="form-control" placeholder="0">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Per Kill Prize (৳)</label>
                        <input type="number" step="0.01" name="per_kill" id="per_kill" class="form-control" placeholder="0">
                    </div>

                    <div class="col-12"><div class="section-title">4. Player & Match Setup</div></div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Total Match</label>
                        <input type="number" name="total_match" id="total_match" class="form-control" placeholder="1">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Total Players limit</label>
                        <input type="number" name="total_player" id="total_player" class="form-control" placeholder="48">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Entry Type</label>
                        <select name="entry_type" id="entry_type" class="form-select">
                            <option value="Solo">Solo</option>
                            <option value="Duo">Duo</option>
                            <option value="Squad">Squad</option>
                        </select>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Join Type</label>
                        <input type="text" name="join_type" id="join_type" class="form-control" placeholder="Standard">
                    </div>

                    <div class="col-12"><div class="section-title">5. Status & Details</div></div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Registration Status</label>
                        <select name="registration" id="registration" class="form-select">
                            <option value="Open">Open</option>
                            <option value="Closed">Closed</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Match Status</label>
                        <select name="status" id="status" class="form-select">
                            <option value="Upcoming">Upcoming</option>
                            <option value="Ongoing">Ongoing</option>
                            <option value="Completed">Completed</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Created Count</label>
                        <input type="number" name="created_count" id="created_count" class="form-control" placeholder="0">
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Prize Details & Description</label>
                        <textarea name="prize_details" id="prize_details" class="form-control" rows="3" placeholder="Write full details here..."></textarea>
                    </div>
                </div>
                
                <hr>
                <div class="text-end">
                    <button type="button" class="btn btn-light border fw-bold me-2" onclick="switchTab('list')">Cancel</button>
                    <button type="submit" class="btn-theme" id="saveBtn"><i class="fas fa-save"></i> Save Match</button>
                </div>
            </form>
        </div>

    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
// পিএইচপি থেকে ক্যাটাগরি এবং পারমিশন ডাটা জাভাস্ক্রিপ্টে পাঠানো হলো
const CATEGORY_PERMISSIONS = <?php echo json_encode($allowed_categories, JSON_UNESCAPED_UNICODE); ?>;
const API_URL = 'match_schedule_api.php'; 
let allSystemCategories = []; // ডাটাবেজের সব ক্যাটাগরি সেভ রাখার জন্য

function showToast(message, type = 'success') {
    const toastEl = $('#liveToast');
    const body = $('#toastMessage');
    if (type === 'success') body.html(`✅ ${message}`).css('color', '#15803d');
    else body.html(`❌ ${message}`).css('color', '#b91c1c');
    new bootstrap.Toast(toastEl, { delay: 3000 }).show();
}

function formatToLocalInput(dbDateStr) {
    if(!dbDateStr || dbDateStr === '0000-00-00 00:00:00' || dbDateStr.trim() === '') return '';
    const date = new Date(dbDateStr);
    if(isNaN(date.getTime())) return '';
    date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return date.toISOString().slice(0, 16);
}

function formatDisplayDate(dbDateStr) {
    if(!dbDateStr || dbDateStr === '0000-00-00 00:00:00' || dbDateStr.trim() === '') return 'N/A';
    const date = new Date(dbDateStr);
    if(isNaN(date.getTime())) return dbDateStr;
    return date.toLocaleString('en-US', {day:'numeric', month:'short', year:'numeric', hour:'numeric', minute:'numeric', hour12:true});
}

// ড্রপডাউন পপুলেট করার ফাংশন (Add এবং Edit এর জন্য আলাদা ফিল্টারিং)
function populateCategoryDropdown(isEditMode) {
    let options = '<option value="">-- Select Match Type --</option>';
    allSystemCategories.forEach(cat => {
        let catName = cat.title || cat;
        if (CATEGORY_PERMISSIONS[catName]) {
            let perms = CATEGORY_PERMISSIONS[catName];
            // Add মোডে থাকলে শুধু যেসব ক্যাটাগরিতে Add='Yes' সেগুলো দেখাবে
            // Edit মোডে থাকলে শুধু যেসব ক্যাটাগরিতে Edit='Yes' সেগুলো দেখাবে
            if ((!isEditMode && perms.Add === 'Yes') || (isEditMode && perms.Edit === 'Yes')) {
                options += `<option value="${catName}">${catName}</option>`;
            }
        }
    });
    $('#match_type').html(options);
}

window.switchTab = function(tab) {
    $('.os-tabs button').removeClass('active');
    if(tab === 'list') {
        $('.os-tabs button:eq(0)').addClass('active');
        $('#tab-list').show(); $('#tab-form').hide();
        fetchData();
        resetForm();
    } else {
        if($('#tabAddBtn').length) $('#tabAddBtn').addClass('active');
        $('#tab-list').hide(); $('#tab-form').show();
        populateCategoryDropdown(false); // Add Mode dropdown
    }
}

window.resetForm = function() {
    $('#setupForm')[0].reset();
    $('#matchId').val(0);
    if($('#tabAddBtn').length) $('#tabAddBtn').html('<i class="fas fa-plus"></i> Add Match');
    $('#saveBtn').html('<i class="fas fa-save"></i> Save Match');
}

$(document).ready(function() {
    
    // এপিআই থেকে একবার সব ক্যাটাগরি লোড করে ভেরিয়েবলে সেভ করে রাখা
    window.loadCategories = function() {
        $.post(API_URL, { action: 'get_categories' }, function(res) {
            if (res.status === 'success' && res.categories) {
                allSystemCategories = res.categories; 
            } else if (res.status === 'success' && res.data) {
                allSystemCategories = res.data;
            }
        });
    };

    // টেবিল ডাটা লোড করার ফাংশন
    window.fetchData = function() {
        $('#tableBody').html('<tr><td colspan="6" class="text-center py-4"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');
        $.post(API_URL, { action: 'get_list' }, function(res) {
            if (res.status === 'success') {
                let html = '';
                let visibleCount = 0;
                
                res.data.forEach(item => {
                    let catName = item.match_type;
                    
                    // ১. যদি এই ক্যাটাগরিতে পারমিশন না থাকে, তবে এই ম্যাচ দেখাবেই না
                    if (!CATEGORY_PERMISSIONS[catName]) return; 

                    let perms = CATEGORY_PERMISSIONS[catName];
                    let canEdit = (perms.Edit === 'Yes');
                    let canDelete = (perms.Delete === 'Yes');

                    let badgeClass = 'bg-primary';
                    if(item.status === 'Completed') badgeClass = 'bg-success';
                    if(item.status === 'Upcoming') badgeClass = 'bg-warning text-dark';
                    
                    // ২. পারমিশন অনুযায়ী অ্যাকশন বাটন তৈরি
                    let actionBtns = '';
                    if (canEdit) {
                        actionBtns += `<button class="btn btn-sm btn-info text-white px-2 py-1 me-1" onclick="editData(${item.id})"><i class="fas fa-edit"></i></button>`;
                    }
                    if (canDelete) {
                        actionBtns += `<button class="btn btn-sm btn-danger px-2 py-1" onclick="deleteData(${item.id})"><i class="fas fa-trash"></i></button>`;
                    }
                    if (!canEdit && !canDelete) {
                        actionBtns = '<span class="text-muted" style="font-size:10px; font-weight:bold;">No Access</span>';
                    }

                    visibleCount++;
                    html += `<tr>
                        <td>
                            <strong>${item.match_title}</strong><br>
                            <span class="text-muted" style="font-size:10px;">ID: #${item.id} | ${catName}</span>
                        </td>
                        <td>
                            <strong class="text-primary">${formatDisplayDate(item.match_time)}</strong><br>
                            <span class="text-muted" style="font-size:11px;">Show: ${formatDisplayDate(item.start_time)}</span>
                        </td>
                        <td>
                            Fee: <strong>৳${item.entry_fee}</strong><br>
                            Prize: <strong class="text-success">৳${item.total_prize}</strong>
                        </td>
                        <td>
                            Limit: <strong>${item.total_player}</strong> (${item.entry_type})<br>
                            <span class="text-muted" style="font-size:10px;">Map: ${item.play_map}</span>
                        </td>
                        <td>
                            <span class="badge ${badgeClass}">${item.status}</span><br>
                            <span class="text-muted" style="font-size:10px;">Reg: ${item.registration}</span>
                        </td>
                        <td><div class="d-flex">${actionBtns}</div></td>
                    </tr>`;
                });

                if (visibleCount === 0) {
                    html = '<tr><td colspan="6" class="text-center py-4 text-muted">আপনার দেখার মতো কোনো ম্যাচ পাওয়া যায়নি।</td></tr>';
                }
                $('#tableBody').html(html);
            }
        });
    }

    // ফর্ম সাবমিট (Add/Edit)
    $('#setupForm').on('submit', function(e) {
        e.preventDefault();
        let matchId = parseInt($('#matchId').val());
        let selectedCat = $('#match_type').val();
        
        // সাবমিট করার সময় ডাবল পারমিশন সিকিউরিটি চেক
        let perms = CATEGORY_PERMISSIONS[selectedCat] || {Add: 'No', Edit: 'No'};
        if (matchId === 0 && perms.Add !== 'Yes') return showToast("এই ক্যাটাগরিতে Add করার পারমিশন নেই!", "error");
        if (matchId > 0 && perms.Edit !== 'Yes') return showToast("এই ক্যাটাগরিতে Edit করার পারমিশন নেই!", "error");

        const formData = $(this).serialize() + '&action=save';
        const btn = $('#saveBtn');
        const originalHtml = btn.html();
        btn.html('<i class="fas fa-spinner fa-spin"></i> Processing...').prop('disabled', true);

        $.post(API_URL, formData, function(res) {
            btn.html(originalHtml).prop('disabled', false);
            if(res.status === 'success') {
                showToast(res.message, 'success');
                switchTab('list');
            } else {
                showToast(res.message, 'error');
            }
        });
    });

    // এডিট ডাটা রিকোয়েস্ট
    window.editData = function(id) {
        $.post(API_URL, { action: 'get_single', id: id }, function(res) {
            if(res.status === 'success') {
                const d = res.data;
                let catName = d.match_type;
                let perms = CATEGORY_PERMISSIONS[catName];
                
                if (!perms || perms.Edit !== 'Yes') return showToast("এই ম্যাচটি Edit করার পারমিশন আপনার নেই!", "error");

                populateCategoryDropdown(true); // Edit Mode dropdown (শুধু Edit=Yes গুলো দেখাবে)
                
                setTimeout(() => {
                    $('#matchId').val(d.id);
                    $('#match_title').val(d.match_title);
                    $('#match_type').val(catName);
                    $('#version').val(d.version);
                    $('#play_map').val(d.play_map);
                    $('#start_time').val(formatToLocalInput(d.start_time));
                    $('#match_time').val(formatToLocalInput(d.match_time));
                    $('#interval_minute').val(d.interval_minute);
                    $('#timer').val(formatToLocalInput(d.timer));
                    $('#entry_fee').val(d.entry_fee);
                    $('#total_prize').val(d.total_prize);
                    $('#per_kill').val(d.per_kill);
                    $('#total_match').val(d.total_match);
                    $('#total_player').val(d.total_player);
                    $('#entry_type').val(d.entry_type);
                    $('#join_type').val(d.join_type);
                    $('#registration').val(d.registration);
                    $('#status').val(d.status);
                    $('#created_count').val(d.created_count);
                    $('#prize_details').val(d.prize_details);
                    
                    $('.os-tabs button').removeClass('active');
                    if($('#tabAddBtn').length) $('#tabAddBtn').addClass('active').html('<i class="fas fa-edit"></i> Edit Match');
                    
                    $('#tab-list').hide(); $('#tab-form').show();
                    $('#saveBtn').html('<i class="fas fa-sync-alt"></i> Update Match');
                }, 100);
            }
        });
    }

    // ডিলিট রিকোয়েস্ট
    window.deleteData = function(id) {
        // ডিলিট করার আগে সিকিউরিটি পারমিশন চেক করার জন্য এপিআই থেকে ক্যাটাগরি জেনে নিবে
        $.post(API_URL, { action: 'get_single', id: id }, function(res) {
            if(res.status === 'success') {
                let catName = res.data.match_type;
                let perms = CATEGORY_PERMISSIONS[catName];
                if (!perms || perms.Delete !== 'Yes') {
                    return showToast("এই ম্যাচটি Delete করার পারমিশন আপনার নেই!", "error");
                }

                if(!confirm('আপনি কি নিশ্চিত এই ম্যাচটি ডিলিট করতে চান?')) return;
                
                $.post(API_URL, { action: 'delete', id: id }, function(delRes) {
                    if(delRes.status === 'success') { showToast(delRes.message, 'success'); fetchData(); }
                    else showToast(delRes.message, 'error');
                });
            }
        });
    }

    // পেজ লোড হওয়ার সাথে সাথে ক্যাটাগরি ও ডাটা ফেচ করা
    loadCategories();
    fetchData();
});
</script>
</body>
</html>