<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\LandingPage;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\OrderHistory;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\ShippingMethod;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;

class LandingPageApiController extends Controller
{
    /**
     * Show the landing page and its sections by slug.
     */
    public function show(string $slug)
    {
        try {
            $landingPage = LandingPage::with(['product', 'sections'])
                ->where('slug', $slug)
                ->where('is_active', true)
                ->firstOrFail();

            // Transform sections content to resolve image arrays to strings for Next.js compatibility
            $landingPage->sections->each(function ($section) {
                $content = $section->content;
                
                if (is_array($content)) {
                    // Hero block
                    if ($section->block_type === 'hero' && isset($content['image_path'])) {
                        if (is_array($content['image_path'])) {
                            $content['image_path'] = reset($content['image_path']);
                        }
                    }
                    
                    // Features block
                    if ($section->block_type === 'features' && isset($content['features_list'])) {
                        foreach ($content['features_list'] as $i => $item) {
                            if (isset($item['icon_path']) && is_array($item['icon_path'])) {
                                $content['features_list'][$i]['icon_path'] = reset($item['icon_path']);
                            }
                        }
                    }
                    
                    // Testimonials block
                    if ($section->block_type === 'testimonials' && isset($content['testimonials_list'])) {
                        foreach ($content['testimonials_list'] as $i => $item) {
                            if (isset($item['avatar']) && is_array($item['avatar'])) {
                                $content['testimonials_list'][$i]['avatar'] = reset($item['avatar']);
                            }
                        }
                    }
                    
                    $section->content = $content;
                }
            });

            return response()->json([
                'success' => true,
                'data' => $landingPage
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Landing page not found.'
            ], 404);
        }
    }

    /**
     * Place an order directly from the express checkout form.
     */
    public function placeOrder(Request $request)
    {
        Log::info('LandingPageApiController::placeOrder request:', $request->all());

        if (Auth::check() && Auth::user()->role === 'reseller') {
            return response()->json([
                'success' => false,
                'message' => 'রিসেলার অ্যাকাউন্ট দিয়ে ল্যান্ডিং পেজ থেকে অর্ডার করা যাবে না। অনুগ্রহ করে আপনার রিসেলার প্যানেল অথবা মেইন শপ থেকে অর্ডার করুন।'
            ], 403);
        }

        $request->validate([
            'landing_page_id' => 'required|exists:landing_pages,id',
            'product_variant_id' => 'nullable|exists:product_variants,id',
            'customer_name' => 'required|string|max:255',
            'customer_phone' => 'required|string|min:11|max:15',
            'customer_email' => 'nullable|email',
            'shipping_address' => 'required|string|max:1000',
            'shipping_area' => 'required|in:inside_dhaka,outside_dhaka',
            'payment_method' => 'required|in:cod,sslcommerz,bkash,nagad',
            'quantity' => 'required|integer|min:1',
            'notes' => 'nullable|string|max:1000',
        ]);

        // Validate if the selected payment gateway is enabled in database settings
        $paymentMethod = $request->payment_method;
        $isEnabled = match ($paymentMethod) {
            'cod' => Setting::getValue('cod_enabled', true),
            'sslcommerz' => Setting::getValue('sslcommerz_enabled', false),
            'bkash' => Setting::getValue('bkash_enabled', false),
            'nagad' => Setting::getValue('nagad_enabled', false),
            default => false,
        };
        
        $isEnabled = ($isEnabled === true || $isEnabled === 1 || $isEnabled === '1' || $isEnabled === 'true');

        if (!$isEnabled) {
            return response()->json([
                'success' => false,
                'message' => 'The selected payment method (' . strtoupper($paymentMethod) . ') is currently disabled.'
            ], 422);
        }

        // Fetch Landing Page and Linked Product
        $landingPage = LandingPage::findOrFail($request->landing_page_id);
        $product = Product::findOrFail($landingPage->product_id);

        // Compute Item Pricing
        $price = $landingPage->landing_price !== null && floatval($landingPage->landing_price) > 0
            ? floatval($landingPage->landing_price)
            : ($request->product_variant_id 
                ? (ProductVariant::find($request->product_variant_id)?->price ?? $product->price)
                : $product->price
              );

        $quantity = (int)$request->quantity;
        $subtotal = $price * $quantity;

        // Resolve Shipping Method and Cost
        $shippingMethod = ShippingMethod::where('zone', $request->shipping_area)
            ->where('is_active', true)
            ->where('pricing_type', 'flat')
            ->first();

        // Calculate package weight if weight based
        $totalWeight = 0;
        if ($product->is_weight_based && $product->weight_grams) {
            $totalWeight = $product->weight_grams * $quantity;
        }

        $shippingCost = $shippingMethod ? $shippingMethod->calculateCost($totalWeight) : ($request->shipping_area === 'inside_dhaka' ? 80.00 : 150.00);
        $shippingMethodId = $shippingMethod ? $shippingMethod->id : null;

        // Calculate VAT/Tax
        $vatRate = (float)Setting::getValue('vat_percentage', 0.00);
        $tax = ($subtotal * $vatRate) / 100;

        $grandTotal = $subtotal + $shippingCost + $tax;

        // Start Transaction
        DB::beginTransaction();

        try {
            // 1. Stock validation
            if ($request->product_variant_id) {
                $variant = ProductVariant::findOrFail($request->product_variant_id);
                if ($variant->quantity < $quantity) {
                    throw new Exception('Stock error: Selected variant does not have enough stock.');
                }
            } else {
                if ($product->quantity < $quantity) {
                    throw new Exception('Stock error: Product does not have enough stock.');
                }
            }

            // 2. Generate unique order number
            $orderNumber = 'ORD-' . date('ymd') . rand(10000, 99999);
            while (Order::where('order_number', $orderNumber)->exists()) {
                $orderNumber = 'ORD-' . date('ymd') . rand(10000, 99999);
            }

            // 3. Create Order
            $order = Order::create([
                'order_number' => $orderNumber,
                'user_id' => null, // Guest checkout on landing pages by default
                'customer_name' => $request->customer_name,
                'customer_phone' => $request->customer_phone,
                'customer_email' => $request->customer_email ?: null,
                'shipping_address' => $request->shipping_address,
                'billing_address' => $request->shipping_address,
                'notes' => $request->notes ?: null,
                
                'shipping_method_id' => $shippingMethodId,
                'subtotal' => $subtotal,
                'shipping_cost' => $shippingCost,
                'tax' => $tax,
                'discount' => 0.00,
                'grand_total' => $grandTotal,
                
                'payment_method' => $paymentMethod,
                'payment_status' => 'pending',
                'status' => 'pending',
            ]);

            // 4. Deduct stock using backend adjustments
            if ($request->product_variant_id) {
                $variant = ProductVariant::find($request->product_variant_id);
                \App\Services\StockAdjustmentService::adjust($variant, -$quantity, 'order_placed', [
                    'order_id' => $order->id,
                    'notes' => "Deducted variant stock for Landing Page Order #{$order->order_number}",
                ]);
                \App\Services\StockAdjustmentService::adjust($product, -$quantity, 'order_placed', [
                    'order_id' => $order->id,
                    'notes' => "Deducted product stock aggregate for Landing Page Order #{$order->order_number}",
                ]);
            } else {
                \App\Services\StockAdjustmentService::adjust($product, -$quantity, 'order_placed', [
                    'order_id' => $order->id,
                    'notes' => "Deducted product stock for Landing Page Order #{$order->order_number}",
                ]);
            }

            // 5. Create Order Item
            \App\Services\StockAdjustmentService::$skipObserver = true;
            OrderItem::create([
                'order_id' => $order->id,
                'product_id' => $product->id,
                'product_variant_id' => $request->product_variant_id,
                'product_name' => $product->name,
                'product_sku' => $request->product_variant_id ? ProductVariant::find($request->product_variant_id)->sku : $product->sku,
                'price' => $price,
                'quantity' => $quantity,
            ]);
            \App\Services\StockAdjustmentService::$skipObserver = false;

            // 6. Record audit history
            OrderHistory::create([
                'order_id' => $order->id,
                'user_id' => null,
                'action' => 'order_created',
                'from_status' => null,
                'to_status' => 'pending',
                'notes' => 'Customer placed order via Landing Page Express Checkout with ' . strtoupper($paymentMethod) . '.',
            ]);

            DB::commit();

            // 7. Process payment redirection URL
            $redirectUrl = '';
            if ($paymentMethod === 'cod') {
                try {
                    \App\Services\NotificationDispatcher::dispatchOrderPlaced($order);
                } catch (Exception $e) {
                    Log::error('Failed E2E placed notification for landing page order: ' . $e->getMessage());
                }
                $redirectUrl = env('NEXTJS_FRONTEND_URL', 'http://localhost:3000') . '/checkout/success/' . $order->id;
            } else if ($paymentMethod === 'sslcommerz') {
                $redirectUrl = route('payment.ssl.initiate', ['order' => $order->id]);
            } else if ($paymentMethod === 'bkash') {
                $redirectUrl = route('payment.bkash.initiate', ['order' => $order->id]);
            } else if ($paymentMethod === 'nagad') {
                $redirectUrl = route('payment.nagad.initiate', ['order' => $order->id]);
            }

            return response()->json([
                'success' => true,
                'message' => 'Order created successfully from landing page.',
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'redirect_url' => $redirectUrl,
            ]);

        } catch (Exception $e) {
            DB::rollBack();
            Log::error('Landing Page Order placement failed: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 422);
        }
    }
}
