<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Models\Category;
use Toastr;
use Image;
use File;
use Str;
class CategoryController extends Controller
{
    function __construct()
    {
         $this->middleware('permission:category-list|category-create|category-edit|category-delete', ['only' => ['index','store']]);
         $this->middleware('permission:category-create', ['only' => ['create','store']]);
         $this->middleware('permission:category-edit', ['only' => ['edit','update']]);
         $this->middleware('permission:category-delete', ['only' => ['destroy']]);
    }

    public function index(Request $request)
    {
        $data = Category::orderBy('id','DESC')->with('category')->get();
        // return $data;
        return view('backEnd.category.index',compact('data'));
    }
    public function create()
    {
        $categories = Category::orderBy('id','DESC')->select('id','name')->get();
        return view('backEnd.category.create',compact('categories'));
    }
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'status' => 'required',
        ]);
        // image with intervention 
        $image = $request->file('image');
        if($image){
        $name =  time().'-'.$image->getClientOriginalName();
        $name = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name);
        $name = strtolower(preg_replace('/\s+/', '-', $name));
        $uploadpath = 'public/uploads/category/';
        $imageUrl = $uploadpath.$name; 
        $img=Image::make($image->getRealPath());
        $img->encode('webp', 90);
        $width = "";
        $height = "";
        $img->height() > $img->width() ? $width=null : $height=null;
        $img->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio();
        });
        $img->save($imageUrl);
        }else{
            $imageUrl = null;
        }
        
        if ($request->hasFile('banner_img'))
        {
            $banner_img = $request->file('banner_img');
            $banner_name =  time().'-'.$banner_img->getClientOriginalName();
            $banner_name = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$banner_name);
            $banner_name = strtolower(preg_replace('/\s+/', '-', $banner_name));
            $uploadpath = 'public/uploads/category/';
            $banner_imgUrl = $uploadpath.$banner_name; 
            $img=Image::make($banner_img->getRealPath());
            $img->encode('webp', 90);
            $width = "";
            $height = "";
            $img->height() > $img->width() ? $width=null : $height=null;
            $img->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio();
            });
            $img->save($banner_imgUrl);
        }

        $input = $request->all();
        $input['slug'] = strtolower(preg_replace('/\s+/', '-', $request->name));
        $input['slug'] = str_replace('/', '', $input['slug']);

        $input['parent_id'] = $request->parent_id?$request->parent_id:0;
        $input['front_view'] = $request->front_view ? 1 : 0;
        $input['image'] = $imageUrl;
        Category::create($input);
        Toastr::success('Success','Data insert successfully');
        return redirect()->route('categories.index');
    }
    
    public function edit($id)
    {
        $edit_data = Category::find($id);
        $categories = Category::select('id','name')->get();
        return view('backEnd.category.edit',compact('edit_data','categories'));
    }
    
  public function update(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
    ]);

    $update_data = Category::find($request->id);
    $input = $request->all();

    // Handle category image upload
    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $name = time() . '-' . $image->getClientOriginalName();
        $name = strtolower(preg_replace('/\s+/', '-', $name));
        $uploadPath = 'public/uploads/category/';
        $image->move(public_path('uploads/category'), $name);
        $input['image'] = $uploadPath . $name;

        // Delete old image
        if (File::exists(public_path($update_data->image))) {
            File::delete(public_path($update_data->image));
        }
    } else {
        $input['image'] = $update_data->image;
    }

    // Handle banner image upload
    if ($request->hasFile('banner_img')) {
        $banner = $request->file('banner_img');
        $bannerName = time() . '-' . $banner->getClientOriginalName();
        $bannerName = strtolower(preg_replace('/\s+/', '-', $bannerName));
        $uploadPath = 'public/uploads/category/';
        $banner->move(public_path('uploads/category'), $bannerName);
        $input['banner_img'] = $uploadPath . $bannerName;
    }

    // Slug generation
    $input['slug'] = strtolower(preg_replace('/\s+/', '-', $request->name));
    $input['slug'] = str_replace('/', '', $input['slug']);

    // Defaults
    $input['parent_id'] = $request->parent_id ? $request->parent_id : 0;
    $input['front_view'] = $request->front_view ? 1 : 0;
    $input['status'] = $request->status ? 1 : 0;

    // Handle discount
    if (isset($input['discount']) && $input['discount'] > 0) {
        $products = Product::where('category_id', $request->id)->get();
        foreach ($products as $product) {
            $product->old_price = $product->new_price;
            $product->new_price = $product->new_price - ($product->new_price * $input['discount']) / 100;
            $product->save();
        }
    }

    // Update category
    $update_data->update($input);

    Toastr::success('Success', 'Data update successfully');
    return redirect()->route('categories.index');
}

 
    public function inactive(Request $request)
    {
        $inactive = Category::find($request->hidden_id);
        $inactive->status = 0;
        $inactive->save();
        Toastr::success('Success','Data inactive successfully');
        return redirect()->back();
    }
    public function active(Request $request)
    {
        $active = Category::find($request->hidden_id);
        $active->status = 1;
        $active->save();
        Toastr::success('Success','Data active successfully');
        return redirect()->back();
    }
    public function destroy(Request $request)
    {
        $delete_data = Category::find($request->hidden_id);
        $delete_data->delete();
        Toastr::success('Success','Data delete successfully');
        return redirect()->back();
    }
}
