<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\TestCatalogRequest;
use App\Models\TestCatalog;
use App\Models\TestCategory;

class TestCatalogController extends Controller
{
    public function index()
    {
        $tests = TestCatalog::query()
            ->with('categoryRelation:id,name')
            ->orderBy('name')
            ->paginate(20);
        return view('admin.tests.index', compact('tests'));
    }

    public function create()
    {
        $categories = TestCategory::query()->where('is_active', true)->orderBy('name')->get();
        return view('admin.tests.create', compact('categories'));
    }

    public function store(TestCatalogRequest $request)
    {
        $data = $request->validated();
        $data['is_active'] = (bool)($data['is_active'] ?? true);
        $data['category'] = TestCategory::query()->whereKey($data['category_id'])->value('name');

        TestCatalog::create($data);

        return redirect()->route('admin.tests.index')->with('success', 'Test created.');
    }

    public function edit(TestCatalog $test)
    {
        $categories = TestCategory::query()->where('is_active', true)->orderBy('name')->get();
        return view('admin.tests.edit', compact('test', 'categories'));
    }

    public function update(TestCatalogRequest $request, TestCatalog $test)
    {
        $data = $request->validated();
        $data['is_active'] = (bool)($data['is_active'] ?? false);
        $data['category'] = TestCategory::query()->whereKey($data['category_id'])->value('name');

        $test->update($data);

        return redirect()->route('admin.tests.index')->with('success', 'Test updated.');
    }

    public function destroy(TestCatalog $test)
    {
        $test->delete();
        return redirect()->route('admin.tests.index')->with('success', 'Test deleted.');
    }
}
