<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Log;
use RealRashid\SweetAlert\Facades\Alert;
use Str;

class CategoryController extends Controller
{
    public function index(Request $request)
    {

        $page = $request->page;

        if(isset($page) && is_numeric($page) && $page>0) {

            $records_to_show = 25;
            $records_to_skip = ($page - 1) * $records_to_show;

            $query = Category::query();
            $query->where('deleted', 0);

            $all_records_count = $query->count();

            $num_of_pages = (int) ceil($all_records_count / $records_to_show);
            
            $categories = $query->skip($records_to_skip)
            ->take($records_to_show)
            ->with('parent')
            ->get();

            return view('categories.index', compact('categories','num_of_pages', 'page'));

            
        } else {
            return redirect()->route('categories.index', ['page'=>1]);
        }

    }

    public function create() {

        if(session()->has('success')) {
            Alert::success('success', session()->get('success'));
        }

        if(session()->has('error')) {
            Alert::error('error', session()->get('error'));
        }

        $categories = Category::where('parent_id', 0)->select("id", "name")->get();

        return view('categories.form', compact("categories"));
    }

    public function store(Request $request) {
        $insert = 0;
        $error = '';

        try {

            $this->requestValidations();

            $inputs = $request->all();

            // Upload Main Image
            $imgName = $this->uploadFile($request, 'image', 'categories_imgs', 'required|mimes:jpeg,jpg,png,webp,avif|max:1024');
            $inputs['image'] = $imgName;

            // Store
            $insert = Category::create($inputs);

        } catch (ValidationException $e) {
            return redirect()->back()->withErrors($e->errors())->withInput();

        } catch (\Exception $e) {
            $error = $e->getMessage();
        }

        if($insert) {
            Session()->flash('success' , 'Record Created Successfully !');
        } else {
            Log::error($error);
            Session()->flash('error' , 'Something went wrong.');
        }
       
        return redirect()->back();
    }

    public function show($id) {
        
        if(session()->has('success')) {
            Alert::success('success', session()->get('success'));
        }

        if(session()->has('error')) {
            Alert::error('error', session()->get('error'));
        }

        $category = Category::findOrFail($id);
        $categories = Category::where('parent_id', 0)->select("id", "name")->get();

        return view('categories.form', compact('category', 'categories'));
    }

    public function update(Request $request, Category $category, $id)
    {

        $status = 0;
        $error = '';

        try {

            $this->requestValidations($id);
            $category = Category::findOrFail($id);

            $inputs = $request->all();

            if($request->image != null) {
                // Upload Image
                $imgName = $this->uploadFile($request, 'image', 'categories_imgs', 'required|mimes:jpeg,jpg,png,webp,avif|max:1024');
                $inputs['image'] = $imgName;
            }

            $category->fill($inputs);

            if($category->save()) {
                $status = 1;
            }
            
        } catch (ValidationException $e) {
            return redirect()->back()->withErrors($e->errors())->withInput();

        } catch (\Exception $e) {
            $error = $e->getMessage();
        }

        if($status) {
            Session()->flash('success' , 'Record Updated Successfully !');
        } else {
            Log::error($error);
            Session()->flash('error' , 'Something went wrong.');
        }
       
        return redirect()->back();
        
    }

    public function destroy(Request $request)
    {
        $status = 0;
        $message = 'Something went wrong !';

        $delete = Category::where('id', $request->record_id)->update(['deleted' => 1]);

        if($delete) {
            $status = 1;
            $message = "Record Deleted Successfully !";
        }

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

    public function requestValidations($record_id = null) {

        $slugUniqueRule = Rule::unique('categories', 'slug')->ignore($record_id);

        return request()->validate([
            'name' => ['required', 'string', 'max:128'],
        ]);
    }


    public function uploadFile(Request $request, $file_name, $folder_name, $rules) {

        // Get the uploaded file
        $file = $request->file($file_name);
    
        // Validation rules for general files
        $fileRules = [
            $file_name => $rules,
        ];
    
        // Validate the file input
        $this->validate($request, $fileRules);
    
        // Generate a unique name for the file
        $fileName = uniqid().'_'.Str::random(6).'.'.$file->getClientOriginalExtension();
    
        // Specify the directory where you want to save the file
        $directory = 'uploads/'.$folder_name;
    
        // Create the directory if it doesn't exist
        File::makeDirectory($directory, $mode = 0777, true, true);
    
        // Move the uploaded file to the specified directory
        $file->move($directory, $fileName);
    
        // Return the path of the uploaded file
        return $folder_name.'/'.$fileName;
    }
    

}
