<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Div;
use Illuminate\Http\Request;

class DivController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');
        $status = $request->input('status');
        $divs = Div::query()
            ->when($search, fn($q) => $q->search($search))
            ->when($status, fn($q) => $q->status($status))
            ->latest()
            ->paginate(10)
            ->appends(['search' => $search, 'status' => $status]);

        return view('admin.divs.index', compact('divs', 'search', 'status'));
    }

    public function create()
    {
        return view('admin.divs.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:64|unique:divs,code',
            'category' => 'nullable|string|max:255',
            'owner' => 'nullable|string|max:255',
            'status' => 'required|in:active,inactive,archived',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'notes' => 'nullable|string',
        ]);

        $div = Div::create($validated);
        return redirect()->route('admin.divs.index')->with('success', 'Div created successfully.');
    }

    public function show(Div $div)
    {
        return view('admin.divs.show', compact('div'));
    }

    public function edit(Div $div)
    {
        return view('admin.divs.edit', compact('div'));
    }

    public function update(Request $request, Div $div)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:64|unique:divs,code,' . $div->id,
            'category' => 'nullable|string|max:255',
            'owner' => 'nullable|string|max:255',
            'status' => 'required|in:active,inactive,archived',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'notes' => 'nullable|string',
        ]);

        $div->update($validated);
        return redirect()->route('admin.divs.index')->with('success', 'Div updated successfully.');
    }

    public function destroy(Div $div)
    {
        $div->delete();
        return redirect()->route('admin.divs.index')->with('success', 'Div deleted successfully.');
    }
}