<?php
/**
 * API - Cambiar modo de disponibilidad del asesor
 * POST { "available": true|false }
 * GET  → devuelve estado actual
 */

require_once '../config/config.php';
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');

$db = Database::getInstance();

try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $row = $db->fetch(
            "SELECT config_value FROM system_config WHERE config_key = 'advisor_available' LIMIT 1"
        );
        $available = $row ? (bool)(int)$row['config_value'] : true;
        echo json_encode(['success' => true, 'available' => $available]);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Método no permitido']);
        exit;
    }

    $input = json_decode(file_get_contents('php://input'), true);
    if (!isset($input['available'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Falta el campo "available"']);
        exit;
    }

    $value = $input['available'] ? '1' : '0';

    // Upsert en system_config
    $existing = $db->fetch(
        "SELECT id FROM system_config WHERE config_key = 'advisor_available' LIMIT 1"
    );

    if ($existing) {
        $db->update(
            'system_config',
            ['config_value' => $value, 'updated_at' => date('Y-m-d H:i:s')],
            'config_key = :k',
            ['k' => 'advisor_available']
        );
    } else {
        $db->insert('system_config', [
            'config_key'   => 'advisor_available',
            'config_value' => $value,
            'description'  => 'Indica si hay asesores disponibles (1=sí, 0=no).',
            'created_at'   => date('Y-m-d H:i:s'),
        ]);
    }

    $label = $value === '1' ? 'disponible' : 'ausente';
    error_log("[AdvisorMode] Modo asesor cambiado a '{$label}' por usuario=" . ($_SESSION['user_id'] ?? 'unknown'));

    echo json_encode(['success' => true, 'available' => (bool)(int)$value, 'label' => $label]);

} catch (Exception $e) {
    error_log('[set_advisor_mode] Error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno del servidor']);
}
