<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Art;
use App\Models\LegalOpinion;
use App\Models\LegalOpinionCategory;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class LegalOpinionController extends Controller
{
    public function index(Request $request)
    {
        $query = LegalOpinion::with('category');

        if ($request->filled('q')) {
            $q = $request->q;
            $query->where(function ($qry) use ($q) {
                $qry->where('opinion_number', 'like', "%{$q}%")
                    ->orWhere('subject', 'like', "%{$q}%")
                    ->orWhere('full_text', 'like', "%{$q}%")
                    ->orWhere('issuing_authority', 'like', "%{$q}%");
            });
        }

        $perPage = min(max((int) $request->input('per_page', 15), 10), 100);
        $legalOpinions = $query->latest()->paginate($perPage)->withQueryString();

        return view('admin.legal-opinion.index', compact('legalOpinions'));
    }

    public function create()
    {
        $arts = Art::all();
        $categories = LegalOpinionCategory::all();

        return view('admin.legal-opinion.create', compact('arts', 'categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'opinion_number' => [
                'required',
                Rule::unique('legal_opinions', 'opinion_number')->where('category_id', $request->input('category_id')),
            ],
            'opinion_date' => 'nullable|date',
            'subject' => 'nullable|string|max:1000',
            'full_text' => 'required|string',
            'issuing_authority' => 'nullable|string',
            'category_id' => 'required|exists:legal_opinion_categories,id',
            'art_ids' => 'nullable|array',
            'art_ids.*' => 'exists:art,id',
        ]);

        $legalOpinion = LegalOpinion::create([
            'opinion_number' => $validated['opinion_number'],
            'opinion_date' => $validated['opinion_date'] ?? null,
            'subject' => $validated['subject'] ?? null,
            'full_text' => $validated['full_text'],
            'issuing_authority' => $validated['issuing_authority'] ?? null,
            'category_id' => $validated['category_id'],
        ]);

        if (!empty($validated['art_ids'])) {
            $legalOpinion->arts()->attach($validated['art_ids']);
        }

        return redirect(route('legal-opinion.index'));
    }

    public function edit(LegalOpinion $legalOpinion)
    {
        $arts = Art::all();
        $categories = LegalOpinionCategory::all();
        $selectedArtIds = $legalOpinion->arts->pluck('id')->toArray();

        return view('admin.legal-opinion.update', compact('legalOpinion', 'arts', 'categories', 'selectedArtIds'));
    }

    public function show(LegalOpinion $legalOpinion)
    {
        return redirect(route('legal-opinion.edit', $legalOpinion->id));
    }

    public function update(Request $request, LegalOpinion $legalOpinion)
    {
        $validated = $request->validate([
            'opinion_number' => [
                'required',
                Rule::unique('legal_opinions', 'opinion_number')
                    ->where('category_id', $request->input('category_id'))
                    ->ignore($legalOpinion->id),
            ],
            'opinion_date' => 'nullable|date',
            'subject' => 'nullable|string|max:1000',
            'full_text' => 'required|string',
            'issuing_authority' => 'nullable|string',
            'category_id' => 'required|exists:legal_opinion_categories,id',
            'art_ids' => 'nullable|array',
            'art_ids.*' => 'exists:art,id',
        ]);

        $legalOpinion->update([
            'opinion_number' => $validated['opinion_number'],
            'opinion_date' => $validated['opinion_date'] ?? null,
            'subject' => $validated['subject'] ?? null,
            'full_text' => $validated['full_text'],
            'issuing_authority' => $validated['issuing_authority'] ?? null,
            'category_id' => $validated['category_id'],
        ]);

        $legalOpinion->arts()->sync($validated['art_ids'] ?? []);

        return redirect(route('legal-opinion.edit', $legalOpinion->id));
    }

    public function destroy(LegalOpinion $legalOpinion)
    {
        $legalOpinion->delete();

        return redirect(route('legal-opinion.index'));
    }
}
