<?php
// =============================================================================
// 1. HELPERS DE PARSING
// =============================================================================

/** Convierte un string en slug seguro para nombres de tema. */
function wpgen_slugify(string $str): string {
    $str = mb_strtolower($str, 'UTF-8');
    $str = preg_replace('/[áàäâã]/u', 'a', $str);
    $str = preg_replace('/[éèëê]/u', 'e', $str);
    $str = preg_replace('/[íìïî]/u', 'i', $str);
    $str = preg_replace('/[óòöôõ]/u', 'o', $str);
    $str = preg_replace('/[úùüû]/u', 'u', $str);
    $str = preg_replace('/[ñ]/u', 'n', $str);
    $str = preg_replace('/[^a-z0-9]+/', '-', $str);
    return trim($str, '-') ?: 'cliente';
}

/** Extrae el contenido del primer bloque <style>...</style> y devuelve [css, html_sin_style]. */
function wpgen_extract_style(string $html): array {
    if (preg_match('/<style[^>]*>(.*?)<\/style>/is', $html, $m)) {
        $css = trim($m[1]);
        $html = str_replace($m[0], '', $html);
        return [$css, $html];
    }
    return ['', $html];
}

/** Extrae scripts inline (sin src). Devuelve array de strings + html limpio. */
function wpgen_extract_scripts(string $html): array {
    $scripts = [];
    $html = preg_replace_callback(
        '/<script(?![^>]*\bsrc=)[^>]*>(.*?)<\/script>/is',
        function($m) use (&$scripts) {
            $code = trim($m[1]);
            // No incluir JSON-LD schemas en scripts JS
            if (stripos($code, '@context') !== false && stripos($code, 'schema.org') !== false) {
                return $m[0]; // dejar el schema en el HTML, lo manejamos aparte
            }
            $scripts[] = $code;
            return '';
        },
        $html
    );
    return [$scripts, $html];
}

/** Detecta variables Lottie en scripts: const/var _xData = {...}. Devuelve [name => json_string]. */
function wpgen_extract_lottie(array $scripts): array {
    $lotties = [];
    foreach ($scripts as $idx => $code) {
        if (preg_match_all('/(?:const|var|let)\s+(_?[a-zA-Z][a-zA-Z0-9_]*Data)\s*=\s*(\{)/m', $code, $matches, PREG_OFFSET_CAPTURE)) {
            foreach ($matches[1] as $i => $name_match) {
                $var_name = $name_match[0];
                $brace_pos = $matches[2][$i][1];
                $json = wpgen_balanced_json($code, $brace_pos);
                if (!$json) continue;
                $decoded = json_decode($json, true);
                // Validar que tiene estructura Lottie (campos típicos: v, fr, ip, op, w, h, layers)
                if (is_array($decoded) && isset($decoded['v'], $decoded['layers'])) {
                    $clean_name = preg_replace('/^_+|Data$/', '', $var_name);
                    $clean_name = wpgen_slugify($clean_name ?: 'lottie' . $idx);
                    $lotties[$clean_name] = $json;
                }
            }
        }
    }
    return $lotties;
}

/** Extrae JSON balanceado desde una posición de '{' considerando strings y escapes. */
function wpgen_balanced_json(string $code, int $start): ?string {
    $depth = 0; $in_str = false; $escape = false;
    $len = strlen($code);
    for ($i = $start; $i < $len; $i++) {
        $c = $code[$i];
        if ($escape) { $escape = false; continue; }
        if ($c === '\\') { $escape = true; continue; }
        if ($c === '"') { $in_str = !$in_str; continue; }
        if ($in_str) continue;
        if ($c === '{') $depth++;
        elseif ($c === '}') {
            $depth--;
            if ($depth === 0) return substr($code, $start, $i - $start + 1);
        }
    }
    return null;
}

/**
 * Divide el HTML en secciones usando comentarios HTML como marcadores TOP-LEVEL.
 * Solo considera comentarios que están directamente al nivel del body (no anidados
 * dentro de <section>, <div>, etc.). Devuelve [slug => html_section].
 */
function wpgen_split_sections(string $html): array {
    // Si tiene <body>, quedarnos solo con el contenido
    if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $m)) {
        $body = $m[1];
    } else {
        $body = $html;
    }

    // Buscar comentarios top-level: deben estar precedidos por whitespace y newline
    // y la siguiente línea típicamente abre un <section>, <nav>, <footer>, <a>, <div>
    $pattern = '/(?:^|\n)\s*<!--\s*([A-ZÁÉÍÓÚÑ][A-ZÁÉÍÓÚÑa-zñ0-9\s\/]{2,}?)\s*-->\s*\n\s*<(section|nav|footer|aside|article|a\s|div\s+class)/u';

    if (!preg_match_all($pattern, $body, $matches, PREG_OFFSET_CAPTURE)) {
        return ['content' => trim($body)];
    }

    $sections = [];
    $marker_count = count($matches[0]);
    for ($i = 0; $i < $marker_count; $i++) {
        $name = trim($matches[1][$i][0]);

        // Skip palabras sin sentido como "TICKER SEPARATOR" repetido
        $start_pos = $matches[0][$i][1];
        // Avanzar hasta después del comentario (no incluir el comment en la sección)
        $after_comment = strpos($body, '-->', $start_pos);
        if ($after_comment === false) continue;
        $start_pos = $after_comment + 3;

        $end_pos = ($i + 1 < $marker_count) ? $matches[0][$i + 1][1] : strlen($body);
        $section_html = trim(substr($body, $start_pos, $end_pos - $start_pos));

        $slug = wpgen_slugify($name);
        // Repetidos (tickers): solo guardar el primero
        if (isset($sections[$slug])) continue;
        if ($section_html !== '') $sections[$slug] = $section_html;
    }

    return $sections ?: ['content' => trim($body)];
}

/**
 * Detecta campos editables (precios, teléfonos, emails, URLs sociales) en el HTML.
 * IMPORTANTE: elimina <script> y <style> antes de escanear para evitar falsos positivos
 * (JSON de Lottie contiene números que parecen teléfonos).
 */
function wpgen_detect_fields(string $html): array {
    // Limpiar scripts y styles antes de escanear
    $clean = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $html);
    $clean = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $clean);

    $fields = ['prices' => [], 'phones' => [], 'emails' => [], 'socials' => []];

    // PRECIOS — formato $XX.XXX o $XXX.XXX
    if (preg_match_all('/\$\s?\d{1,3}(?:[.,]\d{3})+/u', $clean, $m)) {
        $fields['prices'] = array_values(array_unique($m[0]));
    }

    // TELÉFONOS COLOMBIANOS — solo en hrefs (tel:, wa.me) o texto visible con formato claro
    $phones = [];

    // Patrón 1: hrefs tel:+57... o wa.me/57...
    if (preg_match_all('/(?:tel:\+?|wa\.me\/)(\d{10,13})/i', $clean, $m)) {
        foreach ($m[1] as $p) {
            $d = preg_replace('/[^0-9]/', '', $p);
            if (strlen($d) === 10 && $d[0] === '3') $d = '57' . $d;
            if (strlen($d) === 12 && substr($d, 0, 2) === '57') $phones[] = $d;
        }
    }

    // Patrón 2: texto visible con formato +57 XXX XXX XXXX o 3XX XXX XXXX
    if (preg_match_all('/\+?57\s\d{3}\s\d{3}\s\d{4}|\b3\d{2}\s\d{3}\s\d{4}\b/', $clean, $m)) {
        foreach ($m[0] as $p) {
            $d = preg_replace('/[^0-9]/', '', $p);
            if (strlen($d) === 10 && $d[0] === '3') $d = '57' . $d;
            if (strlen($d) === 12 && substr($d, 0, 2) === '57') $phones[] = $d;
        }
    }

    $fields['phones'] = array_values(array_unique($phones));

    // EMAILS
    if (preg_match_all('/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/', $clean, $m)) {
        // Filtrar emails de ejemplo/spam comunes
        $emails = array_filter($m[0], fn($e) => !preg_match('/(example|test|demo|noreply)@/i', $e));
        $fields['emails'] = array_values(array_unique($emails));
    }

    // REDES SOCIALES
    $social_patterns = [
        'instagram' => '/https?:\/\/(?:www\.)?instagram\.com\/[A-Za-z0-9._]+/',
        'facebook'  => '/https?:\/\/(?:www\.)?facebook\.com\/[A-Za-z0-9.]+/',
        'tiktok'    => '/https?:\/\/(?:www\.)?tiktok\.com\/@[A-Za-z0-9._]+/',
        'twitter'   => '/https?:\/\/(?:www\.)?(?:twitter|x)\.com\/[A-Za-z0-9_]+/',
        'youtube'   => '/https?:\/\/(?:www\.)?youtube\.com\/(?:@|c\/|channel\/)[A-Za-z0-9._-]+/',
    ];
    foreach ($social_patterns as $net => $regex) {
        if (preg_match_all($regex, $clean, $m)) {
            $fields['socials'][$net] = array_values(array_unique($m[0]))[0];
        }
    }

    return $fields;
}

// =============================================================================
// 2. BUILDERS DE ARCHIVOS DEL TEMA
// =============================================================================

/** Construye style.css con header WordPress oficial + CSS extraído. */
function wpgen_build_style_css(string $theme_name, string $description, string $css): string {
    $header = "/*
Theme Name: {$theme_name}
Theme URI: https://supercerebro.com
Author: SuperCerebro by DIMARK
Author URI: https://supercerebro.com
Description: " . str_replace("\n", ' ', $description) . "
Version: 1.0.0
Requires at least: 5.0
Tested up to: 6.4
Requires PHP: 7.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: " . wpgen_slugify($theme_name) . "
*/

";
    // CSS adicional para que the_content() de about herede tipografía
    $extras = "
/* === Estilos auto-generados para content editable === */
.about-text,.editable-content{font-size:.95rem;line-height:1.8;}
.about-text h1,.about-text h2,.editable-content h1,.editable-content h2{margin:0 0 30px;line-height:1.1;}
.about-text p,.editable-content p{margin:0 0 20px;}
.about-text strong,.editable-content strong{font-weight:700;}
.about-text a,.editable-content a{text-decoration:underline;}
";
    return $header . $css . $extras;
}

/** Construye functions.php con Customizer dinámico basado en campos detectados. */
function wpgen_build_functions_php(string $slug, array $fields, string $brand_name): string {
    $prefix = preg_replace('/[^a-z0-9_]/', '_', strtolower($slug)) ?: 'theme';
    $prefix = substr($prefix, 0, 20);

    // Construir registros del Customizer
    $customizer_settings = [];
    $customizer_controls = [];

    // -- Sección Contacto --
    if (!empty($fields['phones'])) {
        foreach ($fields['phones'] as $i => $phone) {
            $id = "{$prefix}_phone_{$i}";
            $label = $i === 0 ? 'WhatsApp / Principal' : "Teléfono #" . ($i + 1);
            $customizer_settings[] = "\$wp_customize->add_setting('{$id}', ['default' => '{$phone}', 'sanitize_callback' => 'sanitize_text_field']);";
            $customizer_controls[] = "\$wp_customize->add_control('{$id}', ['label' => '{$label}', 'description' => 'Solo dígitos con código país', 'section' => '{$prefix}_contact', 'type' => 'text']);";
        }
    }
    if (!empty($fields['emails'])) {
        foreach ($fields['emails'] as $i => $email) {
            $id = "{$prefix}_email_{$i}";
            $label = $i === 0 ? 'Email principal' : "Email #" . ($i + 1);
            $customizer_settings[] = "\$wp_customize->add_setting('{$id}', ['default' => '{$email}', 'sanitize_callback' => 'sanitize_email']);";
            $customizer_controls[] = "\$wp_customize->add_control('{$id}', ['label' => '{$label}', 'section' => '{$prefix}_contact', 'type' => 'email']);";
        }
    }
    foreach (($fields['socials'] ?? []) as $net => $url) {
        $id = "{$prefix}_{$net}";
        $customizer_settings[] = "\$wp_customize->add_setting('{$id}', ['default' => '{$url}', 'sanitize_callback' => 'esc_url_raw']);";
        $customizer_controls[] = "\$wp_customize->add_control('{$id}', ['label' => '" . ucfirst($net) . "', 'section' => '{$prefix}_contact', 'type' => 'url']);";
    }

    // -- Sección Precios --
    $prices_block = '';
    if (!empty($fields['prices'])) {
        foreach ($fields['prices'] as $i => $price) {
            $id = "{$prefix}_price_{$i}";
            $label = "Precio #" . ($i + 1);
            $customizer_settings[] = "\$wp_customize->add_setting('{$id}', ['default' => '" . addslashes($price) . "', 'sanitize_callback' => 'sanitize_text_field']);";
            $customizer_controls[] = "\$wp_customize->add_control('{$id}', ['label' => '{$label}', 'description' => 'Incluye símbolo \$', 'section' => '{$prefix}_prices', 'type' => 'text']);";
        }
    }

    $settings_code = implode("\n    ", $customizer_settings);
    $controls_code = implode("\n    ", $customizer_controls);

    $file = "<?php
/**
 * {$brand_name} — functions.php
 *
 * Tema WordPress nativo generado automáticamente por SuperCerebro.
 * Estructura modular con template-parts, Customizer dinámico.
 */

// ============================================================================
// SETUP
// ============================================================================

function {$prefix}_setup() {
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('html5', ['search-form','comment-form','comment-list','gallery','caption']);
    add_theme_support('automatic-feed-links');
    add_theme_support('custom-logo', ['height' => 60, 'width' => 60, 'flex-height' => true, 'flex-width' => true]);
}
add_action('after_setup_theme', '{$prefix}_setup');

function {$prefix}_hide_admin_bar() {
    if (!current_user_can('administrator')) show_admin_bar(false);
}
add_action('after_setup_theme', '{$prefix}_hide_admin_bar');

// ============================================================================
// ENQUEUE ASSETS
// ============================================================================

function {$prefix}_enqueue_assets() {
    \$theme_uri  = get_template_directory_uri();
    \$theme_path = get_template_directory();

    wp_enqueue_style('{$prefix}-main', get_stylesheet_uri(), [],
        file_exists(\$theme_path . '/style.css') ? filemtime(\$theme_path . '/style.css') : '1.0');

    // Lottie library (solo si hay archivos lottie en el tema)
    if (is_dir(\$theme_path . '/assets/lottie')) {
        wp_enqueue_script('lottie-web',
            'https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.12.2/lottie.min.js',
            [], '5.12.2', true);
    }

    if (file_exists(\$theme_path . '/assets/js/main.js')) {
        \$deps = is_dir(\$theme_path . '/assets/lottie') ? ['lottie-web'] : [];
        wp_enqueue_script('{$prefix}-main', \$theme_uri . '/assets/js/main.js',
            \$deps, filemtime(\$theme_path . '/assets/js/main.js'), true);
        wp_localize_script('{$prefix}-main', 'THEME_CONFIG', ['themeUrl' => \$theme_uri]);
    }
}
add_action('wp_enqueue_scripts', '{$prefix}_enqueue_assets');

// ============================================================================
// ADMIN BAR FIX
// ============================================================================

function {$prefix}_admin_bar_fix() {
    if (!is_admin_bar_showing()) return;
    echo '<style>'
        . 'body.admin-bar .nav{top:32px!important;}'
        . '@media screen and (max-width:782px){body.admin-bar .nav{top:46px!important;}}'
        . '@media screen and (max-width:600px){body.admin-bar .nav{top:0!important;}}'
        . '</style>';
}
add_action('wp_head', '{$prefix}_admin_bar_fix', 9999);

// ============================================================================
// CUSTOMIZER — Campos auto-detectados
// ============================================================================

function {$prefix}_customize_register(\$wp_customize) {
    \$wp_customize->add_panel('{$prefix}_panel', [
        'title'       => '" . addslashes($brand_name) . "',
        'description' => 'Edita teléfonos, precios y datos de contacto.',
        'priority'    => 10,
    ]);
    \$wp_customize->add_section('{$prefix}_contact', ['title' => 'Contacto', 'panel' => '{$prefix}_panel']);
    \$wp_customize->add_section('{$prefix}_prices',  ['title' => 'Precios',  'panel' => '{$prefix}_panel']);

    {$settings_code}

    {$controls_code}
}
add_action('customize_register', '{$prefix}_customize_register');

// ============================================================================
// HELPER: formato teléfono colombiano (573XXXXXXXXX → +57 3XX XXX XXXX)
// ============================================================================

function {$prefix}_format_phone(\$num) {
    \$n = preg_replace('/[^0-9]/', '', \$num);
    if (strlen(\$n) === 12 && substr(\$n, 0, 2) === '57') {
        return '+57 ' . substr(\$n, 2, 3) . ' ' . substr(\$n, 5, 3) . ' ' . substr(\$n, 8, 4);
    }
    return '+' . \$n;
}
";

    return $file;
}

/** Construye header.php con nav extraído + hooks WP obligatorios. */
function wpgen_build_header_php(string $nav_html, string $logo_filename = ''): string {
    // Reescribir referencias a imágenes relativas
    if ($logo_filename) {
        $nav_html = preg_replace(
            '/src="([^"\/]+\.(?:png|jpg|jpeg|svg|webp))"/i',
            'src="<?php echo esc_url(get_template_directory_uri() . \'/images/$1\'); ?>"',
            $nav_html
        );
    }
    // Si el nav tiene <a href="#" para el logo, cambiarlo a home_url
    $nav_html = preg_replace(
        '/<a href="#"\s+class="nav-logo"/',
        '<a href="<?php echo esc_url(home_url(\'/\')); ?>" class="nav-logo"',
        $nav_html
    );

    return '<?php
/**
 * Header — Compartido por todas las páginas.
 * Hooks WP obligatorios incluidos (ver feedback_wordpress_sites.md).
 */
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo(\'charset\'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>

' . $nav_html . '
';
}

/** Construye footer.php con departamentos/footer extraído + hooks WP. */
function wpgen_build_footer_php(string $footer_html): string {
    return '<?php
/**
 * Footer — Compartido por todas las páginas.
 */
?>

' . $footer_html . '

<?php wp_footer(); ?>
</body>
</html>
';
}

/** Construye un template-part PHP. Para "about" inyecta the_content(). */
function wpgen_build_template_part(string $name, string $html, string $theme_uri_var = ''): string {
    // Reemplazar src="archivo.png" relativos → template_directory_uri
    $html = preg_replace(
        '/src="([^"\/:]+\.(?:png|jpg|jpeg|svg|webp))"/i',
        'src="<?php echo esc_url(get_template_directory_uri() . \'/images/$1\'); ?>"',
        $html
    );

    // Para sección about/acerca/nosotros: inyectar the_content()
    $is_about = preg_match('/(about|acerca|nosotros|quien|empresa)/i', $name);
    if ($is_about) {
        // Buscar el primer <p>...</p> grande y reemplazarlo con the_content()
        $html = preg_replace_callback(
            '/(<div[^>]*class="[^"]*about[^"]*"[^>]*>)(.*?)(<\/div>)/is',
            function($m) {
                return $m[1] . '
        <?php
        $page_id = (int) get_option(\'page_on_front\');
        if (!$page_id && is_singular()) $page_id = get_queried_object_id();
        $raw = $page_id ? get_post_field(\'post_content\', $page_id) : \'\';
        if (trim($raw) !== \'\') {
            echo apply_filters(\'the_content\', $raw);
        } else {
            ?>' . trim($m[2]) . '<?php
        }
        ?>
        ' . $m[3];
            },
            $html, 1
        );
    }

    return '<?php
/**
 * Template-part: ' . esc_html_compat($name) . '
 */
?>
' . $html . '
';
}

/** Sanitiza string para usar como comentario PHP (escapa cierres de bloque). */
function esc_html_compat(string $s): string {
    return str_replace(['*' . '/', '<?php', '?>'], ['*\/','<? php','? >'], $s);
}

/**
 * Construye main.js con interactividad base + lazy-load de Lottie via fetch.
 * NO copia los scripts originales del HTML — los reemplaza con código limpio.
 */
function wpgen_build_main_js(array $scripts, array $lotties): string {
    // Detectar features que el HTML original tenía para generar el JS correcto
    $combined_scripts = implode("\n", $scripts);
    $has_hamburger     = stripos($combined_scripts, 'hamburger') !== false;
    $has_vehicle_toggle= stripos($combined_scripts, 'vehicle-toggle') !== false;
    $has_badge_rotator = stripos($combined_scripts, 'lottie-badge') !== false || stripos($combined_scripts, 'rotateBadge') !== false;

    $js = "// main.js — Generado automáticamente por SuperCerebro
(function() {
  'use strict';
  const CFG = window.THEME_CONFIG || {};
  const LOTTIE_BASE = (CFG.themeUrl || '') + '/assets/lottie/';

  // ─── Lazy-load Lottie con IntersectionObserver ───
  function lazyLottie(containerId, jsonFile, opts) {
    const el = document.getElementById(containerId);
    if (!el) return;
    const load = () => {
      if (typeof lottie === 'undefined') { setTimeout(load, 100); return; }
      fetch(LOTTIE_BASE + jsonFile)
        .then(r => r.json())
        .then(data => lottie.loadAnimation({
          container: el, renderer: 'svg', loop: true, autoplay: true,
          animationData: data, ...(opts || {})
        }))
        .catch(e => console.error('Lottie load failed:', containerId, e));
    };
    new IntersectionObserver(es => {
      if (es[0].isIntersecting) { load(); es[0].target._loaded = true; }
    }, { rootMargin: '200px' }).observe(el);
  }

";

    // Inyectar carga de cada Lottie con candidatos típicos de IDs
    foreach ($lotties as $name => $_) {
        $candidates = ['lottie-player', "{$name}-lottie", "lottie-{$name}", $name];
        foreach ($candidates as $cid) {
            $js .= "  lazyLottie(" . json_encode($cid) . ", " . json_encode($name . '.json') . ");\n";
        }
    }

    // Hamburger mobile menu (si lo había)
    if ($has_hamburger) {
        $js .= "
  // ─── Hamburger menu móvil ───
  const hamburger = document.getElementById('hamburger');
  if (hamburger) {
    hamburger.addEventListener('click', () => {
      const links = document.querySelector('.nav-links');
      if (!links) return;
      const open = links.style.display === 'flex';
      links.style.cssText = open ? '' :
        'display:flex;flex-direction:column;position:absolute;top:68px;left:0;right:0;background:var(--y,#fff);padding:20px 24px;gap:16px;border-top:1px solid rgba(0,0,0,.08)';
    });
  }
";
    }

    // Vehicle toggle (carro/moto) si lo había
    if ($has_vehicle_toggle) {
        $js .= "
  // ─── Vehicle toggle (carro/moto) ───
  document.querySelectorAll('.vehicle-toggle-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const target = btn.dataset.vehicle;
      document.querySelectorAll('.vehicle-toggle-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      document.querySelectorAll('.pricing-panel').forEach(p => {
        p.style.display = p.dataset.vehicle === target ? 'grid' : 'none';
      });
    });
  });
";
    }

    // Badge rotator (si lo había)
    if ($has_badge_rotator) {
        $js .= "
  // ─── Badge rotator ───
  const badges = ['✓ Mensaje 1','✓ Mensaje 2','✓ Mensaje 3'];
  let bi = 0;
  const badgeEl = document.getElementById('lottie-badge');
  if (badgeEl) {
    setInterval(() => {
      badgeEl.classList.add('fading');
      setTimeout(() => {
        bi = (bi + 1) % badges.length;
        badgeEl.textContent = badges[bi];
        badgeEl.classList.remove('fading');
      }, 290);
    }, 3200);
  }
";
    }

    $js .= "})();\n";
    return $js;
}

// =============================================================================
// 3. PIPELINE PRINCIPAL
// =============================================================================

/**
 * Pipeline completo: HTML → carpeta de tema en disco.
 *
 * @param string $html       HTML aprobado de la propuesta
 * @param array  $client     ['name', 'industry', 'url'] del cliente
 * @param string $output_dir Carpeta donde construir el tema (debe existir y estar vacía)
 * @return array Reporte: ['theme_slug', 'files_created', 'fields_detected', 'sections']
 */
function wpgen_run(string $html, array $client, string $output_dir): array {
    $brand = $client['name'] ?: 'Cliente';
    $slug = wpgen_slugify($brand) . '-theme';

    // Paso 1: Parsear HTML
    [$css, $html_no_style] = wpgen_extract_style($html);
    [$scripts, $html_clean] = wpgen_extract_scripts($html_no_style);
    $lotties = wpgen_extract_lottie($scripts);
    $sections = wpgen_split_sections($html_clean);

    // Paso 2: Detectar campos editables
    $fields = wpgen_detect_fields($html);

    // Paso 3: Crear estructura de carpetas
    @mkdir($output_dir . '/template-parts', 0755, true);
    @mkdir($output_dir . '/assets/js', 0755, true);
    @mkdir($output_dir . '/assets/lottie', 0755, true);
    @mkdir($output_dir . '/images', 0755, true);

    $files = [];

    // Paso 4: style.css
    $description = "Tema generado por SuperCerebro para {$brand}. Industria: " . ($client['industry'] ?: 'general') . ".";
    $style_content = wpgen_build_style_css($brand, $description, $css);
    file_put_contents("{$output_dir}/style.css", $style_content);
    $files[] = 'style.css';

    // Paso 5: functions.php
    file_put_contents("{$output_dir}/functions.php", wpgen_build_functions_php($slug, $fields, $brand));
    $files[] = 'functions.php';

    // Paso 6: Identificar nav y footer — primera y última sección si tienen marcas
    $nav_section = '';
    $footer_section = '';
    $body_sections = $sections;

    foreach (['nav', 'navigation', 'header'] as $key) {
        if (isset($sections[$key])) { $nav_section = $sections[$key]; unset($body_sections[$key]); break; }
    }
    foreach (['footer', 'departamentos', 'departments', 'floating-whatsapp', 'floating-wa'] as $key) {
        if (isset($sections[$key])) {
            $footer_section .= "\n\n" . $sections[$key];
            unset($body_sections[$key]);
        }
    }

    // Si no encontramos nav explícito, buscar <nav>...</nav> en el primer chunk
    if (!$nav_section && !empty($body_sections)) {
        $first = reset($body_sections);
        if (preg_match('/<nav[^>]*>.*?<\/nav>/is', $first, $m)) {
            $nav_section = $m[0];
            $first_key = key($body_sections);
            $body_sections[$first_key] = str_replace($m[0], '', $first);
        }
    }

    file_put_contents("{$output_dir}/header.php", wpgen_build_header_php($nav_section));
    $files[] = 'header.php';

    file_put_contents("{$output_dir}/footer.php", wpgen_build_footer_php($footer_section));
    $files[] = 'footer.php';

    // Paso 7: template-parts por cada sección del body
    $front_calls = [];
    foreach ($body_sections as $name => $section_html) {
        $part_file = "{$output_dir}/template-parts/{$name}.php";
        file_put_contents($part_file, wpgen_build_template_part($name, $section_html));
        $files[] = "template-parts/{$name}.php";
        $front_calls[] = "<?php get_template_part('template-parts/" . $name . "'); ?>";
    }

    // Paso 8: front-page.php que orquesta los template-parts
    $front_php = "<?php
/**
 * Front Page — Home generado automáticamente.
 * Cada sección es un template-part independiente.
 */
get_header(); ?>

" . implode("\n\n", $front_calls) . "

<?php get_footer();\n";
    file_put_contents("{$output_dir}/front-page.php", $front_php);
    $files[] = 'front-page.php';

    // Paso 9: page.php para páginas internas + index.php fallback + 404.php + single.php
    $page_php = "<?php
/**
 * Template páginas estáticas — usa the_content() para SEO con Yoast.
 */
get_header(); ?>
<main class=\"wrap\" style=\"padding:130px 24px 80px;min-height:60vh;\">
    <?php while (have_posts()) : the_post(); ?>
        <article class=\"editable-content\" style=\"max-width:780px;\">
            <h1><?php the_title(); ?></h1>
            <?php the_content(); ?>
        </article>
    <?php endwhile; ?>
</main>
<?php get_footer();\n";
    file_put_contents("{$output_dir}/page.php", $page_php);
    $files[] = 'page.php';

    $single_php = str_replace('the_title(); ?></h1>', 'the_title(); ?></h1><div style="font-size:.85rem;color:#666;margin-bottom:24px;"><?php echo esc_html(get_the_date()); ?></div>', $page_php);
    file_put_contents("{$output_dir}/single.php", $single_php);
    $files[] = 'single.php';

    file_put_contents("{$output_dir}/index.php", "<?php get_template_part('front-page');\n");
    $files[] = 'index.php';

    $err_php = "<?php get_header(); ?>
<main class=\"wrap\" style=\"padding:140px 24px;text-align:center;min-height:60vh;\">
    <h1 style=\"font-size:5rem;\">404</h1>
    <p>Esta página no existe.</p>
    <p><a href=\"<?php echo esc_url(home_url('/')); ?>\">← Volver al inicio</a></p>
</main>
<?php get_footer();\n";
    file_put_contents("{$output_dir}/404.php", $err_php);
    $files[] = '404.php';

    // Paso 10: assets/js/main.js
    if (!empty($scripts) || !empty($lotties)) {
        file_put_contents("{$output_dir}/assets/js/main.js", wpgen_build_main_js($scripts, $lotties));
        $files[] = 'assets/js/main.js';
    }

    // Paso 11: Lottie JSON files
    foreach ($lotties as $name => $json) {
        file_put_contents("{$output_dir}/assets/lottie/{$name}.json", $json);
        $files[] = "assets/lottie/{$name}.json";
    }

    // Paso 12: README.txt con instrucciones para el cliente
    $readme = "TEMA WORDPRESS — {$brand}
========================

Generado automáticamente por SuperCerebro.

INSTALACIÓN
-----------
1. WordPress Admin → Apariencia → Temas → Añadir nuevo → Subir tema
2. Selecciona el archivo ZIP
3. Activar
4. Ajustes → Lectura → Página de inicio: Una página estática → crea/selecciona 'Inicio'

EDITAR PRECIOS Y CONTACTO
-------------------------
Apariencia → Personalizar → {$brand}
  - Sección Contacto: teléfonos, emails, redes sociales
  - Sección Precios: tarifas editables

SEO (Yoast)
-----------
Edita la página 'Inicio' desde el editor de WordPress.
El texto que pongas ahí (con Gutenberg) es lo que Yoast analizará.
Pon el contenido SEO-friendly con la focus keyword.

Generado: " . date('Y-m-d H:i') . "
";
    file_put_contents("{$output_dir}/README.txt", $readme);
    $files[] = 'README.txt';

    return [
        'theme_slug'       => $slug,
        'files_created'    => count($files),
        'fields_detected'  => $fields,
        'sections'         => array_keys($body_sections),
        'has_nav'          => !empty($nav_section),
        'has_footer'       => !empty($footer_section),
        'lotties'          => array_keys($lotties),
    ];
}

/** Empaqueta una carpeta como ZIP. Devuelve path del ZIP creado. */
function wpgen_zip(string $source_dir, string $zip_path): bool {
    // Intento 1: ZipArchive (extensión PHP zip)
    if (class_exists('ZipArchive')) {
        $zip = new ZipArchive();
        if ($zip->open($zip_path, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
            $base_name = basename($source_dir);
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source_dir, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::LEAVES_ONLY
            );
            foreach ($files as $file) {
                if ($file->isDir()) continue;
                $filePath = $file->getRealPath();
                $relativePath = $base_name . '/' . substr($filePath, strlen($source_dir) + 1);
                $zip->addFile($filePath, $relativePath);
            }
            $zip->close();
            if (file_exists($zip_path)) return true;
        }
    }

    // Intento 2: comando zip del sistema (fallback cuando la extensión no está habilitada)
    if (function_exists('exec')) {
        $parent = dirname($source_dir);
        $folder = basename($source_dir);
        $zip_escaped = escapeshellarg($zip_path);
        $folder_escaped = escapeshellarg($folder);
        exec("cd " . escapeshellarg($parent) . " && zip -r {$zip_escaped} {$folder_escaped} 2>&1", $out, $code);
        if ($code === 0 && file_exists($zip_path)) return true;
    }

    return false;
}

// =============================================================================
function wpgen_rmdir_recursive(string $dir): void {
    if (!is_dir($dir)) return;
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $path = $dir . '/' . $item;
        if (is_dir($path)) wpgen_rmdir_recursive($path);
        else @unlink($path);
    }
    @rmdir($dir);
}

$pdo = new PDO('mysql:host=localhost;dbname=dimark93_supercerebro;charset=utf8mb4','dimark93_supercerebro','Cerebro#2024!',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare("SELECT p.proposal_final, c.name cn, c.industry, c.url FROM dm_proposals p JOIN dm_clients c ON c.id=p.client_id WHERE p.id=31");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row || empty($row['proposal_final'])) die("ERROR: sin HTML\n");
echo "Cliente: {$row['cn']}\n";
echo "HTML: ".strlen($row['proposal_final'])." chars\n";
$client=['name'=>$row['cn'],'industry'=>$row['industry']?:'Marketing Digital','url'=>$row['url']?:'dimark.co'];
$slug=wpgen_slugify($client['name']).'-theme';
$work_dir=sys_get_temp_dir().'/'.$slug.'-'.uniqid();
@mkdir($work_dir,0755,true);
echo "Procesando...\n";
try {
    $report=wpgen_run($row['proposal_final'],$client,$work_dir);
    echo "Archivos: {$report['files_created']}\n";
    echo "Secciones: ".implode(', ',$report['sections'])."\n";
    $zip_dir='/home/dimark93/public_html/supercerebro/uploads/themes';
    @mkdir($zip_dir,0755,true);
    $zip_fn=$slug.'-'.date('Ymd-His').'.zip';
    $zip_path=$zip_dir.'/'.$zip_fn;
    if(wpgen_zip($work_dir,$zip_path)){
        echo "ZIP OK: $zip_fn (".number_format(filesize($zip_path))." bytes)\n";
        echo "URL: https://dimark.co/supercerebro/uploads/themes/$zip_fn\n";
        $pdo->prepare("UPDATE dm_proposals SET notes=? WHERE id=31")->execute(["wp_theme_zip:uploads/themes/$zip_fn"]);
    } else {
        echo "ERROR: ZIP failed\n";
    }
} catch(Exception $e){ echo "ERROR: ".$e->getMessage()."\n"; }
wpgen_rmdir_recursive($work_dir);
echo "Listo\n";
