<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\CartItem;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class FrontendController extends Controller
{


    public function products(Request $request)
    {

        $query = Product::query();

        // SEARCH
        if($request->search){

            $query->where(function($q) use ($request){

                $q->where(
                    'description',
                    'LIKE',
                    '%'.$request->search.'%'
                )

                ->orWhere(
                    'collection',
                    'LIKE',
                    '%'.$request->search.'%'
                )

                ->orWhere(
                    'product_type',
                    'LIKE',
                    '%'.$request->search.'%'
                )

                ->orWhere(
                    'new_triple_sku',
                    'LIKE',
                    '%'.$request->search.'%'
                );

            });

        }

        // CATEGORY

        if($request->category){

            $query->where(
                'product_type',
                $request->category
            );

        }

        // SORTING

        if($request->sort == 'low_to_high'){

            $query->orderBy('final_price','ASC');

        }

        elseif($request->sort == 'high_to_low'){

            $query->orderBy('final_price','DESC');

        }

        else{

            $query->latest();

        }

        // $products = $query->paginate(8);
         // SHOW ENTRIES
        $limit = $request->limit ?? 10;

        $products = $query->paginate($limit);

        // AJAX RESPONSE

        if($request->ajax()){

            return view(
                'frontend.product-list',
                compact('products')
            )->render();

        }

        return view('frontend.products');
    }


    public function productDetail($id)
    {
        $product = Product::findOrFail($id);

        return view(
            'frontend.product.product-detail',
            compact('product')
        );
    }


    public function productVariation(Request $request)
    {
        
        $product = Product::find($request->product_id);

        $variation = Product::where(
                'new_triple_sku',
                $product->new_triple_sku
            )
            ->where(
                'metal_color',
                $request->metal_color
            )
            ->first();
        
        return response()->json([
            'id'    => $variation->id,
            'sku'   => $variation->new_triple_sku,
            'product_type'   => $variation->product_type,
            'price' => number_format($variation->final_price, 2),
            'image' => asset($variation->image),
        ]);
    }
    public function addToCart(Request $request)
    {

    if(!Auth::check()){

        return response()->json([
            'status' => false,
            'message' => 'Login Required'
        ]);
    }

        // PRODUCT

        $product = Product::find($request->product_id);

        if(!$product){

            return response()->json([
                'status' => false,
                'message' => 'Product Not Found'
            ]);
        }

        // CART CHECK

        $cart = CartItem::where(
            'user_id',
            Auth::id()
        )

        ->where(
            'product_id',
            $request->product_id
        )

        ->first();

        // IF EXISTS
         $price = $product->final_price ?? 0;

            $markupValue = Auth::user()->markup_value ?? 0;

            $markupType = Auth::user()->markup_type ?? '';

            // FINAL PRICE
            if($markupType == 'percent'){

                $finalPrice = $price + (($price * $markupValue) / 100);

            }
            elseif($markupType == 'fixed'){

                $finalPrice = $price + $markupValue;

            }
            else{

                $finalPrice = $price;

            }

        if($cart){

            $cart->increment('qty');

            
                $cart->total_price = $cart->qty * $finalPrice;

            $cart->save();

        }else{

            CartItem::create([

                'user_id'     => Auth::id(),

                'product_id'  => $request->product_id,

                'qty'         => 1,

                'total_price' => $finalPrice

            ]);
        }

         $cartCount = CartItem::where(
                        'user_id',
                        Auth::id()
                    )->sum('qty');



            return response()->json([

                'status' => true,
                'cartCount' => $cartCount

            ]);
    }


        public function updateQty(Request $request)
        {

            $cart = CartItem::find($request->cart_id);

            if(!$cart){

                return response()->json([
                    'status' => false
                ]);
            }

            // SINGLE ITEM PRICE

            $singlePrice =
                $cart->total_price / $cart->qty;

            // UPDATE QTY

            $cart->qty = $request->qty;

            // NEW TOTAL

            $cart->total_price =
                $singlePrice * $request->qty;

            $cart->save();

            return response()->json([
                'status' => true
            ]);

        }

        public function cart()
        {

            $carts = CartItem::with('product')
                ->where('user_id',Auth::id())
                ->latest()
                ->get();
            return view(
                'frontend.cart.cart',
                compact('carts')
            );
        }

        public function placeOrder(Request $request)
        {
            $request->validate([

                'name'  => 'required',

                'email' => 'required|email',

            ]);

            DB::beginTransaction();

            try {

                // CART IDS
                $productIds = explode(',', $request->product_id);

                // CART ITEMS
                $cartItems = CartItem::with('product')
                            ->whereIn('id', $productIds)
                            ->get();

                // GRAND TOTAL
                $grandTotal = 0;

                foreach ($cartItems as $item) {
                    $grandTotal += $item->total_price;
                }

                $grandTotal = round($grandTotal);

                // =========================
                // ORDER INSERT
                // =========================

                $order = Order::create([

                    'user_id'     => auth()->id(),

                    'name'        => $request->name,

                    'email'       => $request->email,

                    'message'     => $request->message,

                    'total_amount' => $grandTotal,

                    'total_items' => $cartItems->count(),

                    'status'      => 'Pending',

                ]);

                // =========================
                // ORDER ITEMS INSERT
                // =========================

                foreach($cartItems as $item){

                    OrderItem::create([

                        'order_id'   => $order->id,

                        'product_id' => $item->product_id,

                        'sku'        => $item->product->new_triple_sku ?? null,

                        'qty'        => $item->qty,

                        'price' => round($item->total_price),

                        // 'total'      => $item->qty * $item->total_price,

                    ]);

                }

                // =========================
                // SEND EMAIL
                // =========================

                Mail::send(

                    'frontend.emails.order_mail',

                    [

                        'name'       => $request->name,

                        'email'      => $request->email,

                        'userMessage'=> $request->message,

                        'cartItems'  => $cartItems,

                        'grandTotal' => $grandTotal,

                        'order'      => $order,

                    ],

                    function($mail) use ($request){

                        $mail->to($request->email)
                            ->subject('Jewelry Order Received');

                    }

                );

                // =========================
                        // ADMIN EMAIL
                        // =========================

                        Mail::send(

                            'frontend.emails.order_mail',

                            [

                                'name'       => $request->name,
                                'email'      => $request->email,
                                'userMessage'=> $request->message,
                                'cartItems'  => $cartItems,
                                'grandTotal' => $grandTotal,
                                'order'      => $order,

                            ],

                            function($mail){

                                $mail->to('shubhpatidar0777@gmail.com')
                                    ->subject('New Order Received');

                            }

                        );



                // =========================
                // REMOVE CART ITEMS
                // =========================

                CartItem::whereIn('id', $productIds)->delete();

                DB::commit();

                return response()->json([

                    'status'  => true,
                    'message' => 'Order placed successfully'

                ]);

            } catch (\Exception $e) {

                DB::rollBack();

                return response()->json([

                    'status'  => false,
                    'message' => $e->getMessage()

                ]);

            }
        }

        public function removeCart($id)
        {
            $cart = CartItem::find($id);

            if($cart){

                $cart->delete();

            }

            // UPDATED CART COUNT
            $cartCount = CartItem::where(
                            'user_id',
                            Auth::id()
                        )->sum('qty');

            // GRAND TOTAL
            // $grandTotal = CartItem::where(
            //                     'user_id',
            //                     Auth::id()
            //                 )->sum('total');

            return response()->json([

                'success'    => true,

                'cartCount'  => $cartCount

                // 'grandTotal' => $grandTotal

            ]);
        }
       
}