<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Wishlist;
use App\Models\Cart;
use Helper;
use App\Models\SubscriptionPackage;

class CartController extends Controller
{
    protected $product = null;

    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    /* ================= SUBSCRIPTION ================= */

    public function addSubscriptionToCart(Request $request)
    {
        if (Helper::cartHasProduct()) {
            return redirect()->route('cart')
                ->with('error', 'Please checkout or remove products before adding a subscription.');
        }

        

        $subscription = SubscriptionPackage::findOrFail($request->subscription_id);

        $already = Cart::where('user_id', Auth::id())
            ->where('subscription_id', $subscription->id)
            ->where('item_type', 'subscription')
            ->first();

        if ($already) {
            return redirect()->route('cart')
                ->with('error', 'Subscription already added to cart');
        }

        Cart::create([
            'user_id'         => Auth::id(),
            'subscription_id' => $subscription->id,
            'item_type'       => 'subscription',
            'price'           => $subscription->price,
            'quantity'        => 1,
            'amount'          => $subscription->price,
            'status'          => 'new'
        ]);

        return redirect()->route('cart')
            ->with('success', 'Subscription added to cart');
    }

    /* ================= PRODUCT ================= */

    public function addToCart(Request $request)
    {
        if (Helper::cartHasSubscription()) {
            return back()->with(
                'error',
                'You already have a subscription in your cart. Please checkout or remove it first.'
            );
        }

        if (empty($request->slug)) {
            return back()->with('error', 'Invalid product');
        }

        $product = Product::where('slug', $request->slug)->first();
        if (!$product) {
            return back()->with('error', 'Invalid product');
        }

        $already_cart = Cart::where('user_id', auth()->id())
            ->whereNull('order_id')
            ->where('product_id', $product->id)
            ->where('item_type', 'product')
            ->first();

        $price = ($product->price - ($product->price * $product->discount) / 100);

        if ($already_cart) {
            $already_cart->quantity++;
            $already_cart->amount += $price;

            if ($product->stock < $already_cart->quantity) {
                return back()->with('error', 'Stock not sufficient!');
            }

            $already_cart->save();
        } else {
            if ($product->stock < 1) {
                return back()->with('error', 'Stock not sufficient!');
            }

            $cart = Cart::create([
                'user_id'    => auth()->id(),
                'product_id' => $product->id,
                'item_type'  => 'product',
                'price'      => $price,
                'quantity'   => 1,
                'amount'     => $price
            ]);

            Wishlist::where('user_id', auth()->id())
                ->whereNull('cart_id')
                ->update(['cart_id' => $cart->id]);
        }

        return back()->with('success', 'Product successfully added to cart');
    }

    public function singleAddToCart(Request $request)
    {
        if (Helper::cartHasSubscription()) {
            return back()->with(
                'error',
                'You already have a subscription in your cart. Please checkout or remove it first.'
            );
        }

        $request->validate([
            'slug'  => 'required',
            'quant' => 'required'
        ]);

        $product = Product::where('slug', $request->slug)->first();
        if (!$product || $product->stock < $request->quant[1]) {
            return back()->with('error', 'Stock not sufficient!');
        }

        $already_cart = Cart::where('user_id', auth()->id())
            ->whereNull('order_id')
            ->where('product_id', $product->id)
            ->where('item_type', 'product')
            ->first();

        $price = ($product->price - ($product->price * $product->discount) / 100);

        if ($already_cart) {
            $already_cart->quantity += $request->quant[1];
            $already_cart->amount += ($price * $request->quant[1]);

            if ($product->stock < $already_cart->quantity) {
                return back()->with('error', 'Stock not sufficient!');
            }

            $already_cart->save();
        } else {
            Cart::create([
                'user_id'    => auth()->id(),
                'product_id' => $product->id,
                'item_type'  => 'product',
                'price'      => $price,
                'quantity'   => $request->quant[1],
                'amount'     => $price * $request->quant[1]
            ]);
        }

        return back()->with('success', 'Product successfully added to cart');
    }

    /* ================= UPDATE / DELETE ================= */

    public function cartDelete(Request $request)
    {
        Cart::where('id', $request->id)->delete();
        return back()->with('success', 'Cart item successfully removed');
    }

    public function cartUpdate(Request $request)
    {
        if (!$request->quant) {
            return back()->with('error', 'Cart invalid');
        }

        foreach ($request->quant as $k => $quant) {
            $cart = Cart::find($request->qty_id[$k]);

            if (!$cart || $cart->item_type === 'subscription') {
                continue;
            }

            if ($cart->product->stock < $quant) {
                return back()->with('error', 'Out of stock');
            }

            $price = ($cart->product->price - ($cart->product->price * $cart->product->discount) / 100);
            $cart->quantity = $quant;
            $cart->amount   = $price * $quant;
            $cart->save();
        }

        return back()->with('success', 'Cart successfully updated');
    }

    /* ================= CHECKOUT ================= */

public function checkout()
{
    if (Helper::cartHasSubscription() && Helper::cartHasProduct()) {
        return redirect()->route('cart')
            ->with('error', 'You cannot checkout products and subscriptions together.');
    }

    $addresses = auth()->check()
        ? auth()->user()->addresses()->latest()->get()
        : collect();

    return view('frontend.pages.checkout', compact('addresses'));
}

public function addSubscription(Request $request)
{
    $request->validate([
        'subscription_id' => 'required|exists:subscription_packages,id',
    ]);

    $subscription = SubscriptionPackage::findOrFail($request->subscription_id);

    //  Remove existing cart items (important)
    Cart::where('user_id', auth()->id())
        ->whereNull('order_id')
        ->delete();

    // Add subscription to cart
    Cart::create([
        'user_id'         => auth()->id(),
        'subscription_id' => $subscription->id,
        'item_type'       => 'subscription',
        'quantity'        => 1,
        'price'           => $subscription->price,
        'amount'          => $subscription->price,
    ]);

    return redirect()->route('checkout')
        ->with('success', 'Subscription added to cart');
}



}
