<?php

namespace App\Http\Controllers\Api\GoPoints;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class OrdersController extends Controller
{
    public function create(Request $request)
    {
        try {
            $data = json_decode($request->getContent(), true) ?? [];

            $campaign = Str::lower(trim($data['Campaign'] ?? ''));
            if ($campaign !== 'gopoints') {
                return response()->json([
                    'Status'    => 400,
                    'Message'   => 'Campaña no reconocida',
                    'CodeError' => 'INVALID_CAMPAIGN',
                    'Exception' => null,
                ], 400, [], JSON_UNESCAPED_UNICODE);
            }

            // 1. VALIDACIÓN DE CLIENTE
            if (
                empty($data['Customer']['Name'] ?? '') ||
                empty($data['Customer']['Email'] ?? '') ||
                empty($data['Customer']['PhoneNumber'] ?? '') 
            ) {
                return response()->json([
                    'Status'    => 422,
                    'Message'   => 'Datos de cliente incompletos (Nombre, Email y PhoneNumber son requeridos)',
                    'CodeError' => 'INVALID_CUSTOMER',
                    'Exception' => null,
                ], 422, [], JSON_UNESCAPED_UNICODE);
            }

            // 2. VALIDACIÓN DE DIRECCIÓN DETALLADA 
            $address = $data['ShippingAddress'] ?? $data['Shipping'] ?? [];
            if (
                empty($address['StreetName'] ?? '') ||
                empty($address['Number'] ?? '') ||
                empty($address['City'] ?? '')
            ) {
                return response()->json([
                    'Status'    => 422,
                    'Message'   => 'Dirección de envío incompleta (StreetName, Number y City son requeridos)',
                    'CodeError' => 'INVALID_ADDRESS',
                    'Exception' => null,
                ], 422, [], JSON_UNESCAPED_UNICODE);
            }

            // 3. VALIDACIÓN DE PRODUCTOS (Soporta Products o Items)
            $productsRaw = $data['Products'] ?? $data['Items'] ?? [];
            if (empty($productsRaw) || !is_array($productsRaw)) {
                return response()->json([
                    'Status'    => 422,
                    'Message'   => 'Debe incluir al menos un producto',
                    'CodeError' => 'INVALID_ITEMS',
                    'Exception' => null,
                ], 422, [], JSON_UNESCAPED_UNICODE);
            }

            $calc = 0.0;
            $items = [];
            foreach ($productsRaw as $it) {
                $sku = (string)($it['Sku'] ?? '');
                $qty = (int)($it['Quantity'] ?? 0);
                $price = (float)($it['Price'] ?? 0);
                
                if ($sku === '' || $qty <= 0) {
                    continue;
                }
                
                $calc += $qty * $price;
                $items[] = [
                    'Sku' => $sku, 
                    'Quantity' => $qty, 
                    'Price' => $price
                ];
            }

            // 4. TOTALES
            $total = (float)($data['TotalPrice'] ?? $data['Total'] ?? 0);
            $shippingValue = (float)($data['ShippingValue'] ?? 0);

            // Generar ID único de proveedor
            $providerOrderId = (string) Str::uuid();
            $createdAt = now();

            // 5. GUARDAR EN BASE DE DATOS
            $order = Order::create([
                'order_id'         => $providerOrderId,
                'campaign_id'      => 'GoPoints',
                'customer_name'    => $data['Customer']['Name'],
                'customer_email'   => $data['Customer']['Email'],
                'customer_phone'   => $data['Customer']['PhoneNumber'],
                'status'           => 'CREATED',
                'total'            => $total,
                'discount'         => (float)($data['Discount'] ?? 0),
                'shipping'         => $shippingValue,
                'payment_method'   => 'GoPoints',
                'products'         => json_encode($items, JSON_UNESCAPED_UNICODE),
                'shipping_address' => json_encode($address, JSON_UNESCAPED_UNICODE),
                'created_at'       => $createdAt,
            ]);

            Log::info('GoPoints Order Created', ['order_id' => $order->order_id]);

            return response()->json([
                'Status'          => 200,
                'Message'         => 'Orden creada correctamente',
                'CodeError'       => '',
                'Exception'       => null,
                'Parameters'      => [
                    'Campaign' => 'GoPoints',
                    'Customer' => $data['Customer'],
                    'Products' => $items,
                    'Total'    => $total,
                    'Shipping' => [
                        'Value'   => $shippingValue,
                        'Address' => $address,
                    ],
                ],
                'ProviderOrderId' => $providerOrderId,
                'CreatedAt'       => $createdAt->toIso8601String(),
            ], 200, [], JSON_UNESCAPED_UNICODE);

        } catch (\Throwable $e) {
            Log::error('Error creating GoPoints order: '.$e->getMessage());
            return response()->json([
                'Status'    => 500,
                'Message'   => 'Error interno al crear la orden',
                'CodeError' => 'ORDER_CREATION_ERROR',
                'Exception' => $e->getMessage(),
            ], 500, [], JSON_UNESCAPED_UNICODE);
        }
    }

    public function confirm(Request $request)
    {
        try {
            $data = json_decode($request->getContent(), true) ?? [];
            $campaign = Str::lower(trim($data['Campaign'] ?? ''));
            
            if ($campaign !== 'gopoints') {
                return response()->json([
                    'Status' => 400, 'Message' => 'Campaña no reconocida'
                ], 400);
            }

            $providerOrderId = (string)($data['ProviderOrderId'] ?? '');
            $confirmed = (bool)($data['Confirmed'] ?? false);

            $order = Order::where('order_id', $providerOrderId)->first();
            if (!$order) {
                return response()->json([
                    'Status' => 404, 'Message' => 'Pedido no encontrado'
                ], 404);
            }

            $order->status = $confirmed ? 'CONFIRMED' : 'CANCELLED';
            $order->confirmation_date = now();
            $order->save();

            return response()->json([
                'Status'    => 200,
                'Message'   => $confirmed ? 'Orden confirmada' : 'Orden cancelada',
                'ProviderOrderId' => $providerOrderId,
                'StatusOrder'     => $order->status
            ], 200, [], JSON_UNESCAPED_UNICODE);

        } catch (\Throwable $e) {
            return response()->json(['Status' => 500, 'Message' => $e->getMessage()], 500);
        }
    }
}