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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: /login');
    exit;
}

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

// Si el negocio todavía no está configurado, mandar al onboarding conversacional.
$stmt = $db->prepare("SELECT onboarding_status FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
$stmt->execute([':t' => $tenant_id]);
if ($stmt->fetchColumn() !== 'live') {
    header('Location: /onboarding');
    exit;
}

// Fetch conversations for this tenant
$stmt = $db->prepare("
    SELECT 
        c.id, 
        c.status, 
        c.updated_at, 
        co.name as contact_name, 
        co.phone as contact_phone,
        (SELECT body FROM messages WHERE conversation_id = c.id ORDER BY id DESC LIMIT 1) as last_message_body,
        (SELECT created_at FROM messages WHERE conversation_id = c.id ORDER BY id DESC LIMIT 1) as last_message_time
    FROM conversations c
    JOIN contacts co ON c.contact_id = co.id
    WHERE c.tenant_id = :tenant_id
    ORDER BY c.updated_at DESC
");
$stmt->execute([':tenant_id' => $tenant_id]);
$conversations = $stmt->fetchAll();

$selected_conversation = null;
$messages = [];
$contact = null;

$selected_id = filter_input(INPUT_GET, 'conversation_id', FILTER_VALIDATE_INT);
if ($selected_id) {
    // Strictly verify conversation belongs to logged-in tenant
    $stmt = $db->prepare("SELECT * FROM conversations WHERE id = :id AND tenant_id = :tenant_id LIMIT 1");
    $stmt->execute([
        ':id' => $selected_id,
        ':tenant_id' => $tenant_id
    ]);
    $selected_conversation = $stmt->fetch();

    if ($selected_conversation) {
        // Fetch contact details
        $stmt = $db->prepare("SELECT * FROM contacts WHERE id = :id AND tenant_id = :tenant_id LIMIT 1");
        $stmt->execute([
            ':id' => $selected_conversation['contact_id'],
            ':tenant_id' => $tenant_id
        ]);
        $contact = $stmt->fetch();

        // Fetch messages
        $stmt = $db->prepare("SELECT * FROM messages WHERE conversation_id = :conversation_id AND tenant_id = :tenant_id ORDER BY id ASC");
        $stmt->execute([
            ':conversation_id' => $selected_id,
            ':tenant_id' => $tenant_id
        ]);
        $messages = $stmt->fetchAll();
    }
}

require_once dirname(__DIR__) . '/views/inbox.php';
