<?php
require_once '../config/config.php';
header('Content-Type: application/json; charset=utf-8');
requireAuthentication();

try {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $userId = isset($input['user_id']) ? intval($input['user_id']) : 0;
    if (!$userId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'user_id required']);
        exit;
    }

    $db = Database::getInstance();
    $user = $db->fetch('SELECT phone_number FROM users WHERE id = :id', ['id' => $userId]);
    if (!$user) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'User not found']);
        exit;
    }

    $operator = $_SESSION['admin_user'] ?? null;
    $operatorId = $operator['id'] ?? null;
        // Guard: do not set attend if already in_service
        $cur = $db->fetch('SELECT in_service FROM users WHERE id = ?', [$userId]);
        if (!empty($cur['in_service'])) {
            echo json_encode(['success' => false, 'error' => 'La conversación ya está en servicio']);
            exit;
        }
    try {
        require_once __DIR__ . '/../services/BotService.php';
        $bot = new BotService();
        $bot->attendConversation($user['phone_number'], $operatorId);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        // Fallback: apply updates directly and log activity
        $now = date('Y-m-d H:i:s');
        $db->update('users', ['in_service' => 1, 'in_service_by' => $operatorId, 'in_service_at' => $now, 'advisor_requested' => 0], 'id = :id', ['id' => $userId]);
        $db->insert('operator_activity', ['user_id' => $userId, 'operator_id' => $operatorId, 'action' => 'attend', 'details' => 'Marked in_service via fallback', 'created_at' => $now]);
        echo json_encode(['success' => true, 'warning' => 'BotService failed, fallback applied']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
