<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\State;
use Illuminate\Http\Request;

class StateController extends Controller
{
    public function index()
    {
        $states = State::withCount(['zones', 'regulations'])->latest()->paginate(20);
        return view('admin.states.index', compact('states'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'             => ['required', 'string', 'max:100', 'unique:states,name'],
            'code'             => ['required', 'string', 'max:5', 'unique:states,code'],
            'capital'          => ['nullable', 'string', 'max:100'],
            'regulatory_body'  => ['nullable', 'string', 'max:255'],
            'notes'            => ['nullable', 'string'],
            'is_active'        => ['boolean'],
        ]);
        $data['is_active'] = $request->boolean('is_active', true);
        $state = State::create($data);
        ActivityLog::record('create', $state, 'Created state: ' . $state->name);
        return redirect()->route('admin.states.index')->with('success', 'State created successfully.');
    }

    public function show(State $state)
    {
        return redirect()->route('admin.states.edit', $state);
    }

    public function edit(State $state)
    {
        return view('admin.states.form', compact('state'));
    }

    public function update(Request $request, State $state)
    {
        $data = $request->validate([
            'name'             => ['required', 'string', 'max:100', 'unique:states,name,' . $state->id],
            'code'             => ['required', 'string', 'max:5', 'unique:states,code,' . $state->id],
            'capital'          => ['nullable', 'string', 'max:100'],
            'regulatory_body'  => ['nullable', 'string', 'max:255'],
            'notes'            => ['nullable', 'string'],
            'is_active'        => ['boolean'],
        ]);
        $data['is_active'] = $request->boolean('is_active', true);
        $state->update($data);
        ActivityLog::record('update', $state, 'Updated state: ' . $state->name);
        return redirect()->route('admin.states.index')->with('success', 'State updated successfully.');
    }

    public function destroy(State $state)
    {
        ActivityLog::record('delete', $state, 'Deleted state: ' . $state->name);
        $state->delete();
        return redirect()->route('admin.states.index')->with('success', 'State deleted.');
    }
}
