<?php
/**
 * API - Eliminar todas las plantillas locales y re-sincronizar desde WhatsApp/Facebook
 * Borra la tabla local y vuelve a importar todo desde la API de Meta
 */

require_once '../config/config.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

requireAuthentication();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

try {
    $db = Database::getInstance();

    // Obtener configuración de WhatsApp
    $token  = getConfigFromDB('whatsapp_token', '');
    $wabaId = getConfigFromDB('whatsapp_business_account_id', '');
    $config = getWhatsAppConfigFromDB();
    $apiUrl = rtrim($config['api_url'] ?: 'https://graph.facebook.com/v22.0/', '/');

    if (empty($token)) {
        throw new Exception('Token de WhatsApp no configurado');
    }
    if (empty($wabaId)) {
        throw new Exception('Business Account ID no configurado. Configúrelo en Configuración del Sistema.');
    }

    // ── Paso 1: Obtener plantillas desde Facebook ─────────────────────────────
    $url = "{$apiUrl}/{$wabaId}/message_templates";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ["Authorization: Bearer {$token}", "Content-Type: application/json"],
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
        CURLOPT_SSLVERSION     => CURL_SSLVERSION_TLSv1_2,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        throw new Exception("Error de conexión: {$curlErr}");
    }
    if ($httpCode !== 200) {
        $errData = json_decode($response, true);
        $errMsg  = $errData['error']['message'] ?? 'Error desconocido';
        throw new Exception("Error de API ({$httpCode}): {$errMsg}");
    }

    $data = json_decode($response, true);
    if (!isset($data['data']) || !is_array($data['data'])) {
        throw new Exception('Respuesta inválida de la API de WhatsApp');
    }

    $templates = $data['data'];
    $totalFromFacebook = count($templates);

    // ── Paso 2: Eliminar TODAS las plantillas locales ─────────────────────────
    $deletedCount = $db->query("DELETE FROM message_templates");
    error_log("[reset_and_sync_templates] Eliminadas todas las plantillas locales. Iniciando re-import de {$totalFromFacebook} plantillas.");

    // ── Paso 3: Insertar todas las plantillas desde Facebook ──────────────────
    $syncedCount = 0;
    $errors      = [];

    foreach ($templates as $template) {
        try {
            $templateName = $template['name']       ?? '';
            $language     = $template['language']   ?? 'es';
            $status       = $template['status']     ?? 'pending';
            $category     = $template['category']   ?? 'UTILITY';
            $components   = $template['components'] ?? [];

            if (empty($templateName)) continue;

            // Extraer campos de componentes
            $bodyText   = null;
            $headerText = null;
            $headerType = null;
            $footerText = null;
            $exampleParameters = [];

            foreach ($components as $comp) {
                $type = $comp['type'] ?? '';
                if ($type === 'BODY') {
                    $bodyText = $comp['text'] ?? null;
                    if (isset($comp['example']['body_text'])) {
                        $exampleParameters['body'] = $comp['example']['body_text'];
                    }
                } elseif ($type === 'HEADER') {
                    $headerText = $comp['text'] ?? null;
                    $headerType = strtolower($comp['format'] ?? 'text');
                    if (isset($comp['example']['header_text'])) {
                        $exampleParameters['header'] = $comp['example']['header_text'];
                    }
                } elseif ($type === 'FOOTER') {
                    $footerText = $comp['text'] ?? null;
                }
            }

            // Extraer variables automáticamente del body
            $variables = [];
            if ($bodyText) {
                preg_match_all('/\{\{([^\}]+)\}\}/', $bodyText, $matches);
                if (!empty($matches[1])) {
                    $index = 1;
                    foreach (array_unique($matches[1]) as $varName) {
                        $varIndex = is_numeric($varName) ? (int)$varName : $index;
                        $exData   = $exampleParameters['body'][$varIndex - 1] ?? null;
                        $example  = is_array($exData) ? $exData[0] : $exData;
                        $variables[] = [
                            'index'       => $varIndex,
                            'placeholder' => "{{" . $varName . "}}",
                            'name'        => $varName,
                            'example'     => $example,
                        ];
                        if (!is_numeric($varName)) $index++;
                    }
                    $exampleParameters['variables'] = $variables;
                }
            }

            $componentsJson = !empty($components)        ? json_encode($components, JSON_UNESCAPED_UNICODE)        : null;
            $exampleJson    = !empty($exampleParameters) ? json_encode($exampleParameters, JSON_UNESCAPED_UNICODE) : null;

            $db->execute(
                "INSERT INTO message_templates (
                    name, template_name, language_code, category, status,
                    body_text, header_text, header_type, footer_text,
                    components, example_parameters, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())",
                [
                    $templateName, $templateName,
                    $language, strtolower($category), strtolower($status),
                    $bodyText, $headerText, $headerType, $footerText,
                    $componentsJson, $exampleJson,
                ]
            );

            $syncedCount++;
        } catch (Exception $e) {
            $errors[] = "Error con '{$templateName}': " . $e->getMessage();
            error_log("[reset_and_sync_templates] " . end($errors));
        }
    }

    writeLog('INFO', "Reset+Sync plantillas: {$syncedCount}/{$totalFromFacebook} importadas, " . count($errors) . " errores");

    echo json_encode([
        'success' => true,
        'message' => "Re-sincronización completada: {$syncedCount} plantillas importadas",
        'data'    => [
            'total_facebook' => $totalFromFacebook,
            'deleted_local'  => $deletedCount,
            'imported'       => $syncedCount,
            'errors'         => $errors,
        ],
    ]);

} catch (Exception $e) {
    error_log('[reset_and_sync_templates] ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
