<?php

/**
 * Facebook Ads – AI API Controller
 * توليد نص الإعلان واقتراح الجمهور بالذكاء الاصطناعي
 */
class FbAdsApiController
{
    private function json(array $data, int $code = 200): never
    {
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // ── Generate ad copy for all 3 fields ─────────────────────────────
    public function generateCopy(): void
    {
        $productId = (int)($_POST['product_id'] ?? 0);
        $objective = trim($_POST['objective'] ?? 'OUTCOME_SALES');
        $lang      = trim($_POST['lang'] ?? 'ar');

        if (!$productId) $this->json(['success' => false, 'message' => 'Product required.']);

        $product = db()->prepare("SELECT * FROM products WHERE id=? LIMIT 1");
        $product->execute([$productId]);
        $product = $product->fetch(\PDO::FETCH_ASSOC);
        if (!$product) $this->json(['success' => false, 'message' => 'Product not found.']);

        $price    = $product['sale_price'] ?: $product['price'];
        $desc     = strip_tags($product['short_description'] ?? $product['description'] ?? '');
        $desc     = mb_substr($desc, 0, 300);
        $currency = $product['currency'] ?? 'DZD';

        $objectiveLabel = match($objective) {
            'OUTCOME_SALES'      => $lang === 'ar' ? 'زيادة المبيعات' : 'increase sales',
            'OUTCOME_TRAFFIC'    => $lang === 'ar' ? 'زيادة الزيارات' : 'drive traffic',
            'OUTCOME_AWARENESS'  => $lang === 'ar' ? 'نشر الوعي' : 'brand awareness',
            'OUTCOME_ENGAGEMENT' => $lang === 'ar' ? 'زيادة التفاعل' : 'boost engagement',
            default              => $lang === 'ar' ? 'زيادة المبيعات' : 'increase sales',
        };

        $langInstr = $lang === 'ar'
            ? \Core\App\Services\AiService::getDialectInstruction(null, 'ar') . ' فقط.'
            : 'Write in English only.';

        $prompt = $lang === 'ar' ? <<<PROMPT
{$langInstr}

أنت خبير إعلانات Facebook. اكتب نص إعلان ممول لهذا المنتج:
- الاسم: {$product['title']}
- السعر: {$price} {$currency}
- الوصف: {$desc}
- هدف الحملة: {$objectiveLabel}

أعطِ النتيجة بصيغة JSON فقط (بدون أي نص خارجه):
{
  "primary_text": "النص الرئيسي للإعلان (125 حرف كحد أقصى، جذاب ومقنع، مع إيموجي)",
  "headline": "العنوان (40 حرف كحد أقصى، قصير وقوي)",
  "description": "الوصف (30 حرف كحد أقصى، يدعم العنوان)"
}
PROMPT : <<<PROMPT
{$langInstr}

You are a Facebook Ads expert. Write paid ad copy for this product:
- Name: {$product['title']}
- Price: {$price} {$currency}
- Description: {$desc}
- Campaign objective: {$objectiveLabel}

Return JSON only (no extra text):
{
  "primary_text": "Main ad text (max 125 chars, persuasive with emojis)",
  "headline": "Headline (max 40 chars, short and punchy)",
  "description": "Description (max 30 chars, supports headline)"
}
PROMPT;

        try {
            $ai      = \Core\App\Services\AiService::fromActiveProvider();
            $content = $ai->generate($prompt, [
                'system'     => 'You are a professional Facebook Ads copywriter. Return JSON only.',
                'max_tokens' => 300,
            ]);

            // Parse JSON
            $content = trim(preg_replace('/^```(?:json)?\s*/m', '', $content));
            $content = trim(preg_replace('/```\s*$/m', '', $content));
            $result  = json_decode($content, true);

            if (!is_array($result) || empty($result['primary_text'])) {
                if (preg_match('/\{.*\}/s', $content, $m)) {
                    $result = json_decode($m[0], true);
                }
            }

            if (!is_array($result) || empty($result['primary_text'])) {
                $this->json(['success' => false, 'message' => 'AI returned invalid format.']);
            }

            $this->json([
                'success'      => true,
                'primary_text' => trim($result['primary_text'] ?? ''),
                'headline'     => trim($result['headline']     ?? ''),
                'description'  => trim($result['description']  ?? ''),
            ]);

        } catch (\Throwable $e) {
            $this->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }

    // ── Suggest audience ──────────────────────────────────────────────
    public function suggestAudience(): void
    {
        $productId = (int)($_POST['product_id'] ?? 0);
        $lang      = trim($_POST['lang'] ?? 'ar');

        $product = db()->prepare("SELECT title, short_description, description FROM products WHERE id=? LIMIT 1");
        $product->execute([$productId]);
        $product = $product->fetch(\PDO::FETCH_ASSOC);
        if (!$product) $this->json(['success' => false, 'message' => 'Not found.']);

        $desc = strip_tags($product['short_description'] ?? $product['description'] ?? '');

        $dialectInstr = $lang === 'ar'
            ? \Core\App\Services\AiService::getDialectInstruction(null, 'ar') . ' فقط.'
            : 'Write in English only.';

        $prompt = $lang === 'ar' ? <<<PROMPT
{$dialectInstr}

أنت خبير استهداف إعلانات Facebook.
حلّل هذا المنتج واقترح الجمهور المثالي:
المنتج: {$product['title']}
الوصف: {$desc}

أعطِ النتيجة بـ JSON فقط:
{
  "age_min": 18,
  "age_max": 45,
  "gender": "all",
  "interests": ["اهتمام 1", "اهتمام 2", "اهتمام 3"],
  "reason": "سبب قصير لهذا الاستهداف"
}
PROMPT : <<<PROMPT
{$dialectInstr}

You are a Facebook Ads targeting expert.
Analyze this product and suggest the ideal audience:
Product: {$product['title']}
Description: {$desc}

Return JSON only:
{
  "age_min": 18,
  "age_max": 45,
  "gender": "all",
  "interests": ["interest 1", "interest 2", "interest 3"],
  "reason": "Brief reason for this targeting"
}
PROMPT;

        try {
            $ai     = \Core\App\Services\AiService::fromActiveProvider();
            $result = $ai->generate($prompt, ['system' => 'Return JSON only.', 'max_tokens' => 200]);
            $result = trim(preg_replace('/^```(?:json)?\s*/m', '', $result));
            $result = trim(preg_replace('/```\s*$/m', '', $result));
            $data   = json_decode($result, true);
            if (!is_array($data)) { if(preg_match('/\{.*\}/s',$result,$m)) $data=json_decode($m[0],true); }
            $this->json(['success' => true, 'audience' => $data ?? []]);
        } catch (\Throwable $e) {
            $this->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }
}
