<?php 
session_start();
require_once 'config/auth_check.php';
require_once 'config/db.php';

if (!isset($_GET['id'])) {
    header("Location: manage-templates.php");
    exit;
}

$id = intval($_GET['id']);
$res = $conn->query("SELECT * FROM templates WHERE id = $id");
$data = $res->fetch_assoc();

if (!$data) {
    die("Template not found.");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin - Edit Template <?php echo $data['template_id']; ?></title>
    <link rel="stylesheet" href="assets/css/admin.css">
    <style>
        .preview-container { width: 100%; height: 120px; border: 1px solid #ddd; background: #f9f9f9; display: flex; align-items: center; justify-content: center; overflow: hidden; margin-bottom: 5px; border-radius: 5px; }
        .preview-container img { max-width: 100%; max-height: 100%; object-fit: contain; }
        .layer-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-top: 15px; }
        .layer-card { background: #fff; border: 1px solid #eee; padding: 10px; border-radius: 8px; }
        .current-label { font-size: 10px; color: #27ae60; font-weight: bold; text-transform: uppercase; margin-bottom: 5px; display: block; }
        .preview-container { position: relative; }
    .del-btn {
        position: absolute;
        top: 5px;
        right: 5px;
        background: rgba(231, 76, 60, 0.9);
        color: white;
        border: none;
        border-radius: 50%;
        width: 22px;
        height: 22px;
        cursor: pointer;
        font-weight: bold;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10;
    }
    .del-btn:hover { background: #c0392b; }
    .empty-msg { color: #ccc; font-size: 10px; }

        .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>

<div class="sidebar">
    <h3>Grovia Admin</h3>
    <a href="manage-templates.php">Manage Templates</a>
    <a href="add-template.php">Add Template</a>
</div>

<div class="main">
    <h2>Edit Template: <span style="color:#3498db;"><?php echo $data['template_id']; ?></span></h2>
    <div id="msg" class="alert" style="display:none;"></div>

    <form id="editTemplateForm" enctype="multipart/form-data">
        <input type="hidden" name="id" value="<?php echo $data['id']; ?>">
        
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px;">
            <div>
                <label>Category (Locked)</label>
                <input type="text" value="<?php echo $data['category_name']; ?>" disabled>
            </div>
            <div>
                <label>Sub-Category (Locked)</label>
                <input type="text" value="<?php echo $data['sub_category_name']; ?>" disabled>
            </div>
            <div>
                <label>Template Rate (₹)</label>
                <input type="number" name="template_rate" value="<?php echo (int)$data['template_rate']; ?>" required>
            </div>
        </div>

        <h3 style="margin-top: 30px; border-bottom: 1px solid #eee; padding-bottom: 10px;">Update Visual Assets</h3>
        <p style="font-size: 12px; color: #666;">Leave file inputs empty to keep the current version.</p>

        <div class="layer-grid">
    <div class="layer-card" id="card_thumb">
        <span class="current-label">Thumbnail</span>
        <div class="preview-container" id="prev_thumb">
            <img src="<?php echo $data['thumbnail_image']; ?>" id="img_thumb">
            <button type="button" class="del-btn" onclick="markForDeletion('thumbnail_image', 'thumb')">&times;</button>
        </div>
        <input type="file" name="thumbnail_image" onchange="previewImage(this, 'prev_thumb')">
        <input type="hidden" name="delete_thumbnail_image" id="del_thumb" value="0">
    </div>

    <div class="layer-card" id="card_l0">
        <span class="current-label">Layer 0 (Base)</span>
        <div class="preview-container" id="prev_l0">
            <img src="<?php echo $data['layer_0']; ?>" id="img_l0">
            <button type="button" class="del-btn" onclick="markForDeletion('layer_0', 'l0')">&times;</button>
        </div>
        <input type="file" name="layer_0" onchange="previewImage(this, 'prev_l0')">
        <input type="hidden" name="delete_layer_0" id="del_l0" value="0">
    </div>

    <?php for($i=1; $i<=3; $i++): 
        $path = $data['layer_'.$i];
    ?>
    <div class="layer-card" id="card_l<?php echo $i; ?>">
        <span class="current-label">Layer <?php echo $i; ?></span>
        <div class="preview-container" id="prev_l<?php echo $i; ?>">
            <?php if(!empty($path)): ?>
                <img src="<?php echo $path; ?>" id="img_l<?php echo $i; ?>">
                <button type="button" class="del-btn" onclick="markForDeletion('layer_<?php echo $i; ?>', 'l<?php echo $i; ?>')">&times;</button>
            <?php else: ?>
                <span class="empty-msg">Empty Layer</span>
            <?php endif; ?>
        </div>
        <input type="file" name="layer_<?php echo $i; ?>" onchange="previewImage(this, 'prev_l<?php echo $i; ?>')">
        <input type="hidden" name="delete_layer_<?php echo $i; ?>" id="del_l<?php echo $i; ?>" value="0">
    </div>
    <?php endfor; ?>
</div>

        <button type="submit" style="margin-top: 30px; background: #3498db; width: 100%; padding: 15px; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">
            Update GVT Template Data
        </button>
    </form>
</div>

<script>
// for deleteing of image

function markForDeletion(fieldName, shortId) {
    if(confirm('Delete this asset and clear from database?')) {
        // Set the hidden flag to 1
        document.getElementById('del_' + shortId).value = "1";
        // Hide the image and button
        const container = document.getElementById('prev_' + shortId);
        if(container.querySelector('img')) container.querySelector('img').style.display = 'none';
        if(container.querySelector('.del-btn')) container.querySelector('.del-btn').style.display = 'none';
        // Show empty message
        if(!container.querySelector('.empty-msg')) {
            const msg = document.createElement('span');
            msg.className = 'empty-msg';
            msg.innerText = 'Marked for removal';
            container.appendChild(msg);
        }
    }
}

// for preview function
function previewImage(input, containerId) {
    const container = document.getElementById(containerId);
    let img = container.querySelector('img');
    const span = container.querySelector('span');

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

document.getElementById('editTemplateForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button');
    btn.innerText = "Updating...";
    btn.disabled = true;

    const res = await fetch("api/update-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;
    
    btn.innerText = "Update GVT Template Data";
    btn.disabled = false;
    window.scrollTo(0,0);
};
</script>
</body>
</html>