<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Art;
use App\Models\JudicialPrecedent;
use App\Models\JudicialPrecedentCategory;
use Illuminate\Http\Request;

class JudicialPrecedentController extends Controller
{
    public function index(Request $request)
    {
        $query = JudicialPrecedent::query();

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

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

        return view('admin.judicial-precedent.index', compact('judicialPrecedents'));
    }

    public function create()
    {
        $arts = Art::all();
        $categories = JudicialPrecedentCategory::all();
        return view('admin.judicial-precedent.create', compact('arts', 'categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'ruling_number' => 'required|unique:judicial_precedents,ruling_number',
            'ruling_date' => 'required|date',
            'subject' => 'required|string',
            'full_text' => 'required|string',
            'issuing_authority' => 'nullable|string',
            'category_id' => 'nullable|exists:judicial_precedent_categories,id',
            'art_ids' => 'nullable|array',
            'art_ids.*' => 'exists:arts,id'
        ]);

        $judicialPrecedent = JudicialPrecedent::create([
            'ruling_number' => $validated['ruling_number'],
            'ruling_date' => $validated['ruling_date'],
            'subject' => $validated['subject'],
            'full_text' => $validated['full_text'],
            'issuing_authority' => $validated['issuing_authority'] ?? 'هیأت عمومی دیوان عالی کشور',
            'category_id' => $validated['category_id']
        ]);

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

        return redirect(route('judicial-precedent.index'));
    }

    public function edit(JudicialPrecedent $judicialPrecedent)
    {
        $arts = Art::all();
        $categories = JudicialPrecedentCategory::all();
        $selectedArtIds = $judicialPrecedent->arts->pluck('id')->toArray();
        
        return view('admin.judicial-precedent.update', compact('judicialPrecedent', 'arts', 'categories', 'selectedArtIds'));
    }

    public function update(Request $request, JudicialPrecedent $judicialPrecedent)
    {
        $validated = $request->validate([
            'ruling_number' => 'required|unique:judicial_precedents,ruling_number,' . $judicialPrecedent->id,
            'ruling_date' => 'required|date',
            'subject' => 'required|string',
            'full_text' => 'required|string',
            'issuing_authority' => 'nullable|string',
            'category_id' => 'nullable|exists:judicial_precedent_categories,id',
            'art_ids' => 'nullable|array',
            'art_ids.*' => 'exists:arts,id'
        ]);

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

        return redirect(route('judicial-precedent.edit', $judicialPrecedent->id));
    }

    public function destroy(JudicialPrecedent $judicialPrecedent)
    {
        $judicialPrecedent->delete();
        return redirect(route('judicial-precedent.index'));
    }
}
