<?php

use App\Models\{Order, OrderItem, CartItem};
use App\Models\Address;
use App\Models\Coupon;
use App\Models\PaymentGateway;
use App\Services\ShippingCalculator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Attributes\Layout;
use Livewire\Component;

return new class extends Component
{
    #[Layout('layouts.store')]
    public $fullname, $address, $address_id, $city, $pincode, $house_no, $area, $phone, $landmark, $type, $is_default, $coupon_id_text;
    public $coupon_id = '';
    public $discount = 0;
    public $hasAddress = false;
    public $user;
    public $payment_method;


    public function mount()
    {

        $this->hasAddress = Auth::user()->address()->get();
        $this->address_id = (string) $this->hasAddress->where('is_default', 1)->first()?->id;
        $this->user = Auth::user();

        if (session()->get('cart') == null || count(session()->get('cart')) === 0) {
            return redirect()->route('shop')->with('notify', 'Your bag must contain items to checkout.');
        }
        if (!Auth::check()) {
            return redirect()->route('login')->with(
                'toast',
                [
                    'type' => 'danger',
                    'text' => 'Please login first to checkout'
                ]
            );
        }
    }

    public function placeOrder()
    {
        if ($this->hasAddress->isEmpty()) {
            $this->validate([
                'fullname' => 'required|string|max:255',
                'phone'    => 'required|digits:10',
                'house_no' => 'required',
                'area'     => 'required',
                'city'     => 'required',
                'pincode'  => 'required|digits:6',
                'type'     => 'required',
            ]);

            // Create the new address and capture the ID
            $newAddress = Address::create([
                'user_id'    => Auth::id(),
                'fullname'   => $this->fullname,
                'phone'      => $this->phone,
                'house_no'   => $this->house_no,
                'area'       => $this->area,
                'landmark'   => $this->landmark,
                'city'       => $this->city,
                'state'      => $this->city, // Or add a state field
                'pincode'    => $this->pincode,
                'type'       => $this->type,
                'is_default' => $this->is_default ?? 0,
            ]);

            $this->address_id = $newAddress->id;
        } else {
            $this->validate([
                'address_id' => 'required|exists:addresses,id',
            ]);

            $ownsAddress = Address::where('id', $this->address_id)
                ->where('user_id', Auth::id())
                ->exists();

            if (!$ownsAddress) {
                $this->addError('address_id', 'Please select a valid shipping address.');
                return;
            }
        }

        $order = Order::create([
            'user_id'          => Auth::id(),
            'address_id'       => $this->address_id,
            'order_number'     => 'ORD-' . now()->format('Ymd') . '-' . Str::upper(Str::random(8)),
            'subtotal'         => $this->getSubtotal(),
            'discount_amount'  => $this->discount,
            'coupon_id'        => $this->coupon_id ?: null,
            'shipping_charges' => $this->getShippingFeeProperty(),
            'total'            => $this->getTotal(), // Used your getTotal method here
            'status'           => 'pending',
        ]);

        $cartItems = CartItem::where('user_id', Auth::id())->with('product')->get();
        foreach ($cartItems as $item) {
            OrderItem::create([
                'order_id'   => $order->id,
                'product_id' => $item->product_id,
                'price'      => $item->product->price,
                'quantity'   => $item->quantity
            ]);
        }

        CartItem::where('user_id', Auth::id())->delete();
        session()->forget('cart');

        return redirect()->route('thanks', ['orderid' => $order->order_number]);
    }

    public function getSubtotal()
    {
        $cart = session()->get('cart', []);
        return array_reduce($cart, fn($carry, $item) => $carry + ($item['price'] * $item['quantity']), 0);
    }

    public function getShippingFeeProperty()
    {
        return ShippingCalculator::getFee($this->getSubtotal());
    }

    public function getTotal()
    {
        return $this->getSubTotal() + $this->getShippingFeeProperty() - $this->discount;
    }

    public function applyCoupon()
    {
        $this->resetErrorBag();

        $couponData = Coupon::where('code', $this->coupon_id_text)
            ->where('is_active', 1)
            ->first();

        if (!$couponData) {
            $this->dispatch('toast', text: 'Invalid or inactive coupon code.', type: 'error');
            return;
        }

        if ($couponData->expiry_date && Carbon::parse($couponData->expiry_date)->isPast()) {
            $this->dispatch('toast', text: 'This coupon has expired.', type: 'error');
            return;
        }

        if ($this->getSubtotal() < $couponData->min_order_amount) {
            $this->dispatch('toast', text: 'Minimum spend of ₹' . $couponData->min_order_amount . ' required.', type: 'error');
            return;
        }

        if ($couponData->usage_limit && $couponData->used_count >= $couponData->usage_limit) {
            $this->dispatch('toast', text: 'This coupon has reached its usage limit.', type: 'error');
            return;
        }

        if ($couponData->type === 'percent') {
            $this->coupon_id = $couponData->id;
            $this->discount = ($this->getSubtotal() * ($couponData->value / 100));
            $this->dispatch('toast', text: 'Coupon Code Applied Successfully', type: 'success');
        } else {
            $this->coupon_id = $couponData->id;
            $this->discount = $couponData->value;
            $this->dispatch('toast', text: 'Coupon Code Applied Successfully', type: 'success');
        }
    }

    // Inside your Checkout Component class
    public function getEnabledGatewaysProperty() {
        return PaymentGateway::where('is_active', true)
            ->orderBy('sort_order')
            ->get();
    }

    protected function view($data = [])
    {
        return app('view')->file('C:\laragon\www\ecommerce\storage\framework/views/livewire/views/d78c4265.blade.php', $data);
    }
};
