<?php
/**
 * API Endpoint: Cancel Trading Order
 * Cancela una orden pendiente del cliente
 */

session_start();

// Verificar autenticación del cliente
if (!isset($_SESSION['client_id']) || $_SESSION['client_status'] !== 'active') {
    http_response_code(401);
    echo json_encode(['error' => 'No autorizado']);
    exit;
}

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

// Configuración de la base de datos
require_once '../../../config/database.php';

header('Content-Type: application/json');

try {
    // Obtener datos de la solicitud
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || empty($input['orderId'])) {
        throw new Exception('ID de orden requerido');
    }
    
    $orderId = intval($input['orderId']);
    $client_id = $_SESSION['client_id'];
    $accountNumber = !empty($input['account_number']) ? trim($input['account_number']) : null;
    
    // Obtener cuenta de trading del cliente (filtrar por account_number si se proporcionó)
    if ($accountNumber) {
        $stmt = $pdo->prepare("SELECT id FROM trading_accounts WHERE client_id = ? AND account_number = ? AND status = 'active' LIMIT 1");
        $stmt->execute([$client_id, $accountNumber]);
    } else {
        $stmt = $pdo->prepare("SELECT id FROM trading_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$client_id]);
    }
    $account = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$account) {
        throw new Exception('No se encontró cuenta de trading activa');
    }
    
    // Obtener la orden
    $stmt = $pdo->prepare("
        SELECT to.*, ti.name as instrument_name
        FROM trading_orders to
        LEFT JOIN trading_instruments ti ON to.symbol = ti.symbol
        WHERE to.id = ? AND to.account_id = ? AND to.status = 'pending'
    ");
    $stmt->execute([$orderId, $account['id']]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        throw new Exception('Orden no encontrada o ya procesada');
    }
    
    // Iniciar transacción
    $pdo->beginTransaction();
    
    try {
        // Cancelar la orden
        $stmt = $pdo->prepare("
            UPDATE trading_orders 
            SET status = 'cancelled',
                cancelled_at = NOW(),
                updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$orderId]);
        
        // Verificar que se actualizó correctamente
        if ($stmt->rowCount() === 0) {
            throw new Exception('No se pudo cancelar la orden');
        }
        
        // Registrar en el historial de órdenes canceladas (opcional)
        $stmt = $pdo->prepare("
            INSERT INTO trading_order_history (
                account_id, order_id, symbol, type, volume, price,
                status, action, created_at, processed_at
            ) VALUES (?, ?, ?, ?, ?, ?, 'cancelled', 'cancel', ?, NOW())
        ");
        $stmt->execute([
            $account['id'], $orderId, $order['symbol'], $order['type'], 
            $order['volume'], $order['price'], $order['created_at']
        ]);
        
        $pdo->commit();
        
        // Formatear respuesta
        $decimals = (strpos($order['symbol'], 'JPY') !== false) ? 3 : 5;
        
        echo json_encode([
            'success' => true,
            'message' => 'Orden cancelada exitosamente',
            'order_id' => $orderId,
            'order_details' => [
                'symbol' => $order['symbol'],
                'type' => ucfirst(str_replace('_', ' ', $order['type'])),
                'volume' => number_format(floatval($order['volume']), 2),
                'price' => number_format(floatval($order['price']), $decimals),
                'created_at' => date('d/m/Y H:i:s', strtotime($order['created_at'])),
                'duration' => calculateOrderDuration($order['created_at'])
            ]
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    error_log("Error en cancel-order.php: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * Calcular duración de la orden
 */
function calculateOrderDuration($createdAt) {
    $created = new DateTime($createdAt);
    $now = new DateTime();
    $interval = $created->diff($now);
    
    if ($interval->days > 0) {
        return $interval->days . ' día' . ($interval->days > 1 ? 's' : '') . 
               ' ' . $interval->h . ' hora' . ($interval->h > 1 ? 's' : '');
    } elseif ($interval->h > 0) {
        return $interval->h . ' hora' . ($interval->h > 1 ? 's' : '') . 
               ' ' . $interval->i . ' minuto' . ($interval->i > 1 ? 's' : '');
    } else {
        return $interval->i . ' minuto' . ($interval->i > 1 ? 's' : '') . 
               ' ' . $interval->s . ' segundo' . ($interval->s > 1 ? 's' : '');
    }
}
?>
