<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\HadithCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class HadithCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $categories = HadithCategory::withCount('hadiths')->orderBy('created_at', 'desc')->get();
        return view('dashboard.hadith-category.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('dashboard.hadith-category.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            HadithCategory::create($request->all());

            return redirect()
                ->route('hadith-categories.index')
                ->with('success', 'Hadith category created successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Error creating category: '.$e->getMessage());
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $category = HadithCategory::findOrFail($id);
        return view('dashboard.hadith-category.edit', compact('category'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $category = HadithCategory::findOrFail($id);
            $category->update($request->all());

            return redirect()
                ->route('hadith-categories.index')
                ->with('success', 'Hadith category updated successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Error updating category: '.$e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $category = HadithCategory::findOrFail($id);
            
            // Check if category has hadiths
            if ($category->hadiths()->count() > 0) {
                return redirect()
                    ->route('hadith-categories.index')
                    ->with('error', 'Cannot delete category. It has associated hadiths. Please remove or reassign hadiths first.');
            }
            
            $category->delete();

            return redirect()
                ->route('hadith-categories.index')
                ->with('success', 'Hadith category deleted successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->route('hadith-categories.index')
                ->with('error', 'Error deleting category: '.$e->getMessage());
        }
    }
}
