<?php
declare(strict_types=1);

namespace App\Modules\Pricing\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Pricing\Models\PricingConfig;

class PricingController extends Controller
{
    public function index(Request $request): Response
    {
        $configs = PricingConfig::allWithDetails();
        return $this->view('Pricing.Views.index', ['configs' => $configs]);
    }

    public function edit(Request $request, string $id): Response
    {
        $config = PricingConfig::find((int) $id);
        if (!$config) {
            return $this->redirect('/pricing')->withError('التسعير غير موجود');
        }
        $db = App::getInstance()->db();
        $branches = $db->select("SELECT id, name_ar FROM branches WHERE is_active = 1 ORDER BY name_ar");
        $quals = $db->select("SELECT id, name_ar FROM qualifications WHERE is_active = 1 ORDER BY sort_order");
        return $this->view('Pricing.Views.edit', ['config' => $config, 'branches' => $branches, 'quals' => $quals]);
    }

    public function update(Request $request, string $id): Response
    {
        $config = PricingConfig::find((int) $id);
        if (!$config) {
            return $this->redirect('/pricing')->withError('التسعير غير موجود');
        }
        $data = $this->validate($request->all(), [
            'price'          => 'required|numeric|min:0',
            'effective_from' => 'required|date',
            'effective_to'   => 'nullable|date',
            'notes'          => 'nullable|string|max:1000',
        ]);
        $config->update([
            'price'          => $data['price'],
            'effective_from' => $data['effective_from'],
            'effective_to'   => $data['effective_to'] ?? null,
            'notes'          => $data['notes'] ?? null,
        ]);
        return $this->redirect('/pricing')->withSuccess('تم تحديث التسعير بنجاح');
    }
}