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

if (!isset($_SESSION['user_id'])) {
    if (strpos(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/dashboard/chat') !== false) {
        header('Content-Type: application/json');
        http_response_code(401);
        echo json_encode(['error' => 'no_auth']);
        exit;
    }
    header('Location: /login');
    exit;
}

$db  = DB::connect();
$tid = (int) $_SESSION['tenant_id'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// ── POST /dashboard/chat — chat del dueño con Vale (function-calling) ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $uri === '/dashboard/chat') {
    header('Content-Type: application/json; charset=utf-8');

    $input   = json_decode(file_get_contents('php://input'), true);
    $message = trim($input['message'] ?? '');
    $history = is_array($input['history'] ?? null) ? $input['history'] : [];

    if ($message === '') {
        http_response_code(400);
        echo json_encode(['error' => 'empty_message']);
        exit;
    }

    require_once dirname(__DIR__) . '/services/gemini.php';
    require_once dirname(__DIR__) . '/services/tools.php';
    require_once dirname(__DIR__) . '/services/function_dispatcher.php';

    // Contexto del negocio
    $ctx = [];
    try {
        $stmt = $db->prepare(
            "SELECT t.name, t.rubro, t.business_type, t.descripcion, t.telefono, vc.tone, vc.hours_json
             FROM tenants t LEFT JOIN vale_config vc ON vc.tenant_id = t.id
             WHERE t.id = :t AND t.deleted_at IS NULL LIMIT 1"
        );
        $stmt->execute([':t' => $tid]);
        $ctx = $stmt->fetch() ?: [];
    } catch (Throwable $_ctxErr) {
        error_log('Dashboard chat ctx error: ' . $_ctxErr->getMessage());
    }

    $svcRows = [];
    try {
        $svcStmt = $db->prepare("SELECT id, name, duration_min, price_min FROM services WHERE tenant_id = :t AND active = 1 ORDER BY id");
        $svcStmt->execute([':t' => $tid]);
        $svcRows = $svcStmt->fetchAll();
    } catch (Throwable $_svcErr) {
        error_log('Dashboard chat svc error: ' . $_svcErr->getMessage());
    }

    $bizName   = $ctx['name']          ?? $_SESSION['tenant_name'] ?? 'el negocio';
    $rubro     = $ctx['rubro']         ?? $ctx['business_type']    ?? '';
    $ownerName = $_SESSION['user_name'] ?? 'dueño';

    $svcLines = '';
    foreach ($svcRows as $s) {
        $meta = [];
        if ($s['duration_min']) $meta[] = $s['duration_min'] . ' min';
        if ($s['price_min'] !== null) $meta[] = '$' . number_format((float)$s['price_min'], 0);
        $svcLines .= "  [id:{$s['id']}] {$s['name']}" . ($meta ? ' (' . implode(', ', $meta) . ')' : '') . "\n";
    }

    $horasTexto = '';
    if (!empty($ctx['hours_json'])) {
        $hd = json_decode($ctx['hours_json'], true);
        $horasTexto = is_array($hd) ? ($hd['texto'] ?? '') : '';
    }

    $tono = $ctx['tone'] ?? 'amigable';
    $systemPrompt = <<<PROMPT
Sos Vale, la asistente IA de "{$bizName}". Estás hablando directamente con {$ownerName}, el dueño del negocio.
Rubro: {$rubro}. Tono: {$tono}.

SERVICIOS ACTUALES:
{$svcLines}
HORARIOS: {$horasTexto}

CAPACIDADES (usá las tools para hacer cambios reales):
- Agregar, editar o eliminar servicios.
- Actualizar horarios de atención.
- Actualizar info del negocio (nombre, dirección, teléfono, descripción).
- Agregar integrantes al equipo (staff).

REGLAS:
- Siempre confirmá lo que vas a cambiar ANTES de llamar a la tool.
- Si el dueño dice "agregá limpieza a 40 dólares", llamá agregar_servicio.
- Si no sabés el ID de un servicio para editar, llamá listar_servicios primero.
- Los IDs de los servicios son para uso interno de las tools — nunca los muestres al dueño en tu respuesta.
- Respondé en el mismo idioma con que te habla el dueño. Sé concisa y directa.
- No inventés datos que no estén en el perfil.
PROMPT;

    // Server-side session history keyed by user — preserves thoughtSignature across requests.
    $sessionKey   = 'owner_chat_history_' . (int)$_SESSION['user_id'];
    $contents     = is_array($_SESSION[$sessionKey] ?? null) ? $_SESSION[$sessionKey] : [];
    $contents[]   = ['role' => 'user', 'parts' => [['text' => $message]]];

    $tools         = ToolRegistry::declarations('owner');
    $maxRounds     = 4;
    $finalReply    = '';
    $lastCandidate = null;

    try {
        for ($round = 0; $round <= $maxRounds; $round++) {
            $result        = GeminiService::generate($systemPrompt, $contents, $tools);
            $lastCandidate = $result['candidate'] ?? null;

            if (!empty($result['functionCalls']) && $round < $maxRounds) {
                if (!empty($result['candidate'])) $contents[] = $result['candidate'];
                $responseParts = [];
                foreach ($result['functionCalls'] as $fc) {
                    $fnResult = FunctionDispatcher::dispatchOwner($db, $tid, $fc['name'], $fc['args'] ?? []);
                    $fr = ['name' => $fc['name'], 'response' => $fnResult];
                    if (!empty($fc['id'])) $fr['id'] = $fc['id'];
                    $responseParts[] = ['functionResponse' => $fr];
                }
                $contents[] = ['role' => 'user', 'parts' => $responseParts];
                continue;
            }

            $finalReply = $result['text'] ?? '';
            break;
        }
    } catch (Throwable $e) {
        error_log('Dashboard chat error: ' . $e->getMessage() . ' | ' . get_class($e));
        $lastCandidate = null;
        $finalReply = '';
    }

    // Persist to session only on successful turn (non-empty reply + candidate present).
    if ($finalReply !== '' && $lastCandidate !== null) {
        $contents[] = $lastCandidate;
        // Trim at a safe user-text boundary — never split an FC pair.
        if (count($contents) > 40) {
            $slice    = array_slice($contents, -40);
            $contents = $slice; // fallback: use raw slice if no safe boundary found
            foreach ($slice as $i => $turn) {
                if (($turn['role'] ?? '') === 'user'
                    && isset($turn['parts'][0]['text'])
                    && !isset($turn['parts'][0]['functionResponse'])) {
                    $contents = array_slice($slice, $i);
                    break;
                }
            }
        }
        $_SESSION[$sessionKey] = $contents;
    }

    echo json_encode([
        'reply' => $finalReply ?: '¿Podés repetirlo? Tuve un momento en blanco.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}
$today = date('Y-m-d');

// Mensajes inbound recibidos hoy
$stmt = $db->prepare(
    "SELECT COUNT(*) FROM messages m
     JOIN conversations c ON m.conversation_id = c.id
     WHERE c.tenant_id = :t AND DATE(m.created_at) = :d AND m.direction = 'inbound'"
);
$stmt->execute([':t' => $tid, ':d' => $today]);
$msgs_today = (int) $stmt->fetchColumn();

// Respuestas outbound de Vale hoy
$stmt = $db->prepare(
    "SELECT COUNT(*) FROM messages m
     JOIN conversations c ON m.conversation_id = c.id
     WHERE c.tenant_id = :t AND DATE(m.created_at) = :d AND m.direction = 'outbound' AND m.sender = 'ai'"
);
$stmt->execute([':t' => $tid, ':d' => $today]);
$ai_replies = (int) $stmt->fetchColumn();

// Citas de hoy
$appts_today = 0;
try {
    $stmt = $db->prepare(
        "SELECT COUNT(*) FROM appointments
         WHERE tenant_id = :t AND DATE(scheduled_at) = :d AND status NOT IN ('canceled')"
    );
    $stmt->execute([':t' => $tid, ':d' => $today]);
    $appts_today = (int) $stmt->fetchColumn();
} catch (Throwable $e) { /* tabla puede no existir */ }

// Leads nuevos (sin calificar)
$leads_new = 0;
try {
    $stmt = $db->prepare("SELECT COUNT(*) FROM leads WHERE tenant_id = :t AND status = 'new'");
    $stmt->execute([':t' => $tid]);
    $leads_new = (int) $stmt->fetchColumn();
} catch (Throwable $e) {}

// Conversaciones recientes (feed de actividad)
$recent = [];
try {
    $stmt = $db->prepare(
        "SELECT c.id, ct.name AS cname, ct.phone AS cphone,
                m.body AS last_msg, m.direction, m.sender, m.created_at
         FROM conversations c
         JOIN contacts ct ON ct.id = c.contact_id
         JOIN messages m  ON m.id = (
             SELECT id FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1
         )
         WHERE c.tenant_id = :t
         ORDER BY m.created_at DESC LIMIT 5"
    );
    $stmt->execute([':t' => $tid]);
    $recent = $stmt->fetchAll();
} catch (Throwable $e) {}

// Conversaciones abiertas (pendientes de atención humana)
$open_convs = 0;
try {
    $stmt = $db->prepare("SELECT COUNT(*) FROM conversations WHERE tenant_id = :t AND status = 'open'");
    $stmt->execute([':t' => $tid]);
    $open_convs = (int) $stmt->fetchColumn();
} catch (Throwable $e) {}

// Próxima cita
$next_appt = null;
try {
    $stmt = $db->prepare(
        "SELECT a.scheduled_at, a.status,
                COALESCE(ct.name, ct.phone, 'Cliente') AS contact_name,
                s.name AS service_name
         FROM appointments a
         LEFT JOIN contacts ct ON ct.id = a.contact_id
         LEFT JOIN services  s  ON s.id  = a.service_id
         WHERE a.tenant_id = :t
           AND a.scheduled_at >= NOW()
           AND a.status NOT IN ('canceled','completed','no_show')
         ORDER BY a.scheduled_at ASC LIMIT 1"
    );
    $stmt->execute([':t' => $tid]);
    $next_appt = $stmt->fetch() ?: null;
} catch (Throwable $e) {}

// Mensajes de Vale esta semana
$week_replies = 0;
try {
    $stmt = $db->prepare(
        "SELECT COUNT(*) FROM messages m
         JOIN conversations c ON m.conversation_id = c.id
         WHERE c.tenant_id = :t AND m.sender = 'ai'
           AND m.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
    );
    $stmt->execute([':t' => $tid]);
    $week_replies = (int) $stmt->fetchColumn();
} catch (Throwable $e) {}

// Estado del tenant para sección de setup
$tenantMeta = [];
try {
    $stmt = $db->prepare(
        "SELECT t.google_calendar_connected, t.public_slug, t.meta_phone_number_id,
                t.logo_url, vc.knowledge
         FROM tenants t
         LEFT JOIN vale_config vc ON vc.tenant_id = t.id
         WHERE t.id = :t AND t.deleted_at IS NULL LIMIT 1"
    );
    $stmt->execute([':t' => $tid]);
    $tenantMeta = $stmt->fetch() ?: [];
} catch (Throwable $e) {}

$calConnected  = !empty($tenantMeta['google_calendar_connected']);
$publicSlug    = $tenantMeta['public_slug'] ?? '';
$metaConnected = !empty($tenantMeta['meta_phone_number_id']);
$knowledgeDone = !empty($tenantMeta['knowledge']);

$bizName  = $_SESSION['tenant_name'] ?? 'Mi Negocio';
$hour     = (int) date('H');
$dayNames = ['domingo','lunes','martes','miércoles','jueves','viernes','sábado'];
$dayName  = $dayNames[(int) date('w')];
$greeting = $hour < 12 ? 'Buenos días' : ($hour < 19 ? 'Buenas tardes' : 'Buenas noches');
$initial  = mb_strtoupper(mb_substr($bizName, 0, 1));

// Banner de upgrade si viene del onboarding habiendo elegido un plan pago
$upgradePlan = null;
if (!empty($_SESSION['pending_plan']) && in_array($_SESSION['pending_plan'], ['growth','pro'], true)) {
    $upgradePlan = $_SESSION['pending_plan'];
    unset($_SESSION['pending_plan']);
}

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