<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\CryptoWallet;
use Illuminate\Http\Request;

class CheckoutController extends Controller
{
    // ── Show Checkout Page ───────────────────────────────────────────────────
    public function index()
    {
        $cart      = $this->getCart();
        $cartItems = $cart ? $cart->items()->with('product.images')->get() : collect();

        $subtotal = $cartItems->sum(function ($item) {
            $price = ($item->product->is_on_sale && $item->product->discount_price)
                ? $item->product->discount_price
                : $item->product->price;
            return $price * $item->quantity;
        });

        return view('checkout', compact('cartItems', 'subtotal'));
    }

    // ── Place Order ──────────────────────────────────────────────────────────
    public function place(Request $request)
    {
        $request->validate([
            'first_name'     => 'required|string|max:100',
            'last_name'      => 'required|string|max:100',
            'email'          => 'required|email',
            'phone'          => 'required|string|max:30',
            'address'        => 'required|string|max:255',
            'city'           => 'required|string|max:100',
            'country'        => 'required|string|max:100',
            'shipping_cost'  => 'required|numeric|min:0',
            'shipping_type'  => 'required|string',
            'payment_method' => 'required|in:crypto,gift_card',
        ]);

        $cart      = $this->getCart();
        $cartItems = $cart->items()->with('product')->get();

        if ($cartItems->isEmpty()) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty.');
        }

        $subtotal = $cartItems->sum(function ($item) {
            $price = ($item->product->is_on_sale && $item->product->discount_price)
                ? $item->product->discount_price
                : $item->product->price;
            return $price * $item->quantity;
        });

        // Create order
        $order = Order::create([
            'user_id'        => auth()->id(),
            'first_name'     => $request->first_name,
            'last_name'      => $request->last_name,
            'email'          => $request->email,
            'phone'          => $request->phone,
            'address'        => $request->address,
            'address2'       => $request->address2,
            'city'           => $request->city,
            'state'          => $request->state,
            'zip'            => $request->zip,
            'country'        => $request->country,
            'notes'          => $request->notes,
            'shipping_type'  => $request->shipping_type,
            'shipping_cost'  => $request->shipping_cost,
            'subtotal'       => $subtotal,
            'total'          => $subtotal + $request->shipping_cost,
            'payment_method' => $request->payment_method,
            'status'         => 'pending',
        ]);

        // Save order items
        foreach ($cartItems as $item) {
            $price = ($item->product->is_on_sale && $item->product->discount_price)
                ? $item->product->discount_price
                : $item->product->price;

            OrderItem::create([
                'order_id'     => $order->id,
                'product_id'   => $item->product_id,
                'product_name' => $item->product->name,
                'quantity'     => $item->quantity,
                'price'        => $price,
                'subtotal'     => $price * $item->quantity,
            ]);
        }

        // Clear cart
        $cart->items()->delete();
        session()->forget(['shipping_type', 'shipping_cost']);

        return redirect()->route('payment.page', $order->id)
                         ->with('success', 'Order placed! Please complete your payment below.');
    }

    // ── Payment Page ─────────────────────────────────────────────────────────
    public function paymentPage(Order $order)
    {
        if ($order->user_id !== auth()->id()) {
            abort(403);
        }

        // Prevent revisiting after payment already submitted
        if ($order->status === 'payment_submitted') {
            return redirect()->route('home')
                ->with('success', 'Your payment has already been submitted and is being reviewed.');
        }

        $cryptoWallets = $order->payment_method === 'crypto'
            ? CryptoWallet::where('is_active', true)->get()
            : collect();

        $order->load('items');

        return view('user-payment-confirm', compact('order', 'cryptoWallets'));
    }

    // ── Confirm Payment ──────────────────────────────────────────────────────
    public function confirmPayment(Request $request, Order $order)
    {
        if ($order->user_id !== auth()->id()) {
            abort(403);
        }

        // Prevent duplicate submissions
        if ($order->status === 'payment_submitted') {
            return redirect()->route('home')
                ->with('error', 'This order payment has already been submitted.');
        }

        if ($order->payment_method === 'crypto') {

            $request->validate([
                'wallet_id'          => 'required|exists:crypto_wallets,id',
                'payment_screenshot' => 'required|image|mimes:jpeg,jpg,png,gif,webp|max:5120',
                'transaction_id'     => 'nullable|string|max:255',
            ]);

            $screenshotPath = $request->file('payment_screenshot')
                                      ->store('payment_proofs', 'public');

            $order->update([
                'wallet_id'          => $request->wallet_id,
                'transaction_id'     => $request->transaction_id,
                'payment_screenshot' => $screenshotPath,
                'status'             => 'payment_submitted',
            ]);

        } elseif ($order->payment_method === 'gift_card') {

            $request->validate([
                'gift_card_brand' => 'required|string|max:100',
                'gift_card_code'  => 'required|string|max:255',
                'gift_card_pin'   => 'nullable|string|max:50',
                'gift_card_value' => 'required|numeric|min:1',
                'gift_card_photo' => 'required|image|mimes:jpeg,jpg,png,gif,webp|max:5120',
                'gift_card_notes' => 'nullable|string|max:500',
            ]);

            $photoPath = $request->file('gift_card_photo')
                                  ->store('gift_card_proofs', 'public');

            $order->update([
                'gift_card_brand'  => $request->gift_card_brand,
                'gift_card_code'   => $request->gift_card_code,
                'gift_card_pin'    => $request->gift_card_pin,
                'gift_card_value'  => $request->gift_card_value,
                'gift_card_photo'  => $photoPath,
                'gift_card_notes'  => $request->gift_card_notes,
                'status'           => 'payment_submitted',
            ]);

        } else {
            return redirect()->back()->with('error', 'Invalid payment method.');
        }

        return redirect()->route('orders.index')
                         ->with('success', 'Payment submitted successfully! Our team will verify and process your order within 1–24 hours.');
    }

    // ── Helper ───────────────────────────────────────────────────────────────
    private function getCart()
    {
        if (auth()->check()) {
            return Cart::where('user_id', auth()->id())->first();
        }
        return Cart::where('session_id', session()->getId())->first();
    }
}
