<?php
// Include the secure database connection
require_once 'config.php';

$message = '';
$messageType = '';

// Create uploads directory if it doesn't exist
if (!file_exists('uploads')) {
    mkdir('uploads', 0777, true);
}

/**
 * Helper function to handle multiple file uploads safely.
 * Returns an array of file paths.
 */
function processUploads($fileArray) {
    $uploadedPaths = [];
    if (!empty($fileArray['name'][0])) {
        foreach ($fileArray['name'] as $key => $name) {
            if ($fileArray['error'][$key] === UPLOAD_ERR_OK) {
                $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
                
                if (in_array($ext, $allowed)) {
                    $filename = uniqid('prod_') . '_' . time() . '.' . $ext;
                    $dest = 'uploads/' . $filename;
                    if (move_uploaded_file($fileArray['tmp_name'][$key], $dest)) {
                        $uploadedPaths[] = $dest;
                    }
                }
            }
        }
    }
    return $uploadedPaths;
}

// --- HANDLE FORM SUBMISSIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // ADD PRODUCT
    if ($_POST['action'] === 'add') {
        // Handle image uploads
        $newImages = processUploads($_FILES['upload_images']);
        // Store as JSON array. The first image [0] is the default main image.
        $imgJson = json_encode($newImages);

        $stmt = $pdo->prepare('INSERT INTO products (name, cat, price, oldPrice, img, rating, badge, `desc`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
        try {
            $stmt->execute([
                $_POST['name'], $_POST['cat'], $_POST['price'], 
                $_POST['oldPrice'] ?: 0, $imgJson, 
                $_POST['rating'], $_POST['badge'], $_POST['desc']
            ]);
            $message = "Product added successfully!";
            $messageType = "success";
        } catch (\PDOException $e) {
            $message = "Error adding product: " . $e->getMessage();
            $messageType = "error";
        }
    }
    
    // EDIT PRODUCT
    elseif ($_POST['action'] === 'edit') {
        $existing = $_POST['existing_images'] ?? [];
        $remove = $_POST['remove_images'] ?? [];
        $mainImg = $_POST['main_image'] ?? '';

        // 1. Delete removed images from server
        foreach ($remove as $rem_img) {
            if (file_exists($rem_img)) unlink($rem_img);
        }

        // 2. Filter out removed images from existing array
        $kept = array_values(array_diff($existing, $remove));

        // 3. Process new uploads
        $newImages = processUploads($_FILES['upload_images']);
        $allImages = array_merge($kept, $newImages);

        // 4. Set Main Image (Move it to index 0)
        if ($mainImg && in_array($mainImg, $allImages)) {
            $allImages = array_values(array_diff($allImages, [$mainImg]));
            array_unshift($allImages, $mainImg);
        }

        $imgJson = json_encode($allImages);

        $stmt = $pdo->prepare('UPDATE products SET name=?, cat=?, price=?, oldPrice=?, img=?, rating=?, badge=?, `desc`=? WHERE id=?');
        try {
            $stmt->execute([
                $_POST['name'], $_POST['cat'], $_POST['price'], 
                $_POST['oldPrice'] ?: 0, $imgJson, 
                $_POST['rating'], $_POST['badge'], $_POST['desc'], 
                $_POST['id']
            ]);
            $message = "Product updated successfully!";
            $messageType = "success";
        } catch (\PDOException $e) {
            $message = "Error updating product: " . $e->getMessage();
            $messageType = "error";
        }
    }

    // DELETE PRODUCT
    elseif ($_POST['action'] === 'delete') {
        // Fetch to delete images first
        $stmt = $pdo->prepare('SELECT img FROM products WHERE id=?');
        $stmt->execute([$_POST['id']]);
        $prod = $stmt->fetch();
        if ($prod) {
            $imgs = json_decode($prod['img'], true) ?: [$prod['img']];
            foreach($imgs as $i) { if (file_exists($i)) unlink($i); }
        }

        $stmt = $pdo->prepare('DELETE FROM products WHERE id=?');
        try {
            $stmt->execute([$_POST['id']]);
            $message = "Product deleted successfully!";
            $messageType = "success";
        } catch (\PDOException $e) {
            $message = "Error deleting product: " . $e->getMessage();
            $messageType = "error";
        }
    }
}

// --- FETCH ALL PRODUCTS ---
try {
    $stmt = $pdo->query('SELECT * FROM products ORDER BY id DESC');
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process image JSON for frontend
    foreach ($products as &$p) {
        $imgs = json_decode($p['img'], true);
        // Fallback for old single-string URLs
        $p['img_array'] = is_array($imgs) ? $imgs : (!empty($p['img']) ? [$p['img']] : []);
        $p['main_img'] = $p['img_array'][0] ?? 'https://via.placeholder.com/300?text=No+Image';
    }
} catch (\PDOException $e) {
    $products = [];
    $message = "Database error: " . $e->getMessage();
    $messageType = "error";
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | B-A Appliances</title>
    <link rel="icon" type="image/png" href="img/logo.png">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@2.44.0/tabler-icons.min.css">
    <style>
    /* --- CSS VARIABLES --- */
    :root {
        --primary: #185FA5;
        --primary-hover: #0C447C;
        --danger: #E24B4A;
        --bg-body: #f4f6f8;
        --bg-surface: #ffffff;
        --text-main: #1e293b;
        --text-muted: #64748b;
        --border: #e2e8f0;
        --radius: 12px;
        --transition: all 0.2s ease;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
        background-color: var(--bg-body);
        color: var(--text-main);
        display: flex;
        min-height: 100vh;
    }

    button {
        cursor: pointer;
        border: none;
        background: none;
        font-family: inherit;
    }

    input,
    select,
    textarea {
        width: 100%;
        padding: 10px 14px;
        border: 1px solid var(--border);
        border-radius: 6px;
        font-family: inherit;
        outline: none;
        transition: border 0.3s;
    }

    input:focus,
    select:focus,
    textarea:focus {
        border-color: var(--primary);
    }

    /* --- LAYOUT --- */
    .sidebar {
        width: 260px;
        background: var(--bg-surface);
        border-right: 1px solid var(--border);
        display: flex;
        flex-direction: column;
        position: sticky;
        top: 0;
        height: 100vh;
        z-index: 100;
    }

    .sidebar-header {
        padding: 24px;
        border-bottom: 1px solid var(--border);
        text-align: center;
    }

    .sidebar-header h2 {
        color: var(--primary);
        font-weight: 900;
        letter-spacing: -1px;
    }

    .nav-links {
        padding: 20px;
        display: flex;
        flex-direction: column;
        gap: 8px;
        flex: 1;
    }

    .nav-link {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 16px;
        color: var(--text-muted);
        text-decoration: none;
        border-radius: 8px;
        font-weight: 600;
        transition: var(--transition);
    }

    .nav-link:hover,
    .nav-link.active {
        background: var(--primary);
        color: white;
    }

    .main-content {
        flex: 1;
        padding: 40px;
        overflow-y: auto;
    }

    .top-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        flex-wrap: wrap;
        gap: 16px;
    }

    /* --- BUTTONS --- */
    .btn {
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 600;
        font-size: 14px;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: var(--transition);
        text-decoration: none;
        justify-content: center;
    }

    .btn-primary {
        background: var(--primary);
        color: white;
    }

    .btn-primary:hover {
        background: var(--primary-hover);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(24, 95, 165, 0.2);
    }

    .btn-danger {
        background: var(--danger);
        color: white;
    }

    .btn-danger:hover {
        background: #c53030;
    }

    .btn-outline {
        background: transparent;
        border: 1px solid var(--border);
        color: var(--text-main);
    }

    .btn-outline:hover {
        border-color: var(--primary);
        color: var(--primary);
        background: #f8fafc;
    }

    /* --- PRODUCT GRID (Replaced Table for better UX) --- */
    .product-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
        gap: 24px;
    }

    .admin-card {
        background: var(--bg-surface);
        border-radius: var(--radius);
        border: 1px solid var(--border);
        overflow: hidden;
        transition: var(--transition);
        cursor: pointer;
        display: flex;
        flex-direction: column;
    }

    .admin-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.06);
        border-color: var(--primary);
    }

    .card-img-wrap {
        height: 160px;
        position: relative;
        background: #f8fafc;
    }

    .card-img-wrap img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .card-img-count {
        position: absolute;
        bottom: 8px;
        right: 8px;
        background: rgba(0, 0, 0, 0.6);
        color: white;
        font-size: 11px;
        padding: 4px 8px;
        border-radius: 4px;
        font-weight: bold;
        backdrop-filter: blur(4px);
    }

    .card-body {
        padding: 16px;
        display: flex;
        flex-direction: column;
        flex: 1;
    }

    .card-cat {
        font-size: 11px;
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 1px;
        font-weight: bold;
        margin-bottom: 4px;
    }

    .card-title {
        font-size: 15px;
        font-weight: 600;
        margin-bottom: 8px;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .card-price {
        font-size: 18px;
        color: var(--primary);
        font-weight: 700;
        margin-top: auto;
    }

    .card-actions {
        padding: 12px 16px;
        border-top: 1px solid var(--border);
        display: flex;
        gap: 8px;
    }

    /* --- MODAL --- */
    .modal-overlay {
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.6);
        backdrop-filter: blur(4px);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2000;
        opacity: 0;
        pointer-events: none;
        transition: var(--transition);
        padding: 20px;
    }

    .modal-overlay.active {
        opacity: 1;
        pointer-events: all;
    }

    .modal {
        background: var(--bg-surface);
        width: 100%;
        max-width: 800px;
        border-radius: var(--radius);
        padding: 30px;
        transform: translateY(20px);
        transition: var(--transition);
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
    }

    .modal-overlay.active .modal {
        transform: translateY(0);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        border-bottom: 1px solid var(--border);
        padding-bottom: 16px;
    }

    .close-btn {
        font-size: 24px;
        color: var(--text-muted);
        transition: var(--transition);
    }

    .close-btn:hover {
        color: var(--danger);
        transform: rotate(90deg);
    }

    .form-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
        margin-bottom: 24px;
    }

    .form-group {
        display: flex;
        flex-direction: column;
        gap: 6px;
    }

    .form-group.full {
        grid-column: 1 / -1;
    }

    label {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-muted);
    }

    /* --- IMAGE MANAGER --- */
    .image-manager {
        border: 1px dashed var(--border);
        border-radius: 8px;
        padding: 16px;
        background: #f8fafc;
    }

    .img-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 12px;
        margin-bottom: 16px;
    }

    .img-preview-card {
        position: relative;
        border-radius: 6px;
        overflow: hidden;
        border: 2px solid transparent;
        background: white;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .img-preview-card.is-main {
        border-color: var(--primary);
    }

    .img-preview-card img {
        width: 100%;
        height: 100px;
        object-fit: cover;
        display: block;
    }

    .img-actions {
        display: flex;
        justify-content: space-between;
        padding: 6px;
        background: white;
        border-top: 1px solid var(--border);
        font-size: 11px;
        align-items: center;
    }

    .img-actions label {
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 11px;
        font-weight: normal;
        color: var(--primary);
    }

    .btn-del-img {
        color: var(--danger);
        font-size: 14px;
    }

    .upload-zone {
        border: 2px dashed var(--primary);
        background: rgba(24, 95, 165, 0.05);
        padding: 20px;
        text-align: center;
        border-radius: 8px;
        cursor: pointer;
        transition: var(--transition);
    }

    .upload-zone:hover {
        background: rgba(24, 95, 165, 0.1);
    }

    .upload-zone input[type="file"] {
        display: none;
    }

    /* --- ALERT --- */
    .alert {
        padding: 16px 20px;
        border-radius: 8px;
        margin-bottom: 24px;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .alert.success {
        background: #dcfce7;
        color: #166534;
        border: 1px solid #bbf7d0;
    }

    .alert.error {
        background: #fee2e2;
        color: #991b1b;
        border: 1px solid #fecaca;
    }

    /* --- RESPONSIVE --- */
    @media (max-width: 768px) {
        body {
            flex-direction: column;
        }

        .sidebar {
            width: 100%;
            height: auto;
            position: static;
            border-right: none;
            border-bottom: 1px solid var(--border);
        }

        .nav-links {
            flex-direction: row;
            overflow-x: auto;
            padding: 10px 20px;
        }

        .nav-link {
            white-space: nowrap;
        }

        .main-content {
            padding: 20px;
        }

        .form-grid {
            grid-template-columns: 1fr;
        }
    }
    </style>
</head>

<body>

    <aside class="sidebar">
        <div class="sidebar-header">
            <h2>B-A Admin</h2>
            <p style="font-size: 12px; color: var(--text-muted); margin-top: 5px;">Store Management</p>
        </div>
        <nav class="nav-links">
            <a href="admin.php" class="nav-link active"><i class="ti ti-package"></i> Products</a>
            <a href="index.php" class="nav-link" target="_blank"><i class="ti ti-building-store"></i> View Live
                Store</a>
        </nav>
    </aside>

    <main class="main-content">
        <div class="top-bar">
            <div>
                <h1 style="font-size: 28px; margin-bottom: 4px;">Product Inventory</h1>
                <p style="color: var(--text-muted);">Manage your catalog and images.</p>
            </div>
            <button class="btn btn-primary" onclick="openModal('add')">
                <i class="ti ti-plus"></i> Add New Product
            </button>
        </div>

        <?php if ($message): ?>
        <div class="alert <?php echo $messageType; ?>">
            <i class="ti <?php echo $messageType === 'success' ? 'ti-check' : 'ti-alert-triangle'; ?>"></i>
            <?php echo $message; ?>
        </div>
        <?php endif; ?>

        <div class="product-grid">
            <?php if (count($products) > 0): ?>
            <?php foreach ($products as $p): ?>
            <article class="admin-card"
                onclick='openModal("edit", <?php echo json_encode($p, JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>
                <div class="card-img-wrap">
                    <img src="<?php echo htmlspecialchars($p['main_img']); ?>" alt="Product">
                    <?php if(count($p['img_array']) > 1): ?>
                    <span class="card-img-count"><i class="ti ti-photo"></i>
                        <?php echo count($p['img_array']); ?></span>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <span class="card-cat"><?php echo htmlspecialchars($p['cat']); ?></span>
                    <h3 class="card-title"><?php echo htmlspecialchars($p['name']); ?></h3>
                    <div class="card-price">
                        $<?php echo number_format($p['price'], 2); ?>
                        <?php if($p['oldPrice'] > 0): ?>
                        <span
                            style="text-decoration: line-through; color: var(--text-muted); font-size: 12px; font-weight: normal; margin-left: 5px;">$<?php echo number_format($p['oldPrice'], 2); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="card-actions" onclick="event.stopPropagation();">
                    <button class="btn btn-outline" style="flex:1;"
                        onclick='openModal("edit", <?php echo json_encode($p, JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>
                        <i class="ti ti-edit"></i> Edit
                    </button>
                    <form method="POST" style="display: inline;"
                        onsubmit="return confirm('Delete this product permanently?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
                        <button type="submit" class="btn btn-danger"><i class="ti ti-trash"></i></button>
                    </form>
                </div>
            </article>
            <?php endforeach; ?>
            <?php else: ?>
            <div
                style="grid-column: 1/-1; text-align: center; padding: 60px; background: white; border-radius: var(--radius); border: 1px dashed var(--border);">
                <i class="ti ti-package-off" style="font-size: 48px; color: var(--border); margin-bottom: 16px;"></i>
                <h3 style="color: var(--text-main);">No products found</h3>
                <p style="color: var(--text-muted); margin-top: 8px;">Click "Add New Product" to populate your store.
                </p>
            </div>
            <?php endif; ?>
        </div>
    </main>

    <div class="modal-overlay" id="productModal">
        <div class="modal">
            <div class="modal-header">
                <h3 id="modalTitle">Add New Product</h3>
                <button class="close-btn" onclick="closeModal()"><i class="ti ti-x"></i></button>
            </div>

            <form method="POST" id="productForm" enctype="multipart/form-data">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="productId" value="">

                <div class="form-grid">
                    <div class="form-group full">
                        <label>Product Name</label>
                        <input type="text" name="name" id="productName" required
                            placeholder="e.g. Ergonomic Office Chair">
                    </div>

                    <div class="form-group">
                        <label>Category</label>
                        <select name="cat" id="productCat" required>
                            <option value="Furniture">Furniture</option>
                            <option value="Electronics">Electronics</option>
                            <option value="Appliances">Appliances</option>
                            <option value="Garden">Garden & Tools</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Star Rating (1-5)</label>
                        <input type="number" name="rating" id="productRating" min="1" max="5" value="5" required>
                    </div>

                    <div class="form-group">
                        <label>Current Price ($)</label>
                        <input type="number" name="price" id="productPrice" step="0.01" min="0" required
                            placeholder="0.00">
                    </div>

                    <div class="form-group">
                        <label>Old Price ($) <span
                                style="font-weight: normal; color: var(--text-muted);">(Optional)</span></label>
                        <input type="number" name="oldPrice" id="productOldPrice" step="0.01" min="0"
                            placeholder="0.00">
                    </div>

                    <div class="form-group full">
                        <label>Product Images (Locally Uploaded)</label>
                        <div class="image-manager">
                            <div id="existingImagesGrid" class="img-grid">
                            </div>

                            <label class="upload-zone">
                                <i class="ti ti-cloud-upload"
                                    style="font-size: 32px; color: var(--primary); margin-bottom: 10px;"></i>
                                <p style="font-weight: 600; color: var(--primary);">Click to select files</p>
                                <p style="font-size: 12px; color: var(--text-muted);">JPG, PNG, WEBP (Multiple allowed)
                                </p>
                                <input type="file" name="upload_images[]" id="imageInput" multiple accept="image/*"
                                    onchange="previewNewImages(this)">
                            </label>

                            <div id="newImagesPreview"
                                style="display:flex; gap:10px; margin-top:16px; overflow-x:auto;"></div>
                        </div>
                    </div>

                    <div class="form-group full">
                        <label>Promo Badge <span style="font-weight: normal; color: var(--text-muted);">(e.g. SALE, HOT,
                                20% OFF)</span></label>
                        <input type="text" name="badge" id="productBadge" placeholder="Leave blank for none">
                    </div>

                    <div class="form-group full">
                        <label>Description</label>
                        <textarea name="desc" id="productDesc" rows="3" required
                            placeholder="Short product description..."></textarea>
                    </div>
                </div>

                <div
                    style="display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid var(--border); padding-top: 20px;">
                    <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn"><i class="ti ti-device-floppy"></i>
                        Save Product</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    const modal = document.getElementById('productModal');
    const formTitle = document.getElementById('modalTitle');
    const formAction = document.getElementById('formAction');
    const submitBtn = document.getElementById('submitBtn');

    // Form Elements
    const fId = document.getElementById('productId');
    const fName = document.getElementById('productName');
    const fCat = document.getElementById('productCat');
    const fPrice = document.getElementById('productPrice');
    const fOldPrice = document.getElementById('productOldPrice');
    const fRating = document.getElementById('productRating');
    const fBadge = document.getElementById('productBadge');
    const fDesc = document.getElementById('productDesc');
    const existingGrid = document.getElementById('existingImagesGrid');
    const newPreview = document.getElementById('newImagesPreview');
    const fileInput = document.getElementById('imageInput');

    function openModal(type, data = null) {
        // Reset Visuals
        document.getElementById('productForm').reset();
        existingGrid.innerHTML = '';
        newPreview.innerHTML = '';
        fileInput.value = '';

        if (type === 'add') {
            formTitle.innerText = "Add New Product";
            formAction.value = "add";
            submitBtn.innerHTML = '<i class="ti ti-plus"></i> Add Product';
            fId.value = '';
        } else if (type === 'edit' && data) {
            formTitle.innerText = "Edit Product";
            formAction.value = "edit";
            submitBtn.innerHTML = '<i class="ti ti-device-floppy"></i> Update Product';

            // Populate Text Fields
            fId.value = data.id;
            fName.value = data.name;
            fCat.value = data.cat;
            fPrice.value = data.price;
            fOldPrice.value = data.oldPrice > 0 ? data.oldPrice : '';
            fRating.value = data.rating;
            fBadge.value = data.badge;
            fDesc.value = data.desc;

            // Populate Existing Images Grid
            if (data.img_array && data.img_array.length > 0) {
                data.img_array.forEach((imgUrl, index) => {
                    const isMain = index === 0;
                    const card = document.createElement('div');
                    card.className = `img-preview-card ${isMain ? 'is-main' : ''}`;
                    card.innerHTML = `
                        <input type="hidden" name="existing_images[]" value="${imgUrl}">
                        <img src="${imgUrl}" alt="Gallery Image">
                        <div class="img-actions">
                            <label title="Set as Main Image">
                                <input type="radio" name="main_image" value="${imgUrl}" ${isMain ? 'checked' : ''} onclick="updateMainVisual(this)"> Main
                            </label>
                            <button type="button" class="btn-del-img" onclick="markForDeletion(this, '${imgUrl}')" title="Delete Image">
                                <i class="ti ti-trash"></i>
                            </button>
                        </div>
                    `;
                    existingGrid.appendChild(card);
                });
            } else {
                existingGrid.innerHTML =
                    '<p style="grid-column: 1/-1; color: var(--text-muted); font-size: 13px;">No existing images.</p>';
            }
        }
        modal.classList.add('active');
    }

    function closeModal() {
        modal.classList.remove('active');
    }

    // Modal Background Click
    modal.addEventListener('click', (e) => {
        if (e.target === modal) closeModal();
    });

    // Image Manager specific logic
    function updateMainVisual(radioInput) {
        document.querySelectorAll('.img-preview-card').forEach(card => card.classList.remove('is-main'));
        radioInput.closest('.img-preview-card').classList.add('is-main');
    }

    function markForDeletion(btn, imgUrl) {
        const card = btn.closest('.img-preview-card');
        // Create a hidden input telling PHP to delete this file
        const deleteInput = document.createElement('input');
        deleteInput.type = 'hidden';
        deleteInput.name = 'remove_images[]';
        deleteInput.value = imgUrl;
        document.getElementById('productForm').appendChild(deleteInput);

        // Remove from UI
        card.remove();

        // If they deleted the main image, make the first remaining one the main image automatically
        const remainingRadios = existingGrid.querySelectorAll('input[type="radio"]');
        if (remainingRadios.length > 0) {
            let hasChecked = false;
            remainingRadios.forEach(r => {
                if (r.checked) hasChecked = true;
            });
            if (!hasChecked) {
                remainingRadios[0].checked = true;
                updateMainVisual(remainingRadios[0]);
            }
        }
    }

    // Preview newly selected files before upload
    function previewNewImages(input) {
        newPreview.innerHTML = '';
        if (input.files) {
            Array.from(input.files).forEach(file => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.style =
                        "width: 60px; height: 60px; object-fit: cover; border-radius: 4px; border: 2px solid var(--primary);";
                    newPreview.appendChild(img);
                }
                reader.readAsDataURL(file);
            });
        }
    }
    </script>
</body>

</html>