<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Law;
use Illuminate\Http\Request;

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

        if ($request->filled('q')) {
            $query->where('title', 'like', '%' . $request->q . '%');
        }
        if ($request->filled('locked')) {
            $query->where('is_locked', $request->locked === '1');
        }

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

        return view('admin.law.index', compact('laws'));
    }

    public function create()
    {
        $categories = Category::all();

        return view('admin.law.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'is_locked' => 'nullable',
            'category_id' => 'nullable|integer|exists:categories,id',
            'price' => 'nullable|numeric',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $validated['is_locked'] = $request->has('is_locked', false);

        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            dd($request->has('image'));
            $imageName = uniqid('image_', true) . '.' . $request->file('image')->getClientOriginalExtension();

            $request->file('image')->move(public_path('images'), $imageName);

            $validated['image'] = $imageName;
        }

        Law::create($validated);

        return redirect()->route('law.index')->with('success', 'Law created successfully.');
    }



    public function edit(Law $law)
    {
        $categories = Category::all();
        return view('admin.law.update', compact('law', 'categories'));
    }

    public function update(Request $request, Law $law)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'is_locked' => 'sometimes',
            'category_id' => 'nullable|integer',
            'price' => 'nullable|numeric',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $validated['is_locked'] = $request->boolean('is_locked');

        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            $imageName = uniqid('image_', true) . '.' . $request->file('image')->getClientOriginalExtension();
            $request->file('image')->move(public_path('images'), $imageName);
            $validated['image'] = $imageName;
        }

        $law->update($validated);

        return redirect()->route('law.index');
    }

    public function destroy(Law $law)
    {
        $law->delete();

        return redirect(route('law.index'));
    }
}
