<?php
// Convertir Lead a Cliente con clave provisional
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

function isLoggedIn(){ return isset($_SESSION['user_id']); }
if (!isLoggedIn()) { header('Location: ' . get_base_path() . '/index.php?module=auth&action=login'); exit; }

$lead_id = isset($_POST['lead_id']) ? intval($_POST['lead_id']) : (isset($_GET['lead_id']) ? intval($_GET['lead_id']) : 0);
if ($lead_id <= 0) { http_response_code(400); echo 'Lead inválido'; exit; }

$db = Database::getInstance();
$pdo = $db->getConnection();

// Obtener lead
$stmt = $pdo->prepare("SELECT * FROM leads WHERE id = ?");
$stmt->execute([$lead_id]);
$lead = $stmt->fetch();
if (!$lead) { http_response_code(404); echo 'Lead no encontrado'; exit; }

// Si ya existe cliente con ese email, reutilizar y solo marcar lead como convertido
$stmt = $pdo->prepare("SELECT * FROM clients WHERE email = ?");
$stmt->execute([$lead['email']]);
$existingClient = $stmt->fetch();

$pdo->beginTransaction();
try {
    if (!$existingClient) {
        // Generar clave provisional
        $plain = bin2hex(random_bytes(4)); // 8 hex chars
        $hash = password_hash($plain, PASSWORD_DEFAULT);

        // Crear cliente
        $ins = $pdo->prepare("INSERT INTO clients (lead_id, email, first_name, last_name, phone, status, password_hash, created_at) VALUES (?,?,?,?,?,'active',?,NOW())");
        $ins->execute([$lead['id'], $lead['email'], $lead['first_name'], $lead['last_name'], $lead['phone'], $hash]);
        $clientId = $pdo->lastInsertId();

        // Registrar actividad de sistema en lead
        $act = $pdo->prepare("INSERT INTO lead_activities (lead_id, type, subject, description, status, created_at, created_by) VALUES (?,?,?,?, 'completed', NOW(), ?)");
        $act->execute([$lead['id'], 'system', 'Conversión a Cliente', 'Lead convertido a cliente. Clave provisional generada.', $_SESSION['user_id']]);

        // Guardar la clave provisional en sesión para mostrar una sola vez
        $_SESSION['client_provisional_password'] = $plain;
        $_SESSION['client_created_id'] = $clientId;
    } else {
        $clientId = $existingClient['id'];
    }

    // Sincronizar actividades del lead al cliente
    try {
        $pdo->prepare('CREATE TABLE IF NOT EXISTS client_activities (
            id INT AUTO_INCREMENT PRIMARY KEY,
            client_id INT NOT NULL,
            type ENUM("call","email","meeting","note","task","system") NOT NULL,
            subject VARCHAR(255) NOT NULL,
            description TEXT,
            status ENUM("pending","completed","cancelled") DEFAULT "completed",
            scheduled_at DATETIME NULL,
            duration_min INT NULL,
            completed_at DATETIME NULL,
            created_by INT NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE,
            FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
            INDEX idx_client_id (client_id), INDEX idx_type (type), INDEX idx_status (status), INDEX idx_scheduled_at (scheduled_at), INDEX idx_created_by (created_by), INDEX idx_created_at (created_at)
        ) ENGINE=InnoDB')->execute();
        // Insertar actividades si no existen aún para este cliente
        $acts = $pdo->prepare('SELECT type, subject, description, status, scheduled_at, duration_min, completed_at, created_by, created_at FROM lead_activities WHERE lead_id = ?');
        $acts->execute([$lead['id']]);
        $rows = $acts->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as $a) {
            // Evitar duplicados básicos por subject+created_at
            $exists = $pdo->prepare('SELECT 1 FROM client_activities WHERE client_id=? AND subject=? AND created_at=? LIMIT 1');
            $exists->execute([$clientId, $a['subject'], $a['created_at']]);
            if (!$exists->fetchColumn()) {
                $insA = $pdo->prepare('INSERT INTO client_activities (client_id, type, subject, description, status, scheduled_at, duration_min, completed_at, created_by, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)');
                $insA->execute([$clientId, $a['type'], $a['subject'], $a['description'], $a['status'], $a['scheduled_at'], $a['duration_min'], $a['completed_at'], $a['created_by'], $a['created_at']]);
            }
        }
    } catch (Throwable $__) {}

    // Marcar lead como convertido
    $upd = $pdo->prepare("UPDATE leads SET status = 'converted', updated_at = NOW() WHERE id = ?");
    $upd->execute([$lead['id']]);

    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo 'Error en la conversión: ' . $e->getMessage();
    exit;
}

// Redirigir al detalle del cliente (subcarpeta-aware)
header('Location: ' . module_url('clients/view.php') . '?id=' . intval($clientId));
exit;
?>
