<?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 = $request->all();
        $service->update([
            'base_amount'   => ($data['base_amount'] ?? '') !== '' ? $data['base_amount'] : null,
            'percentage'    => ($data['percentage'] ?? '') !== '' ? $data['percentage'] : null,
            'annual_amount' => ($data['annual_amount'] ?? '') !== '' ? $data['annual_amount'] : null,
        ]);
        return $this->redirect('/catalog')->withSuccess('تم تحديث الخدمة بنجاح');
    }
}