<?php
// Llamar directamente al pipeline wpgen sin capa HTTP
chdir('/home/dimark93/public_html/supercerebro');
require_once 'db.php';

// Incluir solo las funciones del generador (sin el dispatcher)
$code = file_get_contents('api/wp-theme-generator.php');
// Extraer solo hasta el dispatcher
$code = preg_replace('/\/\/ =+\s*4\. ACTION DISPATCHER.*$/s', '', $code);
// Quitar el <?php inicial
$code = preg_replace('/^<\?php\s*/', '', $code);
eval($code);

// Obtener propuesta 31
$stmt = $pdo->prepare("SELECT p.proposal_final, c.name AS client_name, c.industry, c.url FROM dm_proposals p JOIN dm_clients c ON c.id=p.client_id WHERE p.id=31");
$stmt->execute();
$prop = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$prop || empty($prop['proposal_final'])) {
    die("ERROR: propuesta no encontrada o sin HTML\n");
}

$client = [
    'name'     => $prop['client_name'],
    'industry' => $prop['industry'] ?? 'Marketing Digital',
    'url'      => $prop['url'] ?? 'dimark.co',
];

echo "Cliente: {$client['name']}\n";
echo "HTML size: " . strlen($prop['proposal_final']) . " chars\n";

$slug = wpgen_slugify($client['name']) . '-theme';
$work_dir = sys_get_temp_dir() . '/' . $slug . '-' . uniqid();
@mkdir($work_dir, 0755, true);

echo "Work dir: $work_dir\n";

$report = wpgen_run($prop['proposal_final'], $client, $work_dir);
echo "Files created: {$report['files_created']}\n";
echo "Sections: " . implode(', ', $report['sections']) . "\n";

$zip_dir  = __DIR__ . '/uploads/themes';
@mkdir($zip_dir, 0755, true);
$zip_filename = $slug . '-' . date('Ymd-His') . '.zip';
$zip_path = $zip_dir . '/' . $zip_filename;

if (wpgen_zip($work_dir, $zip_path)) {
    $size = filesize($zip_path);
    echo "ZIP OK: $zip_filename ($size bytes)\n";
    echo "URL: https://dimark.co/supercerebro/uploads/themes/$zip_filename\n";
} else {
    echo "ERROR: ZIP failed\n";
}

// Limpiar temp
function rrmdir($dir) {
    if (!is_dir($dir)) return;
    foreach(scandir($dir) as $f) {
        if ($f==='.'||$f==='..') continue;
        $p="$dir/$f";
        is_dir($p)?rrmdir($p):unlink($p);
    }
    rmdir($dir);
}
rrmdir($work_dir);
