<?php
declare(strict_types=1);

namespace App\Modules\ServiceCatalog\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\ServiceCatalog\Models\ServicePrice;

class CatalogController extends Controller
{
    public function index(Request $request): Response
    {
        $services = ServicePrice::allActive();
        return $this->view('ServiceCatalog.Views.index', ['services' => $services]);
    }

    public function edit(Request $request, string $id): Response
    {
        $service = ServicePrice::find((int) $id);
        if (!$service) {
            return $this->redirect('/catalog')->withError('الخدمة غير موجودة');
        }
        return $this->view('ServiceCatalog.Views.edit', ['service' => $service]);
    }

    public function update(Request $request, string $id): Response
    {
        $service = ServicePrice::find((int) $id);
        if (!$service) {
            return $this->redirect('/catalog')->withError('الخدمة غير موجودة');
        }
        $data = $this->validate($request->all(), [
            'base_amount'   => 'nullable|numeric|min:0',
            'percentage'    => 'nullable|numeric|min:0|max:100',
            'annual_amount' => 'nullable|numeric|min:0',
        ]);
        $service->update([
            'base_amount'   => $data['base_amount'] ?? null,
            'percentage'    => $data['percentage'] ?? null,
            'annual_amount' => $data['annual_amount'] ?? null,
        ]);
        return $this->redirect('/catalog')->withSuccess('تم تحديث الخدمة بنجاح');
    }
}