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

// 1. Generate the next Story ID (e.g., GVST0001)
$res = $conn->query("SELECT MAX(id) as last_id FROM stories");
$row = $res->fetch_assoc();
$next_num = ($row['last_id'] ?? 0) + 1;
$story_id = "GVST" . str_pad($next_num, 4, '0', STR_PAD_LEFT);

// 2. Fetch Categories and Sub-Categories for the dynamic selection
$categories = $conn->query("SELECT id, category_name FROM categories WHERE status='Active'");
$sub_categories = $conn->query("SELECT id, sub_category_name FROM sub_categories WHERE status='Active'");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Story | Grovia Admin</title>
    <style>
        :root { --sidebar-bg: #3b4368; --accent: #3498db; --bg: #f4f7f6; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg); display: flex; }
        .sidebar { width: 280px; background: var(--sidebar-bg); height: 100vh; position: fixed; color: #fff; }
        .main-content { margin-left: 280px; width: 100%; padding: 40px; }
        .form-card { background: #fff; padding: 35px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 800px; margin: auto; }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #444; font-size: 13px; text-transform: uppercase; }
        input, select { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; }
        .btn-submit { background: #2ecc71; color: #fff; border: none; padding: 15px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; margin-top: 20px; font-size: 16px; }
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; display: none; }

    /* Add these styles to your existing <style> block */
    .story-preview-container {
        width: 250px;
        height: 250px; /* 9:16 Aspect Ratio */
        background: #eee;
        border: 2px dashed #ccc;
        border-radius: 12px;
        margin-bottom: 15px;
        overflow: hidden;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    #storyPrev {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: none; /* Hidden until image is selected */
    }

    #no-image-text {
        color: #999;
        font-size: 12px;
        font-weight: bold;
        text-transform: uppercase;
    }

    .file-upload-wrapper {
        position: relative;
        background: #f8f9fa;
        border: 1px solid #ddd;
        padding: 10px;
        border-radius: 6px;
    }

    .upload-hint {
        font-size: 11px;
        color: #777;
        margin-top: 5px;
        }
</style>
</head>
<body>

<div class="sidebar">
    <div style="padding:30px; text-align:center;"><h2>GROVIA</h2></div>
    <a href="manage-stories.php" style="display:block; padding:18px 25px; color:#fff; text-decoration:none;">← Back to Stories</a>
</div>

<div class="main-content">
    <div class="form-card">
        <h2 style="margin-top:0;">Create New Story Feed</h2>
        <div id="msg" class="alert"></div>

        <form id="addStoryForm" enctype="multipart/form-data">
            <div class="form-grid">
                <div>
                    <label>Story ID (System Generated)</label>
                    <input type="text" name="story_id" value="<?php echo $story_id; ?>" readonly style="background:#f9f9f9; font-weight:bold; color:var(--accent);">
                </div>
                <div>
                    <label>Story Title</label>
                    <input type="text" name="story_title" placeholder="e.g. New Arrivals 2026" required>
                </div>
                <div>
                    <label>Target Type</label>
                    <select name="target_type" id="targetType" onchange="updateTargetList()">
                        <option value="category">Category</option>
                        <option value="sub_category">Sub-Category</option>
                    </select>
                </div>
                <div>
                    <label>Select Target Directory</label>
                    <select name="target_id" id="targetId" required>
                        </select>
                </div>
                <div>
                    <label>Start Date</label>
                    <input type="date" name="start_date" required>
                </div>
                <div>
                    <label>End Date</label>
                    <input type="date" name="end_date" required>
                </div>
            </div>

            <div style="margin-top:20px;">
                <label>Story Thumbnail</label>
                
                <div class="story-preview-container">
                    <img id="storyPrev" src="assets/img/story-placeholder.png" alt="Preview">
                    <div id="no-image-text">No Image Selected</div>
                </div>

                <div class="file-upload-wrapper">
                    <input type="file" name="thumbnail_image" id="storyInp" accept="image/*" required>
                    <div class="upload-hint">Click to upload vertical asset</div>
                </div>
            </div>

            <button type="submit" class="btn-submit">Publish Story Feed</button>
        </form>
    </div>
</div>

<script>
// Data for dynamic dropdowns
const categories = <?php echo json_encode($categories->fetch_all(MYSQLI_ASSOC)); ?>;
const subCategories = <?php echo json_encode($sub_categories->fetch_all(MYSQLI_ASSOC)); ?>;

function updateTargetList() {
    const type = document.getElementById('targetType').value;
    const targetSelect = document.getElementById('targetId');
    targetSelect.innerHTML = '';
    
    const data = (type === 'category') ? categories : subCategories;
    const labelKey = (type === 'category') ? 'category_name' : 'sub_category_name';

    data.forEach(item => {
        const opt = document.createElement('option');
        opt.value = item.id;
        opt.innerText = item[labelKey];
        targetSelect.appendChild(opt);
    });
}

// Initial call
updateTargetList();

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

    const res = await fetch('api/save-story.php', {
        method: 'POST',
        body: new FormData(e.target)
    });
    
    const result = await res.json();
    const msg = document.getElementById('msg');
    msg.style.display = "block";
    msg.className = "alert " + (result.success ? "alert-success" : "alert-error");
    msg.innerText = result.message;
    msg.style.background = result.success ? "#d4edda" : "#f8d7da";
    
    if(result.success) {
        setTimeout(() => { window.location.href = 'manage-stories.php'; }, 1500);
    } else {
        btn.innerText = "Publish Story Feed";
        btn.disabled = false;
    }
};

// Update the JavaScript logic to handle the preview
    document.getElementById('storyInp').onchange = evt => {
        const [file] = evt.target.files;
        if (file) {
            const preview = document.getElementById('storyPrev');
            const placeholderText = document.getElementById('no-image-text');
            
            preview.src = URL.createObjectURL(file);
            preview.style.display = 'block';
            if(placeholderText) placeholderText.style.display = 'none';
        }
    }
</script>
</body>
</html>