<?php 
session_start();
require_once 'config/auth_check.php';
require_once 'config/db.php';
// Fetch categories to populate the first dropdown
$categories = $conn->query("SELECT DISTINCT category_name FROM categories WHERE status='Active' ORDER BY category_name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin - Add New Template</title>
    <link rel="stylesheet" href="assets/css/admin.css">
    <style>
        .layer-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 15px; }
        .layer-card { background: #f8f9fa; border: 1px solid #ddd; padding: 10px; border-radius: 8px; }
        .thumb-prev { width: 100%; height: 120px; object-fit: contain; background: #eee; margin-bottom: 10px; display: none; }

        .preview-container {
            width: 100%;
            height: 150px;
            border: 2px dashed #ddd;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #fdfdfd;
            margin-bottom: 10px;
            overflow: hidden;
            position: relative;
        }
        .preview-container img {
            max-width: 100%;
            max-height: 100%;
            display: none; /* Hidden until file selected */
            object-fit: contain;
        }
        .preview-container span {
            color: #aaa;
            font-size: 12px;
            text-transform: uppercase;
        }
        .layer-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); 
            gap: 20px; 
            margin-top: 20px; 
        }
        .layer-card { 
            background: #fff; 
            border: 1px solid #eee; 
            padding: 15px; 
            border-radius: 10px; 
            box-shadow: 0 2px 5px rgba(0,0,0,0.02);
        }

        .alert { padding: 15px; margin-bottom: 20px; border-radius: 4px; text-align: center; }
    .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
    .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>

<?php include 'side-bar.php' ?>

<div class="main">
    <h2>Upload Template (GVT System)</h2>
    <div id="msg" class="alert" style="display:none;"></div>

    <form id="addTemplateForm" enctype="multipart/form-data">
        <div style="display: flex; gap: 20px;">
            <div style="flex: 1;">
                <label>Category Name</label>
                <select name="category_name" id="catName" onchange="loadSubs()" required>
                    <option value="">-- Select Category --</option>
                    <?php while($c = $categories->fetch_assoc()): ?>
                        <option value="<?php echo $c['category_name']; ?>"><?php echo $c['category_name']; ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div style="flex: 1;">
                <label>Sub-Category Name</label>
                <select name="sub_category_name" id="subName" required>
                    <option value="">-- Select Category First --</option>
                </select>
            </div>
        </div>

        <label>Template Rate</label>
        <input type="number" name="template_rate" placeholder="e.g. 5" required>

        <div style="display: flex; gap: 20px; align-items: flex-end;">
            <div style="flex: 1;">
                <label>Main Thumbnail</label>
                <div class="preview-container" id="prev_thumb">
                    <span>Thumbnail Preview</span>
                    <img src="">
                </div>
                <input type="file" name="thumbnail_image" onchange="previewImage(this, 'prev_thumb')" accept="image/*">
            </div>
        </div>

        <div class="layer-grid">
            <?php for($i=0; $i<=3; $i++): ?>
            <div class="layer-card">
                <label>Layer <?php echo $i; ?> <?php echo ($i==0) ? '(Background)' : ''; ?></label>
                <div class="preview-container" id="prev_l<?php echo $i; ?>">
                    <span>Layer <?php echo $i; ?> Preview</span>
                    <img src="">
                </div>
                <input type="file" name="layer_<?php echo $i; ?>" onchange="previewImage(this, 'prev_l<?php echo $i; ?>')" accept="image/*">
            </div>
            <?php endfor; ?>
        </div>

        <button type="submit" style="margin-top: 30px; background: #2ecc71; padding: 12px 30px;">Initialize GVT Template</button>
    </form>
</div>

<script>
// Logic to handle live previews
function previewImage(input, containerId) {
    const container = document.getElementById(containerId);
    const img = container.querySelector('img');
    const span = container.querySelector('span');

    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            img.src = e.target.result;
            img.style.display = 'block';
            span.style.display = 'none';
        }
        reader.readAsDataURL(input.files[0]);
    } else {
        img.style.display = 'none';
        span.style.display = 'block';
    }
}

async function loadSubs() {
    const catName = document.getElementById('catName').value;
    const subSelect = document.getElementById('subName');
    if(!catName) return;

    const res = await fetch(`api/get-subs-by-name.php?cat_name=${encodeURIComponent(catName)}`);
    const data = await res.json();
    
    subSelect.innerHTML = '<option value="">-- Select Sub-Category --</option>';
    data.forEach(s => {
        subSelect.innerHTML += `<option value="${s.sub_category_name}">${s.sub_category_name}</option>`;
    });
}

document.getElementById('addTemplateForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button');
    btn.innerText = "Processing GVT Layers...";
    btn.disabled = true;

    try {
        const res = await fetch("api/save-template.php", {
            method: "POST",
            body: new FormData(e.target)
        });
        const data = await res.json();
        const msg = document.getElementById('msg');
        msg.style.display = "block";
        msg.className = "alert " + (data.success ? "success" : "error");
        msg.innerText = data.message;

        if(data.success) {
            e.target.reset();
            // Clear all previews
            document.querySelectorAll('.preview-container img').forEach(img => img.style.display = 'none');
            document.querySelectorAll('.preview-container span').forEach(span => span.style.display = 'block');
        }
    } catch (err) {
        alert("An error occurred during upload.");
    } finally {
        btn.innerText = "Initialize GVT Template";
        btn.disabled = false;
    }
};
</script>
</body>
</html>