<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use DB;
use App\Traits\DeleteModelTrait; 


class CategoryController extends Controller
{
    use DeleteModelTrait;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
        $post_categories = Category::select('id', 'title')->where('status', true)->get();
        return response()->json($post_categories);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
        try{
            DB::beginTransaction();
            //validating form data
            $validatedData = $request->validate([
                'title' => 'required|min:3', 
                'status' => 'required|boolean',
            
            ]);

            $post_category = new Category;
            $post_category->title = $validatedData['title'];
            $post_category->status = $validatedData['status'];
            $post_category->save();

            DB::commit();
            return to_route('admin.categories')->with('success', [
                'message' => ' Category created successfully',
                'check' => false
            ]);
        } catch (ValidationException $e){
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Validation Error: '.$e->getMessage(),
                'check' => $e->getMessage()
            ]);
        } catch(\Exception $e) {
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Error: '.$e->getMessage(),
                'check' => $e->getMessage()
            ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Category $Category)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $category = Category::findOrFail($id);
        return response()->json($category);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            DB::beginTransaction();
            $validatedData = $request->validate([
                'title' => 'required|min:3', 
                'status' => 'required',
                
            ]);

            // Retrieve the category or fail.
            $category = Category::findOrFail($id);

            $category->fill($validatedData);
            if ($category->isDirty()){
                $category->save();
            }

            DB::commit();

            return Redirect::back()->with('success', [
                'message' => 'Category updated successfully',
                'check'   => false
            ]);
        } catch (ValidationException $e) {
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Validation error: ' . $e->getMessage(),
                'check'   => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Error: ' . $e->getMessage(),
                'check'   => $e->getMessage()
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        return $this->deleteModel($id, new Category());
    }

    public function fetchPostCategories()
    {
        // Fetch all categories
        $categories = Category::orderBy('created_at', 'desc')->get();
        return Inertia::render('posts/categories/Category', [
            'categories' => $categories->map(function ($category) {
                return $category->only('id','title','status','created_at');
            }),
        ]);
    }
}
