<?php
header('Content-Type: application/json');

require_once 'db.php'; // Ensure this is correct relative path

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Invalid request method.']);
    exit;
}

// ✅ Fetch dynamic API key from branding table
$brandingQuery = $pdo->query("SELECT openai_api_key FROM branding LIMIT 1");
$brandingData = $brandingQuery->fetch(PDO::FETCH_ASSOC);
$apiKey = $brandingData['openai_api_key'] ?? null;

if (empty($apiKey)) {
    echo json_encode([
        'error' => '⚠️ AI Generator is not configured. Please contact the system admin to add an OpenAI API key in Branding Settings.'
    ]);
    exit;
}

session_start();


if (!isset($_SESSION['logged_in_user'])) {
    echo json_encode(['error' => 'You must be logged in.']);
    exit;
}

$loggedInUser = $_SESSION['logged_in_user'];
$userQuery = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$userQuery->execute([$loggedInUser]);
$userRow = $userQuery->fetch(PDO::FETCH_ASSOC);
if (!$userRow) {
    echo json_encode(['error' => 'User not found.']);
    exit;
}

$user_id = $userRow['id'];
$tone = htmlspecialchars($_POST['tone'] ?? 'friendly');

// ✅ Check if user has hit 30 uses this month
$usageCheck = $pdo->prepare("
    SELECT COUNT(*) FROM ai_usage_log 
    WHERE user_id = ? 
    AND MONTH(used_at) = MONTH(NOW()) 
    AND YEAR(used_at) = YEAR(NOW())
");
$usageCheck->execute([$user_id]);
$usesThisMonth = $usageCheck->fetchColumn();

if ($usesThisMonth >= 30) {
    echo json_encode(['error' => '❌ You have reached your 30 AI generations for this month.']);
    exit;
}
$tone = htmlspecialchars($tone);

$prompt = "Generate a curiosity-driven headline and matching subheadline for a free landing page promoting a passive crypto income system called Starkord. The system uses crypto staking and smart contracts to deliver sustainable daily rewards, with no trading required. 

Write with a tone of $tone. The headline should be under 12 words, simple and bold. The subheadline should support the headline using light HTML formatting, and include 1–2 relevant emojis. Avoid hype or guarantees, but make it sound exciting and safe. Mention ideas like transparency, automation, or earning daily.";

$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, [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
]);

$data = [
    'model' => 'gpt-3.5-turbo',
    'messages' => [[
        'role' => 'user',
        'content' => $prompt
    ]],
    'max_tokens' => 300,
    'temperature' => 0.9
];

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo json_encode(['error' => curl_error($ch)]);
    exit;
}

curl_close($ch);

$responseData = json_decode($response, true);
$content = $responseData['choices'][0]['message']['content'] ?? '';

// 🧼 Clean output
$lines = explode("\n", $content);
$cleanHeadline = '';
$cleanSubheadline = '';

foreach ($lines as $line) {
    $line = trim($line);
    if (stripos($line, 'headline:') === 0) {
        $cleanHeadline = trim(substr($line, 9));
    } elseif (stripos($line, 'subheadline:') === 0) {
        $cleanSubheadline = trim(substr($line, 12));
    }
}

if (empty($cleanHeadline)) {
    $cleanHeadline = $lines[0] ?? '';
}
if (empty($cleanSubheadline) && isset($lines[1])) {
    $cleanSubheadline = $lines[1];
}
$logStmt = $pdo->prepare("INSERT INTO ai_usage_log (user_id) VALUES (?)");
$logStmt->execute([$user_id]);

echo json_encode([
    'headline' => $cleanHeadline,
    'subheadline' => $cleanSubheadline
]);
