<?php
require_once '../../config.php';
require_once '../../functions.php';
require_once '../includes/ai_helper.php';

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

// Auth check
if (!isset($_SESSION['admin_id']) && !isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'POST only']);
    exit;
}

$action = $_POST['action'] ?? 'generate';
$prompt = $_POST['prompt'] ?? '';
$provider = $_POST['provider'] ?? null;
$tone = $_POST['tone'] ?? '';
$language = $_POST['language'] ?? 'English';
$char_limit = intval($_POST['char_limit'] ?? 160);

if ($action === 'generate') {
    if (empty($prompt)) {
        echo json_encode(['success' => false, 'error' => 'Please enter a topic or prompt.']);
        exit;
    }

    $full_prompt = "Create an SMS message about: $prompt\n";
    if ($tone)
        $full_prompt .= "Tone: $tone\n";
    $full_prompt .= "Language: $language\n";
    $full_prompt .= "Maximum $char_limit characters.\n";
    $full_prompt .= "Return ONLY the SMS text, nothing else.";

    $result = ai_generate_sms($full_prompt, $provider);
    echo json_encode($result);

} elseif ($action === 'test') {
    // Test connection — admin only
    if (!isset($_SESSION['admin_id'])) {
        echo json_encode(['success' => false, 'error' => 'Admin only']);
        exit;
    }
    $test_provider = $_POST['provider'] ?? '';
    $test_key = $_POST['api_key'] ?? '';
    $test_model = $_POST['model'] ?? null;

    if (empty($test_provider) || empty($test_key)) {
        echo json_encode(['success' => false, 'error' => 'Provider and API key required']);
        exit;
    }

    $result = test_ai_connection($test_provider, $test_key, $test_model);
    echo json_encode($result);

} else {
    echo json_encode(['success' => false, 'error' => 'Unknown action']);
}
?>