<?php 
session_start();
require_once 'config/auth_check.php';
require_once 'config/db.php';
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin - Add Banner</title>
    <link rel="stylesheet" href="assets/css/admin.css">
    <style>
        .banner-preview {
            width: 100%;
            height: 200px;
            border: 2px dashed #ddd;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin-bottom: 15px;
            background: #f9f9f9;
        }
        #previewImg { max-width: 100%; max-height: 100%; display: none; }

        .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>Add Promotion Banner</h2>
    <div id="msg" class="alert"></div>

    <form id="addBannerForm" enctype="multipart/form-data">
        <label>Banner Image (Wide Aspect Ratio Recommended)</label>
        <div class="banner-preview">
            <span id="label">Preview will appear here</span>
            <img id="previewImg" src="">
        </div>
        <input type="file" name="banner_image" id="bannerInp" accept="image/*" required>

        <label>1. Target Category</label>
            <select id="targetCat" onchange="fetchSubCats()" required>
                <option value="">-- Select Category --</option>
                <?php 
                $cats = $conn->query("SELECT id, category_name FROM categories WHERE status='Active'");
                while($c = $cats->fetch_assoc()): 
                ?>
                    <option value="<?php echo $c['id']; ?>" data-name="<?php echo $c['category_name']; ?>">
                        <?php echo $c['category_name']; ?>
                    </option>
                <?php endwhile; ?>
            </select>

            <label>2. Target Sub-Category</label>
            <select id="targetSub" onchange="updateDirPath()" required>
                <option value="">-- Select Category First --</option>
            </select>

        <input type="hidden" name="target_url" id="finalDirPath">

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px;">
            <div>
                <label>Start Date</label>
                <input type="date" name="start_date" required value="<?php echo date('Y-m-d'); ?>">
            </div>
            <div>
                <label>End Date</label>
                <input type="date" name="end_date" required>
            </div>
        </div>

        <label>Status</label>
        <select name="status">
            <option value="Active">Active</option>
            <option value="Not Active">Not Active</option>
        </select>

        <button type="submit" style="margin-top: 20px; background: #3498db;">Upload Banner</button>
        <br>
        <p><b>Note: </b> The Banner will get In-Active from user app automatically after the end date, even if you forgot to make it inactive </p>
    </form>
</div>

<script>
    // Image Preview
    document.getElementById('bannerInp').onchange = e => {
        const [file] = e.target.files;
        if (file) {
            document.getElementById('previewImg').src = URL.createObjectURL(file);
            document.getElementById('previewImg').style.display = 'block';
            document.getElementById('label').style.display = 'none';
        }
    };

    // AJAX Submission
    document.getElementById('addBannerForm').onsubmit = async (e) => {
        e.preventDefault();
        const res = await fetch("api/save-banner.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();
    };
</script>


<script>
async function fetchSubCats() {
    const catId = document.getElementById('targetCat').value;
    const subSelect = document.getElementById('targetSub');
    
    if(!catId) return;

    const res = await fetch(`api/get-subcategories.php?cat_id=${catId}`);
    const data = await res.json();

    subSelect.innerHTML = '<option value="">-- Select Sub-Category --</option>';
    data.forEach(s => {
        subSelect.innerHTML += `<option value="${s.id}" data-name="${s.sub_category_name}">${s.sub_category_name}</option>`;
    });
}

function updateDirPath() {
    const catSelect = document.getElementById('targetCat');
    const subSelect = document.getElementById('targetSub');
    
    const catName = catSelect.options[catSelect.selectedIndex].getAttribute('data-name');
    const subName = subSelect.options[subSelect.selectedIndex].getAttribute('data-name');

    // Convert names to folder-safe strings
    const catFolder = catName.replace(/[^A-Za-z0-9_\-]/g, '_');
    const subFolder = subName.replace(/[^A-Za-z0-9_\-]/g, '_');

    // Construct the path: uploads/templates/Category/SubCategory/
    const fullPath = `uploads/templates/${catFolder}/${subFolder}/`;
    document.getElementById('finalDirPath').value = fullPath;
}
</script>
</body>
</html>