<?php
/**
 * DEPRECATED: Same-origin proxy for legacy single ad copy generation.
 * New campaign pack endpoint: api/openai-campaign-pack.php
 * Reads OpenAI API key from Firebase RTDB:
 * clients/{clientId}/siteSettings/openaiApiKey
 */
header('Content-Type: application/json; charset=UTF-8');

require_once __DIR__ . '/firebase-rtdb-admin.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!function_exists('curl_init')) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'PHP curl extension is required.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$raw = file_get_contents('php://input');
$body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
if (!is_array($body)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON'], JSON_UNESCAPED_UNICODE);
    exit;
}

$clientId = isset($body['clientId']) ? trim((string) $body['clientId']) : '';
$product = isset($body['product']) && is_array($body['product']) ? $body['product'] : [];

if ($clientId === '' || !preg_match('/^[-A-Za-z0-9_]{1,128}$/', $clientId)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Valid clientId is required.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$productName = trim((string) ($product['name'] ?? ''));
$productDescription = trim((string) ($product['description'] ?? ''));
$salePrice = isset($product['salePrice']) && is_numeric($product['salePrice']) ? (float) $product['salePrice'] : 0.0;
$regularPrice = isset($product['regularPrice']) && is_numeric($product['regularPrice']) ? (float) $product['regularPrice'] : 0.0;
$categories = isset($product['categories']) && is_array($product['categories']) ? $product['categories'] : [];

if ($productName === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Product name is required.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootPath)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Server not configured. Copy api/firebase-admin-bootstrap.example.php to firebase-admin-bootstrap.local.php.'], JSON_UNESCAPED_UNICODE);
    exit;
}
$boot = include $bootPath;
if (!is_array($boot)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Invalid firebase-admin-bootstrap.local.php.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$saPath = isset($boot['service_account_json_path']) ? trim((string) $boot['service_account_json_path']) : '';
$dbUrl = isset($boot['firebase_database_url']) ? trim((string) $boot['firebase_database_url']) : '';
if ($saPath === '' || $dbUrl === '') {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Bootstrap missing service account path or database URL.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$tok = firebase_service_account_access_token($saPath);
if (isset($tok['error'])) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Firebase admin error: ' . $tok['error']], JSON_UNESCAPED_UNICODE);
    exit;
}
$access = $tok['access_token'];

$settingsSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/siteSettings', $access);
if (isset($settingsSnap['error'])) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Could not load site settings from Firebase.'], JSON_UNESCAPED_UNICODE);
    exit;
}
$settings = is_array($settingsSnap['data']) ? $settingsSnap['data'] : [];
$openaiKey = trim((string) ($settings['openaiApiKey'] ?? ''));
$model = trim((string) ($settings['openaiModel'] ?? 'gpt-4o-mini'));

if ($openaiKey === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'OpenAI API Key not found in Site Settings.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$catText = '';
if (!empty($categories)) {
    $safeCats = [];
    foreach ($categories as $c) {
        $v = trim((string) $c);
        if ($v !== '') {
            $safeCats[] = $v;
        }
    }
    if (!empty($safeCats)) {
        $catText = implode(', ', array_slice($safeCats, 0, 6));
    }
}

$promptPayload = [
    'product_name' => $productName,
    'description' => $productDescription,
    'sale_price_bdt' => $salePrice,
    'regular_price_bdt' => $regularPrice,
    'categories' => $catText,
    'language' => 'Bangla (with natural ecommerce style)',
    'output_format' => 'json',
];

$systemPrompt = 'You are a senior Bangla direct-response ecommerce copywriter for Facebook ads in Bangladesh. Output ONLY JSON.';
$userPrompt = "Generate one high-converting ad copy pack for the product using this exact JSON shape:\n{\n  \"primaryText\": \"...\",\n  \"headline\": \"...\",\n  \"cta\": \"...\",\n  \"suggestedInterests\": [\"...\", \"...\"],\n  \"audienceAngle\": \"...\"\n}\nRules: primaryText max 220 chars, headline max 60 chars, cta max 20 chars, interests 3-8 items.\nProduct data:\n" . json_encode($promptPayload, JSON_UNESCAPED_UNICODE);

$req = [
    'model' => $model !== '' ? $model : 'gpt-4o-mini',
    'temperature' => 0.7,
    'response_format' => ['type' => 'json_object'],
    'messages' => [
        ['role' => 'system', 'content' => $systemPrompt],
        ['role' => 'user', 'content' => $userPrompt],
    ],
];

$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($req, JSON_UNESCAPED_UNICODE),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $openaiKey,
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 45,
]);
$res = curl_exec($ch);
$errno = curl_errno($ch);
$http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($errno !== 0 || $res === false) {
    http_response_code(502);
    echo json_encode(['status' => 'error', 'message' => 'Could not reach OpenAI API.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$decoded = json_decode($res, true);
if ($http >= 400) {
    $msg = 'OpenAI request failed.';
    if (is_array($decoded) && isset($decoded['error']['message'])) {
        $msg = (string) $decoded['error']['message'];
    }
    http_response_code($http);
    echo json_encode(['status' => 'error', 'message' => $msg], JSON_UNESCAPED_UNICODE);
    exit;
}

$content = '';
if (is_array($decoded) && isset($decoded['choices'][0]['message']['content'])) {
    $content = trim((string) $decoded['choices'][0]['message']['content']);
}
if ($content === '') {
    http_response_code(502);
    echo json_encode(['status' => 'error', 'message' => 'Empty response from OpenAI.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$jsonOut = json_decode($content, true);
if (!is_array($jsonOut)) {
    $start = strpos($content, '{');
    $end = strrpos($content, '}');
    if ($start !== false && $end !== false && $end > $start) {
        $slice = substr($content, $start, $end - $start + 1);
        $jsonOut = json_decode($slice, true);
    }
}

if (!is_array($jsonOut)) {
    http_response_code(502);
    echo json_encode(['status' => 'error', 'message' => 'Could not parse AI JSON output.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$primaryText = trim((string) ($jsonOut['primaryText'] ?? ''));
$headline = trim((string) ($jsonOut['headline'] ?? ''));
$cta = trim((string) ($jsonOut['cta'] ?? 'Shop Now'));
$audienceAngle = trim((string) ($jsonOut['audienceAngle'] ?? ''));
$interests = isset($jsonOut['suggestedInterests']) && is_array($jsonOut['suggestedInterests']) ? $jsonOut['suggestedInterests'] : [];

$cleanInterests = [];
foreach ($interests as $it) {
    $v = trim((string) $it);
    if ($v !== '') {
        $cleanInterests[] = $v;
    }
}
$cleanInterests = array_values(array_slice(array_unique($cleanInterests), 0, 12));

echo json_encode([
    'status' => 'success',
    'primaryText' => substr($primaryText, 0, 1000),
    'headline' => substr($headline, 0, 300),
    'cta' => substr($cta, 0, 120),
    'suggestedInterests' => $cleanInterests,
    'audienceAngle' => substr($audienceAngle, 0, 400),
    'model' => $req['model'],
], JSON_UNESCAPED_UNICODE);
