<?php

namespace App\Http\Controllers;

use App\Models\CattleCategory;
use Illuminate\Http\Request;

class CattleCategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view categories', ['only' => ['index', 'show']]);
        $this->middleware('permission:create categories', ['only' => ['create', 'store']]);
        $this->middleware('permission:update categories', ['only' => ['edit', 'update']]);
        $this->middleware('permission:delete categories', ['only' => ['destroy']]);
    }

    public function index()
    {
        $user = auth()->user();

        if (!$user) {
            abort(403, 'Unauthorized access.');
        }

        $categoriesQuery = CattleCategory::with('user')
            ->withCount('animals')
            ->withSum('expenses as total_expense_amount', 'amount')
            ->latest();

        if (!$user->hasRole('super admin')) {
            $categoriesQuery->where('user_id', $user->id);
        }

        $categories = $categoriesQuery->get();

        return view('cattle-categories.index', compact('categories'));
    }

    public function create()
    {
        return view('cattle-categories.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $category = CattleCategory::create([
            'user_id' => auth()->id(),
            'title' => $request->title,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
        ]);

        audit_log(
            'cattle_categories',
            $category->id,
            'created',
            'Cattle category created successfully',
            $category->toArray()
        );

        return redirect()
            ->route('cattle-categories.index')
            ->with('success', 'Cattle category created successfully.');
    }

    public function show(CattleCategory $cattleCategory)
    {
        $this->authorizeOwner($cattleCategory);

        audit_log(
            'cattle_categories',
            $cattleCategory->id,
            'viewed',
            'Cattle category viewed successfully',
            $cattleCategory->toArray()
        );

        return view('cattle-categories.show', compact('cattleCategory'));
    }

    public function edit(CattleCategory $cattleCategory)
    {
        $this->authorizeOwner($cattleCategory);

        return view('cattle-categories.edit', compact('cattleCategory'));
    }

    public function update(Request $request, CattleCategory $cattleCategory)
    {
        $this->authorizeOwner($cattleCategory);

        $request->validate([
            'title' => 'required|string|max:255',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $oldData = $cattleCategory->toArray();

        $cattleCategory->update([
            'title' => $request->title,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
        ]);

        audit_log(
            'cattle_categories',
            $cattleCategory->id,
            'updated',
            'Cattle category updated successfully',
            [
                'old' => $oldData,
                'new' => $cattleCategory->fresh()->toArray(),
            ]
        );

        return redirect()
            ->route('cattle-categories.index')
            ->with('success', 'Cattle category updated successfully.');
    }

    public function destroy(CattleCategory $cattleCategory)
    {
        $this->authorizeOwner($cattleCategory);

        $oldData = $cattleCategory->toArray();

        $cattleCategory->delete();

        audit_log(
            'cattle_categories',
            $oldData['id'],
            'deleted',
            'Cattle category deleted successfully',
            $oldData
        );

        return redirect()
            ->route('cattle-categories.index')
            ->with('success', 'Cattle category deleted successfully.');
    }

    private function authorizeOwner(CattleCategory $cattleCategory)
    {
        $user = auth()->user();

        if ($user->hasRole('super admin')) {
            return true;
        }

        if ($cattleCategory->user_id == $user->id) {
            return true;
        }

        abort(403, 'Unauthorized access.');
    }
}