<?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\PaymentService;use InvalidArgumentException;use RuntimeException;
final class PaymentController extends Controller
{
    public function __construct(private ?PaymentService $service=null){$this->service??=new PaymentService();}
    public function index():Response{$filters=['search'=>(string)($_GET['search']??''),'status'=>(string)($_GET['status']??''),'page'=>(int)($_GET['page']??1)];return $this->view('payments/index',['pageTitle'=>'Payments','pageDescription'=>'Record and review invoice payments.','payments'=>$this->service->list($filters),'filters'=>$filters,'csrf'=>Csrf::token(),'message'=>Session::pull('payment_message'),'error'=>Session::pull('payment_error')]);}
    public function createForm(int $invoiceId):Response{try{$invoice=$this->service->invoice($invoiceId);return $this->view('payments/form',['pageTitle'=>'Record Payment','pageDescription'=>'Record a full or partial payment against an invoice.','invoice'=>$invoice,'csrf'=>Csrf::token(),'form'=>Session::pull('payment_form')??[],'error'=>Session::pull('payment_error'),'message'=>Session::pull('payment_message')]);}catch(RuntimeException $e){return Response::html('<h1>'.htmlspecialchars($e->getMessage(),ENT_QUOTES,'UTF-8').'</h1>',404);}}
    public function create(int $invoiceId):Response{Csrf::verify((string)($_POST['_csrf']??''));try{$id=$this->service->create($invoiceId,$_POST,Auth::id()??0);Session::put('payment_message','Payment recorded and receipt generated successfully.');return Response::redirect('/crm/public/payments/'.$id.'/receipt');}catch(InvalidArgumentException|RuntimeException $e){Session::put('payment_error',$e->getMessage());Session::put('payment_form',$_POST);return Response::redirect('/crm/public/invoices/'.$invoiceId.'/payment');}}
    public function void(int $id):Response{Csrf::verify((string)($_POST['_csrf']??''));try{$this->service->void($id,Auth::id()??0);Session::put('payment_message','Payment voided successfully.');}catch(RuntimeException|InvalidArgumentException $e){Session::put('payment_error',$e->getMessage());}return Response::redirect('/crm/public/payments');}
    public function receipt(int $id):Response{try{$payment=$this->service->find($id);$invoice=$this->service->invoice((int)$payment['invoice_id']);$receipt=null;foreach($invoice['payments'] as $p){if((int)$p['id']===$id){$receipt=$p['receipt_number']??null;break;}}return $this->view('payments/receipt',['pageTitle'=>'Receipt','pageDescription'=>'Payment receipt preview.','payment'=>$payment,'invoice'=>$invoice,'receiptNumber'=>$receipt,'csrf'=>Csrf::token(),'message'=>Session::pull('payment_message'),'error'=>Session::pull('payment_error')]);}catch(RuntimeException $e){return Response::html('<h1>'.htmlspecialchars($e->getMessage(),ENT_QUOTES,'UTF-8').'</h1>',404);}}
}
