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

$story_id = $_POST['story_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. Handle Thumbnail Upload
$thumb_path = "";
if (isset($_FILES['thumbnail_image']) && $_FILES['thumbnail_image']['error'] == 0) {
    $ext = pathinfo($_FILES['thumbnail_image']['name'], PATHINFO_EXTENSION);
    $filename = "story_" . time() . "." . $ext;
    $target = "../uploads/stories/" . $filename;
    
    if (!is_dir("../uploads/stories/")) { mkdir("../uploads/stories/", 0777, true); }

    if (move_uploaded_file($_FILES['thumbnail_image']['tmp_name'], $target)) {
        $thumb_path = "uploads/stories/" . $filename;
    }
}

// 2. Database Insert
$sql = "INSERT INTO stories (story_id, story_title, target_type, target_id, thumbnail_image, start_date, end_date) 
        VALUES (?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sssisss", $story_id, $title, $target_type, $target_id, $thumb_path, $start, $end);

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