<?php
/**
 * Admin-side preview of the AI Template Generator (same endpoint logic the
 * Flutter app calls at /api/ai/generate-template). Lets admin test the
 * Gemini key configured in App Settings without exposing it to any client.
 */
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';

apply_cors();
require_admin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['requirement']);

$pdo = getDbConnection();
$settings = $pdo->query('SELECT gemini_api_key FROM app_settings WHERE id = 1')->fetch();
$apiKey = $settings['gemini_api_key'] ?? '';

$language = clean_str($input['language'] ?? 'English');
$tone = clean_str($input['tone'] ?? 'Professional & Polite');
$eventType = clean_str($input['event_type'] ?? 'Missed Call');
$channel = clean_str($input['channel'] ?? 'WhatsApp');
$requirement = clean_str($input['requirement']);

if (!empty($apiKey)) {
    $systemPrompt = "You are an expert marketing copywriter for auto-reply SMS and WhatsApp messages. "
        . "Generate exactly 3 short, catchy auto-reply message options based on user requirements. "
        . "Use {NAME} for contact name if relevant. Keep options under 250 characters each. "
        . "Return only a numbered list (1., 2., 3.). Language: $language. Tone: $tone.";
    $userPrompt = "Requirement: $requirement. Event: $eventType. Channel: $channel.";

    $ch = curl_init('https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' . urlencode($apiKey));
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 12,
        CURLOPT_POSTFIELDS => json_encode([
            'contents' => [['parts' => [['text' => $systemPrompt . "\n\n" . $userPrompt]]]],
        ]),
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response && $httpCode === 200) {
        $json = json_decode($response, true);
        $text = $json['candidates'][0]['content']['parts'][0]['text'] ?? '';
        if ($text) {
            $items = array_values(array_filter(array_map(
                fn($line) => trim(preg_replace('/^\d+\.\s*/', '', $line)),
                explode("\n", $text)
            )));
            if (!empty($items)) {
                send_success(['messages' => array_slice($items, 0, 3), 'source' => 'gemini']);
            }
        }
    }
}

// Local fallback generator (no internet / no key required) — keeps parity with
// the original app's offline multilingual generator.
send_success(['messages' => generate_local_fallback($requirement, $language, $tone), 'source' => 'local_fallback']);

function generate_local_fallback(string $topic, string $language, string $tone): array
{
    $topic = $topic !== '' ? $topic : 'your enquiry';

    if (stripos($language, 'Hindi') !== false && stripos($language, 'Hinglish') === false) {
        return [
            "नमस्ते {NAME}! आपका कॉल मिस हो गया। $topic के बारे में जल्द संपर्क करेंगे। धन्यवाद!",
            "नमस्ते! मैं अभी व्यस्त हूँ। $topic के लिए कृपया मैसेज छोड़ें, हम जल्द संपर्क करेंगे।",
            "धन्यवाद {NAME}! $topic के संबंध में आपका कॉल मिला। हमारी टीम जल्द बात करेगी।",
        ];
    }
    if (stripos($language, 'Hinglish') !== false) {
        return [
            "Namaste {NAME}! Aapka call miss ho gaya. $topic ke baare mein hum jald contact karenge. Thank you!",
            "Hello! Abhi busy hoon. $topic ke liye kripya message karein, hum callback karenge.",
            "Thank you {NAME}! $topic ke regarding aapka call mila. Team will get back to you shortly.",
        ];
    }
    if (stripos($tone, 'Sales') !== false || stripos($tone, 'Offer') !== false) {
        return [
            "Hello {NAME}! Thanks for calling about $topic. Exclusive offer active today! Reply YES to know more.",
            "Hi {NAME}! Missed your call. Special deals available for $topic. Check our latest catalog!",
            "Thank you for reaching out about $topic. Limited-time promo running now!",
        ];
    }
    return [
        "Hello {NAME}! Thank you for your call regarding $topic. Currently unavailable, will get back shortly.",
        "Hi {NAME}! Sorry I missed your call. Regarding $topic, please leave your query here.",
        "Thank you for contacting us regarding $topic. Our team will follow up with you soon!",
    ];
}
