<?php
/**
 * Migración: añadir columna country a leads y asignar países a 8 leads
 */

// Iniciar sesión
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Definir BASE_PATH
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__))); // .../simple_crm
}

// Includes de BD
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Helper de autenticación
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Requiere login
if (!isLoggedIn()) {
    header('Content-Type: text/plain; charset=utf-8');
    http_response_code(401);
    echo "No autorizado. Inicia sesión para ejecutar la migración.";
    exit;
}

$db = getDB()->getConnection();

$messages = [];

try {
    // Verificar existencia de columna country
    $stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'leads' AND COLUMN_NAME = 'country'");
    $stmt->execute();
    $exists = (int)$stmt->fetchColumn() > 0;

    if (!$exists) {
        $db->exec("ALTER TABLE leads ADD COLUMN country VARCHAR(100) NULL AFTER phone");
        $messages[] = "Columna 'country' añadida a la tabla 'leads'.";
    } else {
        $messages[] = "Columna 'country' ya existe; no se modifica el esquema.";
    }

    // Seleccionar hasta 8 leads sin país
    $stmtSel = $db->query("SELECT id FROM leads WHERE country IS NULL OR country = '' ORDER BY id ASC LIMIT 8");
    $leadIds = $stmtSel->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($leadIds)) {
        $countries = ['Spain','Mexico','Argentina','Chile','Colombia','Peru','United States','Canada'];
        $stmtUpd = $db->prepare("UPDATE leads SET country = ? WHERE id = ?");
        $assigned = [];
        foreach ($leadIds as $i => $leadId) {
            $country = $countries[$i % count($countries)];
            $stmtUpd->execute([$country, $leadId]);
            $assigned[] = [
                'lead_id' => (int)$leadId,
                'country' => $country
            ];
        }
        $messages[] = "Se asignaron países a " . count($assigned) . " lead(s).";
    } else {
        $messages[] = "No se encontraron leads sin país para actualizar.";
    }
} catch (Exception $e) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Error en migración: " . $e->getMessage();
    exit;
}

// Salida HTML simple
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Resultado Migración Country en Leads</title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
    <style>
        .migration-card { max-width: 720px; margin: 24px auto; padding: 16px; border:1px solid #e5e7eb; border-radius:12px; }
        .migration-title { display:flex; align-items:center; gap:8px; }
        .badge { display:inline-block; background:#eef2ff; color:#3730a3; padding:2px 8px; border-radius:999px; font-size:12px; margin-left:8px; }
        ul { padding-left: 18px; }
    </style>
    </head>
<body>
    <div class="migration-card">
        <div class="migration-title">
            <span>🗃️</span>
            <h2>Actualización de País en Leads</h2>
        </div>
        <div>
            <?php foreach ($messages as $m): ?>
                <p><?php echo htmlspecialchars($m); ?></p>
            <?php endforeach; ?>
        </div>
        <div style="margin-top:12px;">
            <a class="btn-primary" href="/test/simple_crm/index.php?module=leads">Volver a Leads</a>
        </div>
    </div>
</body>
</html>