<?php

require_once __DIR__ . '/../config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ----------------------
// AUTH CHECK
// ----------------------

if (
    !isset($_SESSION['admin_logged_in']) ||
    $_SESSION['admin_logged_in'] !== true
) {
    header('Location: login.php');
    exit;
}

// ----------------------
// CURRENT USER
// ----------------------

$userId = $_SESSION['admin_user_id'] ?? 0;

// ----------------------
// GET ALERT ID
// ----------------------

$id = (int)($_GET['id'] ?? 0);

if ($id <= 0) {
    die('Invalid alert ID.');
}

// ----------------------
// LOAD ALERT
// ----------------------

$stmt = $pdo->prepare("
    SELECT *
    FROM media_alerts
    WHERE id = ?
");

$stmt->execute([$id]);

$alert = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$alert) {
    die('Alert not found.');
}

// ----------------------
// CHECK ARTICLE CONTENT
// ----------------------

if (empty($alert['article_content'])) {
    die('No extracted article content available.');
}

// ----------------------
// BUILD PROMPT
// ----------------------

$prompt = "
You are writing for a UK based theme park news website.

Write an ORIGINAL article based on the news item below.

Requirements:
- 1000-1500 words
- Expand naturally with meaningful detail
- Include additional background and context where relevant
- Explore why the announcement matters to theme park fans
- Avoid repetitive phrasing
- Keep pacing varied and engaging
- Use multiple <h2> sections
- Include immersive descriptive writing where appropriate
- Human tone
- Exciting but professional
- SEO friendly
- Strictly no em dashes
- Never use the — character
- Only use standard hyphens -
- Theme park enthusiast style
- Avoid sounding like AI
- 300-800 words
- Use HTML formatting
- Include <h2> headings where suitable
- Use paragraphs only
- Do not invent facts
- Meta description must be under 160 characters
- Meta description should encourage clicks from Google
- Only use information provided in the source content
- Do not invent details
- Use <figure> and <figcaption> formatting for images where appropriate

News title:
{$alert['title']}

Source URL:
{$alert['url']}

Featured image:
{$alert['featured_image']}

Source content:
{$alert['article_content']}

Return ONLY valid JSON.

The content field must contain HTML as a JSON string.
Do not wrap the JSON in markdown.
Do not use ```json.
Do not include any explanation before or after the JSON.

Use this exact structure:

{
    \"title\": \"\",
    \"tagline\": \"\",
    \"meta_description\": \"\",
    \"content\": \"\"
}
";

// ----------------------
// OPENAI REQUEST
// ----------------------

$data = [
    'model' => 'gpt-4.1-mini',
    'response_format' => [
        'type' => 'json_object'
    ],
    'messages' => [
        [
            'role' => 'system',
            'content' => 'You are a UK theme park news writer. You must return only valid JSON. Do not use markdown code fences.'
        ],
        [
            'role' => 'user',
            'content' => $prompt
        ]
    ],
    'temperature' => 0.7
];

$ch = curl_init('https://api.openai.com/v1/chat/completions');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . OPENAI_API_KEY
]);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);

if ($response === false) {
    die('Curl error: ' . curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

$result = json_decode($response, true);

// ----------------------
// CHECK API RESPONSE
// ----------------------

if ($httpCode < 200 || $httpCode >= 300) {

    echo '<pre>';
    print_r($result);
    echo '</pre>';

    die('OpenAI API request failed.');
}

if (!isset($result['choices'][0]['message']['content'])) {

    echo '<pre>';
    print_r($result);
    echo '</pre>';

    die('No content returned from OpenAI.');
}

// ----------------------
// GET CONTENT
// ----------------------

$content = trim(
    $result['choices'][0]['message']['content']
);

$generated = json_decode($content, true);

if (json_last_error() !== JSON_ERROR_NONE) {

    echo '<pre>';
    echo 'JSON decode error: ' . json_last_error_msg() . PHP_EOL . PHP_EOL;
    echo 'Raw content returned:' . PHP_EOL;
    echo htmlspecialchars($content);
    echo '</pre>';

    die('Failed to decode generated article JSON.');
}

// ----------------------
// VALIDATE RESPONSE
// ----------------------

if (
    !$generated ||
    empty($generated['title']) ||
    empty($generated['content']) ||
    empty($generated['meta_description'])
) {

    echo '<pre>';
    print_r($generated);
    echo '</pre>';

    die('Failed to generate valid article.');
}

// ----------------------
// GENERATE SLUG
// ----------------------

function generateSlug($string)
{
    $string = iconv(
        'UTF-8',
        'ASCII//TRANSLIT//IGNORE',
        $string
    );

    $string = preg_replace(
        '/[^A-Za-z0-9 ]+/',
        '',
        $string
    );

    $string = preg_replace(
        '/\s+/',
        '-',
        $string
    );

    return strtolower(trim($string, '-'));
}

$slug = generateSlug($generated['title']);

// ----------------------
// ENSURE UNIQUE SLUG
// ----------------------

$checkStmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM posts
    WHERE slug = ?
");

$checkStmt->execute([$slug]);

if ($checkStmt->fetchColumn() > 0) {
    $slug .= '-' . time();
}

// ----------------------
// INSERT DRAFT
// ----------------------

$insertStmt = $pdo->prepare("
    INSERT INTO posts (
        title,
        tagline,
        meta_description,
        slug,
        content,
        image_path,
        post_location,
        created_by,
        status,
        created_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
");

$insertStmt->execute([
    $generated['title'],
    $generated['tagline'] ?? '',
    $generated['meta_description'],
    $slug,
    $generated['content'],
    $alert['featured_image'] ?? '',
    1,
    $userId,
    'draft'
]);

// ----------------------
// REDIRECT TO EDIT PAGE
// ----------------------

$newPostId = $pdo->lastInsertId();

header("Location: /admin/edit-post.php?id=" . $newPostId);

exit;

?>