<?php
header('Content-Type: application/json; charset=UTF-8');

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

function mb_error($code, $message) {
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

function mb_path_encode($path) {
    $parts = array_filter(explode('/', trim((string) $path, '/')), 'strlen');
    if (!$parts) return '';
    return implode('/', array_map('rawurlencode', $parts));
}

function mb_rtdb_patch($dbUrl, $path, $accessToken, $data) {
    $base = rtrim($dbUrl, '/');
    $encodedPath = mb_path_encode($path);
    $url = $base . '/' . $encodedPath . '.json';
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => 'PATCH',
        CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $accessToken,
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);
    $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 >= 400) {
        return false;
    }
    return true;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') mb_error(405, 'Method not allowed');
if (!function_exists('curl_init')) mb_error(503, 'PHP curl extension is required.');

$raw = file_get_contents('php://input');
$body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
if (!is_array($body)) mb_error(400, 'Invalid JSON');

$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)) mb_error(400, 'Valid clientId is required.');

$productName = trim((string) ($product['name'] ?? ''));
if ($productName === '') mb_error(400, 'Product name is required.');
$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'] : [];

$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootPath)) mb_error(503, 'Server not configured.');
$boot = include $bootPath;
if (!is_array($boot)) mb_error(503, 'Invalid firebase-admin bootstrap.');

$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 === '') mb_error(503, 'Bootstrap missing required values.');

$tok = firebase_service_account_access_token($saPath);
if (isset($tok['error'])) mb_error(503, 'Firebase admin error: ' . $tok['error']);
$access = $tok['access_token'];

$settingsSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/siteSettings', $access);
if (isset($settingsSnap['error'])) mb_error(503, 'Could not load site settings.');
$settings = is_array($settingsSnap['data']) ? $settingsSnap['data'] : [];
$openaiKey = trim((string) ($settings['openaiApiKey'] ?? ''));
$model = trim((string) ($settings['openaiModel'] ?? 'gpt-4o-mini'));
if ($openaiKey === '') mb_error(400, 'OpenAI API Key not found in Site Settings.');

$dateKey = gmdate('Y-m-d');
$usagePath = 'clients/' . $clientId . '/aiBrain/usage/' . $dateKey;
$usageSnap = firebase_rtdb_get($dbUrl, $usagePath, $access);
$usageCount = 0;
if (!isset($usageSnap['error']) && isset($usageSnap['data']['campaignPack']) && is_numeric($usageSnap['data']['campaignPack'])) {
    $usageCount = (int) $usageSnap['data']['campaignPack'];
}
if ($usageCount >= 200) mb_error(429, 'Daily AI campaign generation limit reached (200).');

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

$payload = [
    'product_name' => $productName,
    'description' => $productDescription,
    'sale_price_bdt' => $salePrice,
    'regular_price_bdt' => $regularPrice,
    'categories' => $catText,
    'locale' => 'Bangladesh',
    'language' => 'Bangla',
];

$systemPrompt = 'You are a senior Bangla direct-response ecommerce marketer for Bangladesh. Output ONLY JSON.';
$userPrompt = "Generate one complete Facebook campaign pack in this exact JSON shape:\n{\n  \"variants\": [\n    {\"label\":\"A\",\"primaryText\":\"...\",\"headline\":\"...\",\"cta\":\"...\"},\n    {\"label\":\"B\",\"primaryText\":\"...\",\"headline\":\"...\",\"cta\":\"...\"},\n    {\"label\":\"C\",\"primaryText\":\"...\",\"headline\":\"...\",\"cta\":\"...\"}\n  ],\n  \"suggestedInterests\": [\"...\"],\n  \"audienceAngle\": \"...\",\n  \"imagePrompt\": \"...\",\n  \"dailyBudgetBdt\": 500,\n  \"monthlyBudgetBdt\": 15000,\n  \"schedulingHint\": \"...\"\n}\nRules: Keep primaryText <= 260 chars, headline <= 60, cta <= 20, interests 4-10.\nProduct data:\n" . json_encode($payload, JSON_UNESCAPED_UNICODE);

$req = [
    'model' => $model !== '' ? $model : 'gpt-4o-mini',
    'temperature' => 0.7,
    'max_tokens' => 1200,
    '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 => 50,
]);
$res = curl_exec($ch);
$errno = curl_errno($ch);
$http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno !== 0 || $res === false) mb_error(502, 'Could not reach OpenAI API.');

$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'];
    mb_error($http, $msg);
}

$content = '';
if (is_array($decoded) && isset($decoded['choices'][0]['message']['content'])) $content = trim((string) $decoded['choices'][0]['message']['content']);
if ($content === '') mb_error(502, 'Empty response from OpenAI.');

$out = json_decode($content, true);
if (!is_array($out)) {
    $start = strpos($content, '{');
    $end = strrpos($content, '}');
    if ($start !== false && $end !== false && $end > $start) {
        $slice = substr($content, $start, $end - $start + 1);
        $out = json_decode($slice, true);
    }
}
if (!is_array($out)) mb_error(502, 'Could not parse AI JSON output.');

$variantsRaw = isset($out['variants']) && is_array($out['variants']) ? $out['variants'] : [];
$labels = ['A', 'B', 'C'];
$variants = [];
foreach ($labels as $label) {
    $match = null;
    foreach ($variantsRaw as $row) {
        if (!is_array($row)) continue;
        if (strtoupper(trim((string) ($row['label'] ?? ''))) === $label) {
            $match = $row;
            break;
        }
    }
    if (!$match && isset($variantsRaw[count($variants)]) && is_array($variantsRaw[count($variants)])) $match = $variantsRaw[count($variants)];
    $primary = trim((string) (($match['primaryText'] ?? '')));
    $headline = trim((string) (($match['headline'] ?? '')));
    $cta = trim((string) (($match['cta'] ?? 'Shop Now')));
    $variants[] = [
        'label' => $label,
        'primaryText' => mb_substr($primary, 0, 1000),
        'headline' => mb_substr($headline, 0, 300),
        'cta' => mb_substr($cta, 0, 120),
    ];
}

$interests = isset($out['suggestedInterests']) && is_array($out['suggestedInterests']) ? $out['suggestedInterests'] : [];
$cleanInterests = [];
foreach ($interests as $it) {
    $v = trim((string) $it);
    if ($v !== '') $cleanInterests[] = $v;
}
$cleanInterests = array_values(array_slice(array_unique($cleanInterests), 0, 12));

$audienceAngle = mb_substr(trim((string) ($out['audienceAngle'] ?? '')), 0, 500);
$imagePrompt = mb_substr(trim((string) ($out['imagePrompt'] ?? '')), 0, 1200);
$dailyBudget = isset($out['dailyBudgetBdt']) && is_numeric($out['dailyBudgetBdt']) ? (int) $out['dailyBudgetBdt'] : 500;
$monthlyBudget = isset($out['monthlyBudgetBdt']) && is_numeric($out['monthlyBudgetBdt']) ? (int) $out['monthlyBudgetBdt'] : ($dailyBudget * 30);
$schedulingHint = mb_substr(trim((string) ($out['schedulingHint'] ?? '')), 0, 500);

mb_rtdb_patch($dbUrl, $usagePath, $access, [
    'campaignPack' => $usageCount + 1,
    'updatedAt' => round(microtime(true) * 1000),
]);

echo json_encode([
    'status' => 'success',
    'variants' => $variants,
    'suggestedInterests' => $cleanInterests,
    'audienceAngle' => $audienceAngle,
    'imagePrompt' => $imagePrompt,
    'dailyBudgetBdt' => max(100, min(500000, $dailyBudget)),
    'monthlyBudgetBdt' => max(1000, min(5000000, $monthlyBudget)),
    'schedulingHint' => $schedulingHint,
    'model' => $req['model'],
], JSON_UNESCAPED_UNICODE);
