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

$categories = $conn->query("SELECT id, category_name FROM categories WHERE status='Active'");
$companies = $conn->query("SELECT id, company_name FROM company ORDER BY company_name ASC");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin - Add Sub-Category</title>
    <link rel="stylesheet" href="assets/css/admin.css">
    <style>
    .thumb-preview-wrapper {
        margin: 15px 0;
        text-align: center;
        border: 2px dashed #ddd;
        padding: 20px;
        border-radius: 8px;
        background: #f9f9f9;
        position: relative;
    }
    #thumbPreview {
        max-width: 100%;
        max-height: 200px;
        border-radius: 5px;
        display: none; /* Hidden until image is selected */
        margin: 0 auto;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .preview-label {
        color: #999;
        font-size: 14px;
        display: block;
    }

    .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 New Sub-Category</h2>
    <div id="msg" class="alert"></div>

    <form id="addSubCategoryForm" enctype="multipart/form-data">
        <label>Parent Category</label>
        <select name="cat_id" required>
            <option value="">-- Select Category --</option>
            <?php while($c = $categories->fetch_assoc()): ?>
                <option value="<?php echo $c['id']; ?>"><?php echo $c['category_name']; ?></option>
            <?php endwhile; ?>
        </select>

        <label>Sub-Category Name</label>
        <input type="text" name="sub_category_name" required>

        <label>Thumbnail Image</label>
            <div class="thumb-preview-wrapper">
                <span class="preview-label" id="previewLabel">No image selected</span>
                <img id="thumbPreview" src="" alt="Thumbnail Preview">
                <input type="file" name="thumbnail_image" id="thumbInput" accept="image/*" required style="margin-top: 10px;">
            </div>

        <label>Visibility</label>
        <select name="companies_allowed" id="subPerm" onchange="toggleSubCompanies()">
            <option value="For All">For All</option>
            <option value="For Selective Companies">For Selective Companies</option>
        </select>

        <div id="subSelectiveBox" style="display:none; margin-top:10px; padding:10px; border:1px solid #ddd;">
            <label>Select Allowed Companies:</label>
            <?php while($comp = $companies->fetch_assoc()): ?>
                <label><input type="checkbox" name="allowed_companies[]" value="<?php echo $comp['id']; ?>"> <?php echo $comp['company_name']; ?></label><br>
            <?php endwhile; ?>
        </div>

        <button type="submit" style="margin-top:20px;">Save Sub-Category</button>
    </form>
</div>

<script>
    // Logic for Thumbnail Live Preview
    const thumbInput = document.getElementById('thumbInput');
    const thumbPreview = document.getElementById('thumbPreview');
    const previewLabel = document.getElementById('previewLabel');

    thumbInput.onchange = evt => {
        const [file] = thumbInput.files;
        if (file) {
            thumbPreview.src = URL.createObjectURL(file);
            thumbPreview.style.display = 'block';
            previewLabel.style.display = 'none';
        } else {
            thumbPreview.style.display = 'none';
            previewLabel.style.display = 'block';
        }
    }

    // Existing AJAX Submission Logic
    document.getElementById('addSubCategoryForm').onsubmit = async (e) => {
        e.preventDefault();
        const res = await fetch("api/save-sub-category.php", {
            method: "POST",
            body: new FormData(e.target)
        });
        const data = await res.json();
        const msg = document.getElementById('msg');
        
        msg.className = "alert " + (data.success ? "success" : "error");
        msg.innerText = data.message;
        msg.style.display = "block";

        if(data.success) {
            e.target.reset();
            thumbPreview.style.display = 'none';
            previewLabel.style.display = 'block';
            // Hide selective box if it was open
            document.getElementById('subSelectiveBox').style.display = 'none';
        }
    };
</script>
</body>
</html>