<?php
// CORS Headers - CRITICAL para permitir peticiones desde Vite (localhost:5173)
header('Access-Control-Allow-Origin: http://localhost:5173');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once '../../config/db.php';
require_once '../../core/Auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    // 1. Verificar Autenticación
    error_log("[send.php] === INICIO DE ENVÍO DE MENSAJE ===");
    $user_id = Auth::check();
    error_log("[send.php] Usuario autenticado: $user_id");

    // 2. Obtener datos
    $raw_input = file_get_contents("php://input");
    error_log("[send.php] Raw input: $raw_input");
    
    $data = json_decode($raw_input);
    error_log("[send.php] Decoded data: " . json_encode($data));

    if (!isset($data->chat_id) || !isset($data->content)) {
        error_log("[send.php] ERROR: Missing chat_id or content");
        http_response_code(400);
        echo json_encode(['error' => 'Missing chat_id or content']);
        exit;
    }

    $chat_id = (int)$data->chat_id;
    $content = trim($data->content);
    $type = isset($data->type) ? $data->type : 'text';
    $meta_data = isset($data->meta_data) ? $data->meta_data : null;
    $is_ephemeral = isset($data->is_ephemeral) ? (bool)$data->is_ephemeral : false;
    
    error_log("[send.php] Parámetros procesados: chat_id=$chat_id, type=$type, content_length=" . strlen($content) . ", is_ephemeral=$is_ephemeral");

    // Start Transaction
    error_log("[send.php] Iniciando transacción...");
    $pdo->beginTransaction();

    try {
        // 3. Handle Transactions (Gifts/Payments)
        if (($type === 'gift' || $type === 'payment') && $meta_data) {
            error_log("[send.php] Procesando transacción de tipo: $type");
            $amount = isset($meta_data->amount) ? (int)$meta_data->amount : 0;
            
            if ($amount > 0) {
                // Check Balance (common for both gift and payment)
                // Usamos i_users e iuid
                $stmt = $pdo->prepare("SELECT diamonds FROM i_users WHERE iuid = ? FOR UPDATE");
                $stmt->execute([$user_id]);
                $current_balance = $stmt->fetchColumn();
                
                error_log("[send.php] Balance actual del usuario: $current_balance, monto requerido: $amount");

                if ($current_balance < $amount) {
                    error_log("[send.php] ERROR: Saldo insuficiente");
                    throw new Exception("Insufficient diamonds");
                }

                if ($type === 'payment') {
                    error_log("[send.php] Procesando pago...");
                    // Get Receiver ID (assuming 1-on-1 for payment logic)
                    // La tabla real es chat_members
                    $stmt_rec = $pdo->prepare("SELECT user_id FROM chat_members WHERE chat_id = ? AND user_id != ? LIMIT 1");
                    $stmt_rec->execute([$chat_id, $user_id]);
                    $receiver_id = $stmt_rec->fetchColumn();

                    if (!$receiver_id) {
                        error_log("[send.php] ERROR: Receptor no encontrado en el chat");
                        throw new Exception("Receiver not found in chat");
                    }

                    // Get Fee Setting
                    $stmt_fee = $pdo->prepare("SELECT setting_value FROM site_config WHERE setting_key = 'chat_unlock_fee_percent'");
                    $stmt_fee->execute();
                    $fee_percent = (float)($stmt_fee->fetchColumn() ?: 20); // Default 20%

                    $feeAmount = $amount * ($fee_percent / 100);
                    $receiver_net = $amount - $feeAmount;

                    // Deduct Balance (Sender)
                    $stmt = $pdo->prepare("UPDATE i_users SET diamonds = diamonds - ? WHERE iuid = ?");
                    $stmt->execute([$amount, $user_id]);

                    // Credit Balance (Receiver)
                    $stmt_credit = $pdo->prepare("UPDATE i_users SET diamonds = diamonds + ? WHERE iuid = ?");
                    $stmt_credit->execute([$receiver_net, $receiver_id]);

                    // Record Transactions
                    $stmt_log = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, ?, ?, ?)");
                    
                    // Sender Log
                    $stmt_log->execute([$user_id, 'purchase', $amount, "Unlocked content in chat"]);
                    
                    // Receiver Log
                    $stmt_log->execute([$receiver_id, 'content_sold', $receiver_net, "Content sold in chat (Fee: $feeAmount)"]);

                    $current_balance -= $amount; // Update current_balance for response
                    error_log("[send.php] Pago procesado exitosamente");
                } else if ($type === 'gift') {
                    error_log("[send.php] Procesando regalo...");
                    // Deduct Balance
                    $stmt = $pdo->prepare("UPDATE i_users SET diamonds = diamonds - ? WHERE iuid = ?");
                    $stmt->execute([$amount, $user_id]);
 
                    // Record Transaction (Sender)
                    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, ?, ?, ?)");
                    $desc = "Gift sent: " . ($meta_data->giftName ?? 'Unknown');
                    $type_db = 'gift_sent';
                    
                    $stmt->execute([$user_id, $type_db, $amount, $desc]);
                    
                    $current_balance -= $amount; // Update current_balance for response
                    error_log("[send.php] Regalo procesado exitosamente");
                }
            }
        }

        // 4. Guardar Mensaje
        error_log("[send.php] Guardando mensaje en BD...");
        $meta_json = $meta_data ? json_encode($meta_data) : null;
        
        $sql = "INSERT INTO messages (chat_id, sender_id, type, content, meta_data, is_ephemeral) 
                VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([$chat_id, $user_id, $type, $content, $meta_json, $is_ephemeral]);
        $message_id = $pdo->lastInsertId();
        
        error_log("[send.php] Mensaje guardado con ID: $message_id, resultado: " . ($result ? 'SUCCESS' : 'FAILED'));

        // 5. Commit
        $pdo->commit();
        error_log("[send.php] Transacción confirmada exitosamente");

        echo json_encode([
            'status' => 'success',
            'message_id' => $message_id,
            'timestamp' => date('Y-m-d H:i:s'),
            'new_balance' => isset($current_balance) ? $current_balance - $amount : null
        ]);

        // 6. BOT RESPONSE LOGIC (Async-like)
        $stmt_bot = $pdo->prepare("SELECT bot_id FROM chats WHERE id = ?");
        $stmt_bot->execute([$chat_id]);
        $bot_id = $stmt_bot->fetchColumn();

        if ($bot_id) {
            error_log("[send.php] El chat es con un BOT (ID: $bot_id). Generando respuesta...");
            
            // Get Bot Settings
            $stmt_sett = $pdo->prepare("SELECT * FROM ai_bots WHERE id = ?");
            $stmt_sett->execute([$bot_id]);
            $bot = $stmt_sett->fetch();

            if ($bot) {
                // SIMULACIÓN DE IA (Juuvix Engine)
                // Aquí iría la llamada a OpenAI/Gemini usando $bot['ai_model'] y $bot['system_prompt']
                $bot_response = "Soy " . $bot['name'] . ". Recibí tu mensaje: \"" . $content . "\". Actualmente estoy en modo entrenamiento, pero pronto podré responderte usando " . $bot['ai_model'] . " con mi personalidad de " . $bot['category'] . ".";
                
                // Insert Bot Message
                $stmt_reply = $pdo->prepare("INSERT INTO messages (chat_id, sender_id, type, content) VALUES (?, ?, 'text', ?)");
                // El sender_id 0 o un ID especial para el bot
                $stmt_reply->execute([$chat_id, 0, $bot_response]);
                error_log("[send.php] Respuesta del bot enviada.");
            }
        }

    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("[send.php] EXCEPCIÓN CAPTURADA: " . $e->getMessage());
        error_log("[send.php] Stack trace: " . $e->getTraceAsString());
        http_response_code(400);
        echo json_encode([
            'error' => $e->getMessage(),
            'debug' => [
                'file' => basename($e->getFile()),
                'line' => $e->getLine()
            ]
        ]);
    }

} catch (PDOException $e) {
    error_log("[send.php] ERROR DE BASE DE DATOS: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'DB Error: ' . $e->getMessage()]);
}
?>
