<?php

namespace App\Http\Controllers;

use App\Models\Department;
use App\Models\KeyResultArea;
use App\Models\KpiLibrary;
use Illuminate\Http\Request;
use Inertia\Inertia;

class KraController extends Controller
{
    public function index(Request $request)
    {
        $kras = KeyResultArea::with(['department:id,name'])
            ->withCount('kpis')
            ->when($request->search, fn($q, $s) => $q->where('name', 'like', "%{$s}%"))
            ->when($request->department, fn($q, $d) => $q->where('department_id', $d))
            ->orderBy('name')
            ->paginate(20)
            ->withQueryString();

        return Inertia::render('KRA/Index', [
            'kras' => $kras,
            'filters' => $request->only('search', 'department'),
            'departments' => Department::active()->select('id', 'name')->orderBy('name')->get(),
        ]);
    }

    public function create()
    {
        return Inertia::render('KRA/Form', [
            'departments' => Department::active()->select('id', 'name')->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'department_id' => 'nullable|exists:departments,id',
            'is_active' => 'boolean',
        ]);

        KeyResultArea::create($validated);

        return redirect()->route('kras.index')->with('success', 'Key Result Area created successfully.');
    }

    public function edit(KeyResultArea $kra)
    {
        return Inertia::render('KRA/Form', [
            'kra' => $kra,
            'departments' => Department::active()->select('id', 'name')->orderBy('name')->get(),
        ]);
    }

    public function update(Request $request, KeyResultArea $kra)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'department_id' => 'nullable|exists:departments,id',
            'is_active' => 'boolean',
        ]);

        $kra->update($validated);

        return redirect()->route('kras.index')->with('success', 'Key Result Area updated successfully.');
    }

    public function destroy(KeyResultArea $kra)
    {
        $kra->delete();
        return redirect()->route('kras.index')->with('success', 'Key Result Area deleted successfully.');
    }
}
