<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin\Masters;

use App\Http\Controllers\Admin\Controller;
use App\Http\Requests\Admin\Masters\CategoryStoreRequest;
use App\Http\Requests\Admin\Masters\CategoryUpdateRequest;
use App\Models\Category;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Fetch categories with their subcategories
        $categories = Category::where('level', 1)->get();

        return view('admin.masters.categories', compact('categories'));
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(CategoryStoreRequest $request)
    {
        try
        {
            DB::beginTransaction();
            $input          = $request->validated();
            $input['level'] = 1;
            if ($request->hasFile('image'))
            {
                $input['image'] = 'storage/'.$input['image']->store('categories', 'public');
            }
            Category::create(Arr::only($input, Category::getFillables()));
            DB::commit();

            return response()->json(['success' => 'Category created successfully!']);
        }
        catch (Exception $e)
        {
            return $this->respondWithAjax($e, 'creating', 'Category');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): void
    {
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Category $category)
    {
        $categoryImgHtml = '<a href="'.asset($category->image).'" target="_blank
                                <div class="card p-0 m-0">
                                    <div class="card-body p-0 m-0">
                                        <img src="'.asset($category->image).'" class="img-fluid" alt="category_image">
                                    </div>
                                </div>
                            </a>';

        return [
            'result'          => 1,
            'category'        => $category,
            'categoryImgHtml' => $categoryImgHtml,

        ];
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(CategoryUpdateRequest $request, Category $category)
    {
        try
        {
            DB::beginTransaction();
            $input          = $request->validated();
            $input['level'] = 1;
            if (isset($input['image']))
            {
                $input['image'] = 'storage/'.$input['image']->store('categories', 'public');
                if (File::exists(public_path('\\').$category->image))
                {
                    File::delete(public_path('\\').$category->image);
                }
            }
            else
            {
                $input['image'] = $category->image;
            }
            $category->update(Arr::only($input, Category::getFillables()));
            DB::commit();

            return response()->json(['success' => 'Category updated successfully!']);
        }
        catch (Exception $e)
        {
            return $this->respondWithAjax($e, 'updating', 'Category');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Category $category)
    {
        try
        {
            DB::beginTransaction();
            if (File::exists(public_path('\\').$category->image))
            {
                File::delete(public_path('\\').$category->image);
            }
            $category->delete();
            DB::commit();

            return response()->json(['success' => 'Category deleted successfully!']);
        }
        catch (Exception $e)
        {
            return $this->respondWithAjax($e, 'deleting', 'Category');
        }
    }
}
