<?php
header("Content-Type: application/json");
require_once '../config/db.php';

$id = intval($_POST['id']);
$title = $_POST['story_title'];
$target_type = $_POST['target_type'];
$target_id = intval($_POST['target_id']);
$start = $_POST['start_date'];
$end = $_POST['end_date'];

// 1. Fetch current image for replacement
$curr = $conn->query("SELECT thumbnail_image FROM stories WHERE id = $id")->fetch_assoc();
$thumb_path = $curr['thumbnail_image'];

// 2. Handle New Upload
if (isset($_FILES['thumbnail_image']) && $_FILES['thumbnail_image']['error'] == 0) {
    if (!empty($curr['thumbnail_image']) && file_exists("../" . $curr['thumbnail_image'])) {
        @unlink("../" . $curr['thumbnail_image']);
    }

    $ext = pathinfo($_FILES['thumbnail_image']['name'], PATHINFO_EXTENSION);
    $filename = "story_" . time() . "." . $ext;
    if (move_uploaded_file($_FILES['thumbnail_image']['tmp_name'], "../uploads/stories/" . $filename)) {
        $thumb_path = "uploads/stories/" . $filename;
    }
}

// 3. Update Database
$sql = "UPDATE stories SET story_title = ?, target_type = ?, target_id = ?, thumbnail_image = ?, start_date = ?, end_date = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssisssi", $title, $target_type, $target_id, $thumb_path, $start, $end, $id);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Story updated successfully! Redirecting in 2s...."]);
} else {
    echo json_encode(["success" => false, "message" => "Database Error: " . $conn->error]);
}