<?php

namespace App\Http\Controllers\frontend;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\Category;
use App\Models\Product;
use App\Models\Cart;
use App\Models\FlashDeal;
use App\Models\Review;
use App\Models\ProductStock;
use Illuminate\Http\Request;

class FrontendController extends Controller
{
    public function home(){

         $category=Category::take(10)->get();
        $product=Product::get();
        $trandyproducts=Product::with(['stocks:id,product_id,variant,price,qty,image'])->where('trandy',1)->take(4)->get();
        $mycart='0';
        if(Auth::check()){
            $user_id=Auth::id();
            $mycart=Cart::where('user_id',$user_id)->count();
        }
        return view('welcome',compact('category','product','mycart','trandyproducts'));
    }

    public function viewproduct($id) {
        $product=$product = Product::with('stocks')->findOrFail($id);
        return View('frontend.pages.product_view',compact('product'));
    }

    public function getStock($id){
    $stock = ProductStock::where('product_id',$id)->get();

    if (!$stock) {
        return response()->json(['error' => 'Stock not found'], 404);
    }

    return response()->json($stock);
}

    public function category(){
        $categories=Category::get();
        return View('frontend.pages.allCategory',compact('categories'));
    }

    public function categoryofproducts($id){
        $products=Product::where('category_id',$id)->get();
        $category=Category::where('id',$id)->first();
        return View('frontend.pages.allProducts',compact('products','category'));
    }

    public function product(Request $request){
       
         $name=$request->Search_product;
         $products=Product::where('name','like', '%'.$name.'%')->orwhere('description','like', '%'.$name.'%')->orwhere('long_desc','like', '%'.$name.'%')->get();
         if($name==""){
            $name="Products";
         }
         return View('frontend.pages.search_products',compact('products','name'));
    }

    public function hotsalling(){
        $products=Category::get();
        return View('frontend.pages.hotSalling',compact('products'));
    }

    public function newarivel(){
        $products=Product::orderBy('id', 'DESC')->limit(20)->get();
        return View('frontend.pages.newArivel',compact('products'));
    }

    public function returnPloicy(){
        return View('frontend.pages.returnPolicy');
    }
}
