<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('category.category', [
            'title' => 'Category',
            'categories' => Category::all(),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('category.create', [
            'title' => 'Create Category'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request['slug'] = Str::of($request->name)->slug('-');

        // Validate input data
        $validateData = $request->validate([
            'name' => 'required',
            'slug' => 'required|unique:categories',
            'image' => 'required|image',
        ]);

        // Handle image upload
        $validateData['image'] = $request->file('image')->store('image_post', 'public');

        // Create new category
        $store = Category::create($validateData);

        return $store
            ? redirect()->route('category.index')->with('success', 'New category has been added!')
            : redirect()->route('category.index')->with('failed', 'Failed to add new category!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        return view('category.show', [
            'title' => $category->name,
            'category' => $category
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Category $category)
    {
        return view('category.edit', [
            'title' => 'Edit Category ' . $category->name,
            'category' => $category,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  Category  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        // Validate the update request
        $validate = [
            'name' => 'sometimes|required',
            'image' => 'sometimes|image',
        ];

        // Check if slug needs to be updated
        $slug = Str::of($request->name)->slug('-');
        if ($slug != $category->slug) {
            $validate += ['slug' => 'sometimes|required|unique:categories'];
            $request['slug'] = $slug;
        }

        $validateData = $request->validate($validate);

        // Handle image upload if provided
        if ($request->hasFile('image')) {
            // Delete the old image from storage if exists
            if ($category->image) {
                Storage::disk('public')->delete($category->image);
            }

            // Store new image
            $validateData['image'] = $request->file('image')->store('image_post', 'public');
        }

        // Update the category
        $update = $category->update($validateData);

        return $update
            ? redirect()->route('category.index')->with('success', 'Category has been updated!')
            : redirect()->route('category.index')->with('failed', 'Failed to update category!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  Category  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        // Delete the category image if it exists
        if ($category->image) {
            Storage::disk('public')->delete($category->image);
        }

        // Delete the category from the database
        $delete = $category->delete();

        return $delete
            ? redirect()->route('category.index')->with('success', 'Category has been deleted!')
            : redirect()->route('category.index')->with('failed', 'Failed to delete category!');
    }
}
