<?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.');
}

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

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

Write an ORIGINAL article based on the news item below.

Requirements:
- Human tone
- Exciting but professional
- SEO friendly
- No em dashes
- 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

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

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

Return ONLY valid JSON in this exact structure:

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

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

$data = [
    'model' => 'gpt-4.1-mini',
    'messages' => [
        [
            'role' => 'user',
            'content' => $prompt
        ]
    ]
];

$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);

curl_close($ch);

$result = json_decode($response, true);

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

$content = $result['choices'][0]['message']['content'] ?? '';

$generated = json_decode($content, true);

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

if (
    !$generated ||
    empty($generated['title']) ||
    empty($generated['content']) ||
    empty($generated['meta_description'])
) {
    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,
        post_location,
        created_by,
        status,
        created_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
");

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

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

$newPostId = $pdo->lastInsertId();

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

exit;
?>