<?php
// =================================================================
// client-information.php (VERSIÓN FINAL Y COMPLETA)
// Obtiene todos los datos del negocio desde la base de datos
// para uso en el front-end y herramientas de IA.
// =================================================================

if (!isset($client_info)) { $client_info = []; }

// 1) Cargar conexión a la base de datos
$pdo = $pdo ?? null;
if (!$pdo) {
    if (isset($conn) && $conn instanceof mysqli) {
        $pdo = new PDO(
            "mysql:host={$conn->host_info};dbname=" . $conn->query("SELECT DATABASE()")->fetch_row()[0],
            $conn->user,
            $conn->passwd,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    } else {
        $dbFile = __DIR__ . '/db/db_connection.php';
        if (is_file($dbFile)) {
            require_once $dbFile;
        }
    }
}

// Si después de todo, no hay conexión, establece un array vacío y termina.
if (!isset($pdo)) {
    $client_info = [
        'name' => '', 'business_name' => '', 'license_number' => '', 'phone' => '',
        'phone_secondary' => '', 'whatsapp' => '', 'email' => '', 'website' => '', 'logo_url' => '',
        'social_links' => [], 'google_maps_embed' => '', 'tracking_codes_head' => '',
        'tracking_codes_body' => '', 'sections' => [], 'operating_cities' => '', 'value_proposition' => ''
    ];
    return;
}

try {
    // --- 1. OBTENER DATOS PRINCIPALES DEL NEGOCIO ---
    $mainSql = "SELECT * FROM business_info ORDER BY id DESC LIMIT 1";
    $stmtMain = $pdo->prepare($mainSql);
    $stmtMain->execute();
    $mainData = $stmtMain->fetch() ?: [];
    $business_id = $mainData['id'] ?? 0;

    // --- 2. OBTENER CIUDADES DE OPERACIÓN ---
    $citiesSql = "SELECT city_name FROM cms_coverage_cities";
    $stmtCities = $pdo->prepare($citiesSql);
    $stmtCities->execute();
    $citiesArray = $stmtCities->fetchAll(PDO::FETCH_COLUMN);
    $operatingCities = implode(', ', $citiesArray);

    // --- 3. OBTENER REDES SOCIALES ---
    $linksSql = "SELECT link_icon, link_url FROM social_links WHERE business_info_id = ?";
    $stmtLinks = $pdo->prepare($linksSql);
    $stmtLinks->execute([$business_id]);
    $socialLinks = $stmtLinks->fetchAll() ?: [];

    // --- 4. OBTENER DATOS ADICIONALES DE OTRAS TABLAS ---
    $coverageSql = "SELECT coverage_map_embed FROM cms_coverage LIMIT 1";
    $mapEmbed = $pdo->query($coverageSql)->fetchColumn() ?: '';

    $trackingSql = "SELECT tracking_codes_head, tracking_codes_body FROM tracking_codes WHERE business_info_id = ?";
    $stmtTracking = $pdo->prepare($trackingSql);
    $stmtTracking->execute([$business_id]);
    $trackingData = $stmtTracking->fetch() ?: ['tracking_codes_head' => '', 'tracking_codes_body' => ''];

    $sectionsSql = "SELECT * FROM sections_enabled WHERE business_info_id = ?";
    $stmtSections = $pdo->prepare($sectionsSql);
    $stmtSections->execute([$business_id]);
    $sectionsData = $stmtSections->fetch() ?: [];
    
    $valuePropSql = "SELECT value_proposition FROM website_config LIMIT 1";
    $valueProposition = $pdo->query($valuePropSql)->fetchColumn() ?: '';

    // --- 5. CONSTRUIR EL ARRAY FINAL CON TODA LA INFORMACIÓN ---
    $client_info = [
        'name'                  => $mainData['full_name'] ?? '',
        'business_name'         => $mainData['company_name'] ?? '',
        'operating_cities'      => $operatingCities,
        'value_proposition'     => $valueProposition,
        'license_number'        => $mainData['license_number'] ?? '',
        'phone'                 => $mainData['phone_primary'] ?? '',
        'phone_secondary'       => $mainData['phone_secondary'] ?? '',
        'whatsapp'              => $mainData['whatsapp'] ?? '',
        'email'                 => $mainData['site_email'] ?? '',
        'website'               => $mainData['website_url'] ?? '',
        'logo_url'              => $mainData['logo_url'] ?? '',
        'social_links'          => $socialLinks,
        'google_maps_embed'     => $mapEmbed,
        'tracking_codes_head'   => $trackingData['tracking_codes_head'],
        'tracking_codes_body'   => $trackingData['tracking_codes_body'],
        'sections'              => [
            'differentiators_page_enabled' => $sectionsData['differentiators_page_enabled'] ?? 1,
            'process_page_enabled' => $sectionsData['process_page_enabled'] ?? 1,
            'coverage_page_enabled' => $sectionsData['coverage_page_enabled'] ?? 1,
            'services_page_enabled' => $sectionsData['services_page_enabled'] ?? 1,
            'results_page_enabled' => $sectionsData['results_page_enabled'] ?? 1,
            'reviews_page_enabled' => $sectionsData['reviews_page_enabled'] ?? 1,
            'cta_page_enabled' => $sectionsData['cta_page_enabled'] ?? 1,
            'hours_page_enabled' => $sectionsData['hours_page_enabled'] ?? 1,
            'exit_intent_enabled' => $sectionsData['exit_intent_enabled'] ?? 0,
        ]
    ];

} catch (Throwable $e) {
    // En caso de un error en la base de datos, devuelve un array vacío pero con todas las claves.
    $client_info = [
        'name' => '', 'business_name' => '', 'license_number' => '', 'phone' => '',
        'phone_secondary' => '', 'whatsapp' => '', 'email' => '', 'website' => '', 'logo_url' => '',
        'social_links' => [], 'google_maps_embed' => '', 'tracking_codes_head' => '',
        'tracking_codes_body' => '', 'sections' => [], 'operating_cities' => '', 'value_proposition' => ''
    ];
    error_log("Error en client-information.php: " . $e->getMessage());
}
?>