<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Solo el dueño autenticado puede onboardear su negocio.
if (!isset($_SESSION['user_id'])) {
    if ($uri === '/onboarding/message') {
        header('Content-Type: application/json');
        http_response_code(401);
        echo json_encode(['error' => 'no_autenticado']);
        exit;
    }
    header('Location: /login');
    exit;
}

require_once dirname(__DIR__) . '/services/agent_service.php';

$tenant_id = (int) $_SESSION['tenant_id'];
$db = DB::connect();

/** Foto del estado actual de la config (para el panel en vivo). */
function onboarding_snapshot(PDO $db, int $tid): array {
    $stmt = $db->prepare("SELECT name, business_type, rubro, especialidad, profile_kind, onboarding_status FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
    $stmt->execute([':t' => $tid]);
    $t = $stmt->fetch() ?: [];
    $stmt = $db->prepare("SELECT name, duration_min, price_min FROM services WHERE tenant_id = :t AND active = 1 ORDER BY id");
    $stmt->execute([':t' => $tid]);
    return [
        'name'         => $t['name']              ?? '',
        'rubro'        => $t['rubro']             ?? $t['business_type'] ?? '',
        'especialidad' => $t['especialidad']      ?? null,
        'profile_kind' => $t['profile_kind']      ?? '',
        'status'       => $t['onboarding_status'] ?? '',
        'services'     => $stmt->fetchAll(),
    ];
}

// --- Endpoint del chat (JSON) ---
if ($uri === '/onboarding/message') {
    header('Content-Type: application/json; charset=utf-8');
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => 'method_not_allowed']);
        exit;
    }
    $input = json_decode(file_get_contents('php://input'), true);
    $message = trim((string) ($input['message'] ?? ''));
    $history = is_array($input['history'] ?? null) ? $input['history'] : [];
    if ($message === '') {
        http_response_code(400);
        echo json_encode(['error' => 'mensaje_vacio']);
        exit;
    }

    $stmt = $db->prepare("SELECT * FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
    $stmt->execute([':t' => $tenant_id]);
    $tenant = $stmt->fetch();
    if (!$tenant) {
        http_response_code(404);
        echo json_encode(['error' => 'tenant_no_encontrado']);
        exit;
    }

    try {
        $result = AgentService::handleOnboarding($db, $tenant, $history, $message);
    } catch (Throwable $e) {
        error_log('Onboarding failed: ' . $e->getMessage());
        try { AgentService::logError($db, $tenant_id, 'onboarding_error', $e); } catch (Throwable $_) {}
        http_response_code(500);
        echo json_encode(['reply' => null, 'done' => false, 'options' => [], 'config' => []]);
        exit;
    }

    $snap = onboarding_snapshot($db, $tenant_id);
    // Mantener el nombre en sesión sincronizado (Vale pudo renombrar el negocio).
    if (!empty($snap['name'])) {
        $_SESSION['tenant_name'] = $snap['name'];
    }
    echo json_encode([
        'reply' => $result['text'],
        'done' => $result['done'],
        'options' => $result['options'] ?? [],
        'config' => $snap,
    ]);
    exit;
}

// --- POST: guardar datos del formulario de onboarding ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $uri === '/onboarding') {
    header('Content-Type: application/json; charset=utf-8');
    $name  = trim($_POST['name']          ?? '');
    $rubro = trim($_POST['business_type'] ?? '');
    if ($name !== '') {
        $db->prepare("UPDATE tenants SET name = :n, business_type = :r WHERE id = :t")
           ->execute([':n' => $name, ':r' => $rubro, ':t' => $tenant_id]);
        $_SESSION['tenant_name'] = $name;
    }
    $db->prepare("UPDATE tenants SET onboarding_status = 'live' WHERE id = :t")
       ->execute([':t' => $tenant_id]);
    $greeting = $name
        ? "¡Hola! Soy Vale, el asistente de $name. ¿En qué te puedo ayudar?"
        : '¡Hola! Soy Vale, tu asistente virtual. ¿En qué te puedo ayudar?';
    $db->prepare(
        "INSERT INTO vale_config (tenant_id, greeting) VALUES (:t, :g)
         ON DUPLICATE KEY UPDATE greeting = VALUES(greeting)"
    )->execute([':t' => $tenant_id, ':g' => $greeting]);

    // Capa A: bienvenida por WhatsApp al dueño
    try {
        require_once dirname(__DIR__) . '/services/platform_whatsapp.php';
        PlatformWhatsApp::sendBienvenida($db, $tenant_id, $name ?: 'tu negocio');
    } catch (Throwable $_e) {}

    echo json_encode(['ok' => true]);
    exit;
}

// --- GET: pantalla de onboarding ---
$stmt = $db->prepare("SELECT onboarding_status, preferred_channel FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
$stmt->execute([':t' => $tenant_id]);
$tenantRow = $stmt->fetch();
if (($tenantRow['onboarding_status'] ?? '') === 'live') {
    header('Location: /inicio');
    exit;
}

// Idioma: viene de la bienvenida (?lang) o del default ya guardado.
if (isset($_GET['lang'])) {
    $lang = $_GET['lang'] === 'en' ? 'en' : 'es';
    $db->prepare(
        "INSERT INTO vale_config (tenant_id, default_locale) VALUES (:t, :l)
         ON DUPLICATE KEY UPDATE default_locale = VALUES(default_locale)"
    )->execute([':t' => $tenant_id, ':l' => $lang]);
} else {
    $stmt = $db->prepare("SELECT default_locale FROM vale_config WHERE tenant_id = :t LIMIT 1");
    $stmt->execute([':t' => $tenant_id]);
    $lang = $stmt->fetchColumn() === 'en' ? 'en' : 'es';
}

// País elegido en el wizard -> setea timezone, moneda e idioma del negocio.
if (!empty($_GET['country'])) {
    require_once dirname(__DIR__) . '/services/countries.php';
    $c = Countries::get($_GET['country']);
    if ($c) {
        $db->prepare("UPDATE tenants SET country = :co, currency = :cu, timezone = :tz, locale = :loc WHERE id = :t")
           ->execute([':co' => strtoupper($_GET['country']), ':cu' => $c['currency'], ':tz' => $c['tz'], ':loc' => $lang, ':t' => $tenant_id]);
    }
}

// Canal elegido en el wizard -> guarda preferencia y expone a la vista.
$validChannels = ['web', 'whatsapp', 'sms'];
if (!empty($_GET['channel']) && in_array($_GET['channel'], $validChannels, true)) {
    $channel = $_GET['channel'];
    try {
        $db->prepare("UPDATE tenants SET preferred_channel = :ch WHERE id = :t")
           ->execute([':ch' => $channel, ':t' => $tenant_id]);
    } catch (Throwable $e) {
        error_log('preferred_channel update failed: ' . $e->getMessage());
    }
} else {
    $channel = in_array($tenantRow['preferred_channel'] ?? 'web', $validChannels, true)
        ? $tenantRow['preferred_channel']
        : 'web';
}

require dirname(__DIR__) . '/views/onboarding.php';
