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

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: products_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>OS Style Product 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, #f6d365 0%, #fda085 100%);
            background-attachment: fixed;
            min-height: 100vh; padding: 3vh 1vw; color: var(--text-main); font-size: 13px; 
        }

        .os-window {
            max-width: 1200px; 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: #f97316; box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.1); }
        
        .btn-theme { background: #f97316; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: 600; }
        .btn-theme:hover { background: #ea580c; color: white; }

        /* Dynamic Image Box */
        .extra-img-box { background: #f8fafc; padding: 15px; border-radius: 10px; border: 1px dashed #cbd5e1; margin-bottom: 15px; }
        
        /* Table */
        .table-custom th { background: #f1f5f9; 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 */
        .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">Product Management Center</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-box-open fa-3x mb-3" style="color: #f97316;"></i>
                <h5 class="mb-4">Admin 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> Product List</button>
                <button onclick="switchTab('add')"><i class="fas fa-plus"></i> Add Product</button>
            </div>

            <!-- TAB 1: PRODUCT LIST -->
            <div id="tab-list">
                <div class="table-responsive">
                    <table class="table table-hover table-custom">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Pricing</th>
                                <th>Stock & Sold</th>
                                <th>Images Info</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="productTableBody">
                            <tr><td colspan="5" class="text-center py-4">Loading products...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- TAB 2: ADD PRODUCT -->
            <div id="tab-add" style="display: none;">
                <form id="addProductForm">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Product Title</label>
                                    <input type="text" name="title" class="form-control" placeholder="E.g. Free Fire 100 Diamonds" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Price / Amount (৳)</label>
                                    <input type="number" step="0.01" name="amount" class="form-control" placeholder="0.00" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Discount Price (৳)</label>
                                    <input type="number" step="0.01" name="discount" class="form-control" placeholder="0.00">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Stock Quantity</label>
                                    <input type="number" name="stock" class="form-control" value="100">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Already Sold (Optional)</label>
                                    <input type="number" name="sold" class="form-control" value="0">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Description</label>
                                    <textarea name="description" class="form-control" rows="3" placeholder="Write details..."></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Image Section -->
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label text-primary"><i class="fas fa-image"></i> Main Image Link</label>
                                <input type="text" name="image_link" class="form-control" placeholder="https://domain.com/main.jpg">
                            </div>

                            <div class="extra-img-box">
                                <label class="form-label text-success"><i class="fas fa-images"></i> Extra Images (JSON Array)</label>
                                <div id="extraImagesContainer">
                                    <div class="input-group mb-2">
                                        <input type="text" name="extra_images[]" class="form-control" placeholder="Extra Image URL 1">
                                    </div>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-success mt-2 fw-bold" onclick="addExtraImageInput()">
                                    <i class="fas fa-plus"></i> Add More Image
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    <div class="text-end">
                        <button type="submit" class="btn-theme"><i class="fas fa-check"></i> Save Product</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 = 'products_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 Switcher
window.switchTab = function(tab) {
    $('.os-tabs button').removeClass('active');
    if(tab === 'list') {
        $('.os-tabs button:eq(0)').addClass('active');
        $('#tab-list').show(); $('#tab-add').hide();
        fetchProducts();
    } else {
        $('.os-tabs button:eq(1)').addClass('active');
        $('#tab-list').hide(); $('#tab-add').show();
    }
}

// Add more extra image input field dynamically
window.addExtraImageInput = function() {
    $('#extraImagesContainer').append(`
        <div class="input-group mb-2">
            <input type="text" name="extra_images[]" class="form-control" placeholder="Another Image URL">
            <button type="button" class="btn btn-danger" onclick="$(this).parent().remove()"><i class="fas fa-times"></i></button>
        </div>
    `);
}

$(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 Products
    window.fetchProducts = function() {
        $('#productTableBody').html('<tr><td colspan="5" class="text-center py-4 text-muted"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');
        $.post(API_URL, { action: 'get_products' }, function(res) {
            if (res.status === 'success') {
                let html = '';
                if(res.data.length === 0) html = '<tr><td colspan="5" class="text-center py-4">No products found.</td></tr>';
                res.data.forEach(p => {
                    const img = p.image_link ? `<img src="${p.image_link}" class="prod-img me-2">` : `<div class="prod-img me-2 d-inline-block bg-light"></div>`;
                    const extraImgsCount = p.extra_images.length;
                    
                    html += `<tr>
                        <td>
                            <div class="d-flex align-items-center">
                                ${img}
                                <div><strong>${p.title}</strong><br><span class="text-muted" style="font-size:10px;">ID: #${p.id}</span></div>
                            </div>
                        </td>
                        <td>
                            <strong class="text-success">৳${p.amount}</strong>
                            ${p.discount > 0 ? `<br><small class="text-danger"><del>৳${p.discount}</del></small>` : ''}
                        </td>
                        <td>
                            <span class="badge bg-primary">Stock: ${p.stock}</span><br>
                            <span class="badge bg-secondary mt-1">Sold: ${p.sold}</span>
                        </td>
                        <td>
                            <span style="font-size:11px; color:#475569;"><i class="fas fa-images"></i> Extra Images: <strong>${extraImgsCount}</strong></span>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-danger px-2 py-1" onclick="deleteProduct(${p.id})"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>`;
                });
                $('#productTableBody').html(html);
            }
        });
    }

    // Add Product Form Submit
    $('#addProductForm').on('submit', function(e) {
        e.preventDefault();
        const formData = $(this).serialize() + '&action=add_product';
        const btn = $(this).find('button[type="submit"]');
        btn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);

        $.post(API_URL, formData, function(res) {
            btn.html('<i class="fas fa-check"></i> Save Product').prop('disabled', false);
            if(res.status === 'success') {
                showToast(res.message, 'success');
                $('#addProductForm')[0].reset();
                $('#extraImagesContainer').html(`<div class="input-group mb-2"><input type="text" name="extra_images[]" class="form-control" placeholder="Extra Image URL 1"></div>`);
                switchTab('list');
            } else {
                showToast(res.message, 'error');
            }
        });
    });

    // Delete Product
    window.deleteProduct = function(id) {
        if(!confirm('Are you sure you want to delete this product?')) return;
        $.post(API_URL, { action: 'delete_product', id: id }, function(res) {
            if(res.status === 'success') { showToast(res.message, 'success'); fetchProducts(); }
            else showToast(res.message, 'error');
        });
    }

    // Load list on start
    fetchProducts();
    <?php endif; ?>
});
</script>
</body>
</html>