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

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

$id = intval($_GET['id']);
// Fetch existing story data
$story_res = $conn->query("SELECT * FROM stories WHERE id = $id");
$story = $story_res->fetch_assoc();

if (!$story) { die("Story not found."); }

// 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>Edit 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 */
        .sidebar { width: 280px; background: var(--sidebar-bg); height: 100vh; position: fixed; color: #fff; }
        .logo-area { padding: 30px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .menu-link { display: block; padding: 18px 25px; color: #fff; text-decoration: none; border-bottom: 1px solid rgba(255,255,255,0.1); }
        
        .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: 900px; margin: auto; }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; }
        
        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; }
        
        /* Vertical 9:16 Preview */
        .story-preview-container { width: 250px; height: 250px; background: #eee; border: 2px dashed #ccc; border-radius: 12px; margin-bottom: 15px; overflow: hidden; display: flex; align-items: center; justify-content: center; position: relative; }
        #storyPrev { width: 100%; height: 100%; object-fit: cover; }
        
        .btn-update { background: var(--accent); color: #fff; border: none; padding: 15px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; margin-top: 25px; font-size: 16px; }
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; display: none; }
    </style>
</head>
<body>

<div class="sidebar">
    <div class="logo-area"><h2>GROVIA</h2></div>
    <a href="manage-stories.php" class="menu-link">← Back to Stories</a>
</div>

<div class="main-content">
    <div class="form-card">
        <h2 style="margin-top:0;">Edit Story: <?php echo htmlspecialchars($story['story_title']); ?></h2>
        <div id="msg" class="alert"></div>

        <form id="editStoryForm" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $story['id']; ?>">
            
            <div class="form-grid">
                <div>
                    <label>Story ID</label>
                    <input type="text" value="<?php echo $story['story_id']; ?>" readonly style="background:#f9f9f9; color:var(--accent); font-weight:bold;">
                </div>
                <div>
                    <label>Story Title</label>
                    <input type="text" name="story_title" value="<?php echo htmlspecialchars($story['story_title']); ?>" required>
                </div>
                <div>
                    <label>Target Type</label>
                    <select name="target_type" id="targetType" onchange="updateTargetList()">
                        <option value="category" <?php echo ($story['target_type'] == 'category') ? 'selected' : ''; ?>>Category</option>
                        <option value="sub_category" <?php echo ($story['target_type'] == 'sub_category') ? 'selected' : ''; ?>>Sub-Category</option>
                    </select>
                </div>
                <div>
                    <label>Target Directory</label>
                    <select name="target_id" id="targetId" required>
                        </select>
                </div>
                <div>
                    <label>Start Date</label>
                    <input type="date" name="start_date" value="<?php echo $story['start_date']; ?>" required>
                </div>
                <div>
                    <label>End Date</label>
                    <input type="date" name="end_date" value="<?php echo $story['end_date']; ?>" required>
                </div>
            </div>

            <div style="margin-top:30px; display: flex; gap: 30px; align-items: flex-start;">
                <div>
                    <label>Preview Thumbnail</label>
                    <div class="story-preview-container">
                        <img id="storyPrev" src="<?php echo $story['thumbnail_image']; ?>">
                    </div>
                </div>
                <div style="flex: 1;">
                    <label>Update Thumbnail</label>
                    <input type="file" name="thumbnail_image" id="storyInp" accept="image/*" style="margin-bottom:10px;">
                    <p style="font-size:12px; color:#999;">Select a new image to replace the current asset.</p>
                </div>
            </div>

            <button type="submit" class="btn-update">Save Story Changes</button>
        </form>
    </div>
</div>

<script>
const categories = <?php echo json_encode($categories->fetch_all(MYSQLI_ASSOC)); ?>;
const subCategories = <?php echo json_encode($sub_categories->fetch_all(MYSQLI_ASSOC)); ?>;
const currentTargetId = <?php echo $story['target_id']; ?>;

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];
        if(item.id == currentTargetId) opt.selected = true;
        targetSelect.appendChild(opt);
    });
}

// Initial Population
updateTargetList();

// Preview logic
document.getElementById('storyInp').onchange = evt => {
    const [file] = evt.target.files;
    if (file) { document.getElementById('storyPrev').src = URL.createObjectURL(file); }
}

document.getElementById('editStoryForm').onsubmit = async (e) => {
    e.preventDefault();
    const res = await fetch('api/update-story.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 ? "alert-success" : "alert-error");
    msg.innerText = data.message;
    msg.style.background = data.success ? "#d4edda" : "#f8d7da";
    if(data.success) { setTimeout(() => { window.location.href = 'manage-stories.php'; }, 1500); }
};
</script>
</body>
</html>