<?php
namespace App\Services;
use App\Core\Database;use App\Models\Billing;
final class BillingDocumentService
{
 private function template(string $code):int {$q=Database::connection()->prepare("SELECT id FROM axiom_document_templates WHERE code=? AND active=1 AND status='published' AND archived_at IS NULL ORDER BY version_no DESC LIMIT 1");$q->execute([$code]);$id=(int)$q->fetchColumn();if(!$id)throw new \RuntimeException('Modèle Studio non publié : '.$code);return $id;}
 public function invoice(int $id,int $org):array {$i=Billing::find($id,$org);if(!$i)throw new \RuntimeException('Facture introuvable.');$s=Billing::settings($org);$lines=[];foreach($i['lines'] as $l)$lines[]=['description'=>$l['description'],'activity'=>trim(($l['pole_code']??'').' '.($l['project_code']??'')),'period'=>trim(($l['service_start']??'').' - '.($l['service_end']??'')),'quantity'=>number_format((float)$l['quantity'],2,',',' '),'unit_price'=>number_format((float)$l['unit_price'],2,',',' ').' €','discount'=>number_format((float)$l['discount_amount'],2,',',' ').' €','total'=>number_format((float)$l['net_amount'],2,',',' ').' €'];$schedules=[];foreach($i['schedules'] as $p)$schedules[]=['installment_number'=>$p['installment_number'],'due_date'=>$p['due_date'],'payment_method'=>$p['payment_method'],'cheque_number'=>$p['cheque_number']?:'—','amount'=>number_format((float)$p['amount'],2,',',' ').' €','status'=>$p['status']];$data=['organisation_name'=>$s['legal_name'],'organisation_address'=>$s['address_line1'],'organisation_postal_city'=>$s['postal_code'].' '.$s['city'],'siret'=>$s['siret'],'document_label'=>$i['document_type']==='credit'?'AVOIR':($i['document_type']==='proforma'?'FACTURE PRO FORMA':'FACTURE'),'document_number'=>$i['document_number']?:'Brouillon','issue_date'=>$i['issue_date']??date('Y-m-d'),'client_name'=>$i['prenom'].' '.$i['nom'],'client_account'=>$i['client_account'],'client_address'=>trim(($i['adresse_ligne1']??'').' '.($i['code_postal']??'').' '.($i['ville']??'')),'lines'=>$lines,'schedules'=>$schedules,'total_amount'=>number_format((float)$i['total_amount'],2,',',' ').' €','paid_amount'=>number_format((float)$i['paid_amount'],2,',',' ').' €','balance_amount'=>number_format(max(0,(float)$i['total_amount']-(float)$i['paid_amount']),2,',',' ').' €','account_holder'=>$s['account_holder']??'','bank_name'=>$s['bank_name']??'','iban'=>$s['iban']??'','bic'=>$s['bic']??'','cheque_instruction'=>$s['cheque_instruction']??'','vat_mention'=>$s['vat_mention']??''];return (new StudioDocumentService())->render($this->template('facture_cda_studio'),$data,null,false);}
 public function receipt(int $paymentId,int $org,int $user):array {$pdo=Database::connection();$q=$pdo->prepare("SELECT p.*,i.document_number,i.client_id,c.nom,c.prenom,r.name cash_register,u.nom cashier_nom,u.prenom cashier_prenom FROM cda_payments p JOIN cda_invoices i ON i.id=p.invoice_id JOIN clients c ON c.id=i.client_id LEFT JOIN cda_cash_movements m ON m.payment_id=p.id LEFT JOIN cda_cash_registers r ON r.id=m.target_register_id LEFT JOIN utilisateurs u ON u.id=p.created_by WHERE p.id=? AND i.organisation_id=? AND p.payment_method LIKE '%Esp%'");$q->execute([$paymentId,$org]);$p=$q->fetch();if(!$p)throw new \RuntimeException('Paiement espèces introuvable.');$q=$pdo->prepare("SELECT * FROM cda_cash_receipts WHERE payment_id=?");$q->execute([$paymentId]);$receipt=$q->fetch();if(!$receipt){$year=(int)date('Y');$pdo->prepare("INSERT INTO cda_document_sequences VALUES(?, 'receipt', ?,0) ON DUPLICATE KEY UPDATE last_number=last_number")->execute([$org,$year]);$pdo->prepare("UPDATE cda_document_sequences SET last_number=LAST_INSERT_ID(last_number+1) WHERE organisation_id=? AND document_type='receipt' AND fiscal_year=?")->execute([$org,$year]);$number='REC-'.$year.'-'.str_pad((string)$pdo->lastInsertId(),6,'0',STR_PAD_LEFT);$pdo->prepare("INSERT INTO cda_cash_receipts(organisation_id,payment_id,receipt_number,issued_by) VALUES(?,?,?,?)")->execute([$org,$paymentId,$number,$user]);$receipt=['receipt_number'=>$number];}$s=Billing::settings($org);$data=['receipt_number'=>$receipt['receipt_number'],'client_name'=>$p['prenom'].' '.$p['nom'],'amount'=>number_format((float)$p['amount'],2,',',' ').' €','document_number'=>$p['document_number'],'payment_date'=>$p['payment_date'],'cash_register'=>$p['cash_register']??'Caisse','cashier_name'=>trim(($p['cashier_prenom']??'').' '.($p['cashier_nom']??'')),'vat_mention'=>$s['vat_mention']];return (new StudioDocumentService())->render($this->template('recu_especes_cda'),$data,null,false)+['receipt_number'=>$receipt['receipt_number']];}
}
