<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Response;
use App\Core\Session;
use App\Services\ServiceService;
use InvalidArgumentException;
use RuntimeException;

final class ServiceController extends Controller
{
    public function __construct(private ?ServiceService $service=null){$this->service??=new ServiceService();}
    public function index(): Response
    {
        $filters=['search'=>(string)($_GET['search']??''),'status'=>(string)($_GET['status']??''),'page'=>(int)($_GET['page']??1)];
        return $this->view('services/index',['pageTitle'=>'Services','pageDescription'=>'Manage therapy services and pricing.','services'=>$this->service->list($filters),'filters'=>$filters]);
    }
    public function createForm(): Response
    { return $this->view('services/form',['pageTitle'=>'New Service','pageDescription'=>'Create a billable therapy service.','service'=>null,'csrf'=>Csrf::token(),'form'=>Session::pull('service_form')??[],'error'=>Session::pull('service_error'),'message'=>Session::pull('service_message')]); }
    public function create(): Response
    { Csrf::verify((string)($_POST['_csrf']??'')); try{$id=$this->service->create($_POST,Auth::id()??0);Session::put('service_message','Service created successfully.');return Response::redirect('/crm/public/services/'.$id.'/edit');}catch(InvalidArgumentException|RuntimeException $e){Session::put('service_error',$e->getMessage());Session::put('service_form',$_POST);return Response::redirect('/crm/public/services/create');} }
    public function editForm(int $id): Response
    { return $this->view('services/form',['pageTitle'=>'Edit Service','pageDescription'=>'Update service details and pricing.','service'=>$this->service->find($id),'csrf'=>Csrf::token(),'form'=>Session::pull('service_form')??[],'error'=>Session::pull('service_error'),'message'=>Session::pull('service_message')]); }
    public function update(int $id): Response
    { Csrf::verify((string)($_POST['_csrf']??''));try{$this->service->update($id,$_POST,Auth::id()??0);Session::put('service_message','Service updated successfully.');}catch(InvalidArgumentException|RuntimeException $e){Session::put('service_error',$e->getMessage());Session::put('service_form',$_POST);}return Response::redirect('/crm/public/services/'.$id.'/edit'); }
    public function delete(int $id): Response
    { Csrf::verify((string)($_POST['_csrf']??''));try{$this->service->delete($id,Auth::id()??0);Session::put('service_message','Service deleted successfully.');}catch(RuntimeException $e){Session::put('service_error',$e->getMessage());}return Response::redirect('/crm/public/services'); }
}
