<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
use SebastianBergmann\Diff\Exception;

class ProductController extends Controller
{
    //
    public function index(){
        //get all categories
        $categories = Category::orderBy("created_at", "DESC")->get();
        return view("admin.products.add")->with("categories", $categories);
    }

    public function manage(){
        //get all products
        $products = Product::orderBy("created_at", "DESC")->get();
        return view("admin.products.manage")->with("products", $products);
    }

    public function store(Request $request){
        //validate
        $request->validate([
            'name' => 'required',
            'price' => 'required',
            'category' => 'required',
            'file' => ['mimes:png,jpg,jpeg', 'max:2048']
        ]);

        //move file
        if($request->file != null){
            //get filename with the extension
            $fileNameWithExt = $request->file("file")->getClientOriginalName();
            //get just the filename
            $filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
            //get just ext
            $extension = $request->file('file')->getClientOriginalExtension();
            //file name
            $fileNameToStore = str_replace(" ", "_", strtolower($filename)).'_'.time().'.'.$extension;
            //upload file
            $path = $request->file("file")->storeAs('public/img/', $fileNameToStore);
        }else{
            $fileNameToStore = 'default.png';
        }

        $slug = strtolower(preg_replace('/\s+/', '_', $request->name));

        try{

            Product::create([
                "name" => $request->name,
                "description" => $request->description,
                "price" => $request->price,
                "category_id" => $request->category,
                "photo" => $fileNameToStore,
                "slug" => $slug,
                "vat" => $request->vat,
            ]);
            return redirect()->back()->with("success", "Product Added");
        }catch(Exception $e){
            return redirect()->back()->with("error", "Oops, there was an error!!");
        }
    }

    public function edit($id){
        $product = Product::find($id);
        $categories = Category::orderBy("created_at", "DESC")->get();
        return view("admin.products.edit")->with(["product" => $product, "categories" => $categories]);
    }

    public function update(Request $request){
        //validate
        $request->validate([
            'name' => 'required',
            'price' => 'required',
            'category' => 'required',
            'file' => ['mimes:png,jpg,jpeg', 'max:2048']
        ]);

        //move file
        if($request->file != null){
            //get filename with the extension
            $fileNameWithExt = $request->file("file")->getClientOriginalName();
            //get just the filename
            $filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
            //get just ext
            $extension = $request->file('file')->getClientOriginalExtension();
            //file name
            $fileNameToStore = str_replace(" ", "_", strtolower($filename)).'_'.time().'.'.$extension;
            //upload file
            $path = $request->file("file")->storeAs('public/img/', $fileNameToStore);
        }else{
            if($request->filespan != null){
                $fileNameToStore = $request->filespan;
            }else{
                $fileNameToStore = 'default.png';
            }
        }

        $slug = strtolower(preg_replace('/\s+/', '_', $request->name));

        try{

            Product::where("id", $request->id)->update([
                "name" => $request->name,
                "description" => $request->description,
                "price" => $request->price,
                "category_id" => $request->category,
                "photo" => $fileNameToStore,
                "slug" => $slug,
                "vat" => $request->vat,
            ]);
            return redirect()->back()->with("success", "Product Updated");
        }catch(Exception $e){
            return redirect()->back()->with("error", "Oops, there was an error!!");
        }
    }

    public function deleteModal($id){
        $product = Product::find($id);
        $view = view('modals.product.delete', compact('product'))->render();
        return response()->json(['html'=>$view]);
    }

    public function delete(Request $request){
        try {
            Product::where("id", $request->id)->delete();
            return redirect()->back()->with("success", "Product Deleted");
        } catch (Exception $e) {
            return redirect()->back()->with("error", "Oops, there was an error!!");
        }
    }
}
