<?php
session_start();
$loggedIn = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: topup_list_manager.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Topup List 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, #a1c4fd 0%, #c2e9fb 100%);
            background-attachment: fixed; min-height: 100vh; padding: 3vh 1vw; color: var(--text-main); font-size: 13px; 
        }

        .os-window {
            max-width: 1100px; 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.25); 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; }

        /* Tabs */
        .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 styling */
        .form-label { font-weight: 600; font-size: 12px; color: #475569; margin-bottom: 5px; }
        .form-control { font-size: 13px; border-radius: 8px; padding: 10px; border: 1px solid #cbd5e1; }
        .form-control: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; }

        /* Table */
        .table-custom th { background: #f8fafc; font-size: 11px; text-transform: uppercase; color: #64748b; }
        .table-custom td { vertical-align: middle; font-size: 13px; }
        .prod-img { width: 40px; height: 40px; border-radius: 8px; object-fit: cover; border: 1px solid #e2e8f0; }

        .login-box { max-width: 320px; margin: 60px auto; text-align: center; }
        .login-box input { width: 100%; margin-bottom: 15px; }
    </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">Topup Items Setup</div>
        <?php if ($loggedIn): ?> <a href="?logout=1" class="text-danger fw-bold"><i class="fas fa-power-off"></i></a> <?php else: ?> <div></div> <?php endif; ?>
    </div>

    <div class="window-content">
        <?php if (!$loggedIn): ?>
            <div class="login-box">
                <i class="fas fa-gem fa-3x mb-3" style="color: #3b82f6;"></i>
                <h5 class="mb-4">System Access</h5>
                <form id="loginForm">
                    <input type="text" id="adminUsername" class="form-control" placeholder="Username" required>
                    <input type="password" id="adminPassword" class="form-control" placeholder="Password" required>
                    <button type="submit" class="btn-theme w-100">Login</button>
                </form>
            </div>
        <?php else: ?>
            
            <div class="os-tabs">
                <button class="active" onclick="switchTab('list')"><i class="fas fa-list"></i> View Topups</button>
                <button onclick="switchTab('form')" id="tabAddBtn"><i class="fas fa-plus"></i> Add New</button>
            </div>

            <!-- TAB 1: LIST -->
            <div id="tab-list">
                <div class="table-responsive">
                    <table class="table table-hover table-custom">
                        <thead>
                            <tr>
                                <th>Item details</th>
                                <th>Real Price</th>
                                <th>Discount Price</th>
                                <th>Stock Message</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="tableBody">
                            <tr><td colspan="5" class="text-center py-4">Loading data...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- TAB 2: ADD / EDIT FORM -->
            <div id="tab-form" style="display: none;">
                <form id="setupForm">
                    <input type="hidden" name="id" id="itemId" value="0">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Topup Title</label>
                            <input type="text" name="title" id="title" class="form-control" placeholder="E.g. Weekly Membership" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Image Link</label>
                            <input type="text" name="image_link" id="image_link" class="form-control" placeholder="https://domain.com/img.png">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Real Price (৳)</label>
                            <input type="number" step="0.01" name="real_price" id="real_price" class="form-control" placeholder="0.00" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Discount Price (৳)</label>
                            <input type="number" step="0.01" name="discount_price" id="discount_price" class="form-control" placeholder="0.00">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Stock Message</label>
                            <input type="text" name="stock_message" id="stock_message" class="form-control" placeholder="E.g. In Stock / Out of Stock">
                        </div>
                    </div>
                    
                    <hr>
                    <div class="text-end">
                        <button type="button" class="btn btn-light border fw-bold me-2" onclick="resetForm()">Cancel</button>
                        <button type="submit" class="btn-theme" id="saveBtn"><i class="fas fa-save"></i> Save Topup</button>
                    </div>
                </form>
            </div>

        <?php endif; ?>
    </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 API_URL = 'topup_list_api.php';

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();
}

// Tab Switching
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 {
        $('.os-tabs button:eq(1)').addClass('active');
        $('#tab-list').hide(); $('#tab-form').show();
    }
}

// Reset Form to Add Mode
window.resetForm = function() {
    $('#setupForm')[0].reset();
    $('#itemId').val(0);
    $('#tabAddBtn').html('<i class="fas fa-plus"></i> Add New');
    $('#saveBtn').html('<i class="fas fa-save"></i> Save Topup');
}

$(document).ready(function() {
    // Login
    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        const btn = $(this).find('button');
        btn.text('Wait...');
        $.post(API_URL, { action: 'login', admin_username: $('#adminUsername').val(), admin_password: $('#adminPassword').val() }, function(res) {
            if (res.status === 'success') location.reload(); else { showToast(res.message, 'error'); btn.text('Login'); }
        });
    });

    <?php if ($loggedIn): ?>
    
    // Fetch List
    window.fetchData = function() {
        $('#tableBody').html('<tr><td colspan="5" 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 = '';
                if(res.data.length === 0) html = '<tr><td colspan="5" class="text-center py-4">No topup items found.</td></tr>';
                res.data.forEach(item => {
                    const img = item.image_link ? `<img src="${item.image_link}" class="prod-img me-2">` : `<div class="prod-img me-2 d-inline-block bg-light"></div>`;
                    
                    html += `<tr>
                        <td>
                            <div class="d-flex align-items-center">
                                ${img}
                                <div><strong>${item.title}</strong></div>
                            </div>
                        </td>
                        <td><span class="text-muted"><del>৳${item.real_price}</del></span></td>
                        <td><strong class="text-success" style="font-size:15px;">৳${item.discount_price}</strong></td>
                        <td><span class="badge bg-warning text-dark">${item.stock_message || 'N/A'}</span></td>
                        <td>
                            <button class="btn btn-sm btn-primary px-2 py-1 me-1" onclick="editData(${item.id})"><i class="fas fa-edit"></i> Edit</button>
                            <button class="btn btn-sm btn-danger px-2 py-1" onclick="deleteData(${item.id})"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>`;
                });
                $('#tableBody').html(html);
            }
        });
    }

    // Submit Add/Update Form
    $('#setupForm').on('submit', function(e) {
        e.preventDefault();
        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');
            }
        });
    });

    // Edit Button Clicked
    window.editData = function(id) {
        $.post(API_URL, { action: 'get_single', id: id }, function(res) {
            if(res.status === 'success') {
                $('#itemId').val(res.data.id);
                $('#title').val(res.data.title);
                $('#real_price').val(res.data.real_price);
                $('#discount_price').val(res.data.discount_price);
                $('#image_link').val(res.data.image_link);
                $('#stock_message').val(res.data.stock_message);
                
                // Switch to form tab and change button text
                $('.os-tabs button:eq(1)').addClass('active').html('<i class="fas fa-edit"></i> Edit Item');
                $('#tab-list').hide(); $('#tab-form').show();
                $('#saveBtn').html('<i class="fas fa-sync-alt"></i> Update Topup');
            } else {
                showToast(res.message, 'error');
            }
        });
    }

    // Delete Button Clicked
    window.deleteData = function(id) {
        if(!confirm('Are you sure you want to delete this topup item?')) return;
        $.post(API_URL, { action: 'delete', id: id }, function(res) {
            if(res.status === 'success') { showToast(res.message, 'success'); fetchData(); }
            else showToast(res.message, 'error');
        });
    }

    // Load data on page load
    fetchData();
    <?php endif; ?>
});
</script>
</body>
</html>