<?php
namespace App\Models;use App\Core\Database;
final class PaymentSchedule
{
 public static function add(int $org,int $invoice,array $v,int $user):void
 {
  $date=trim((string)($v['due_date']??''));
  $amount=round((float)($v['amount']??0),2);
  $method=trim((string)($v['payment_method']??''));
  if($invoice<=0)throw new \RuntimeException('Facture introuvable.');
  if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$date))throw new \RuntimeException('La date prévue est invalide.');
  if($amount<=0)throw new \RuntimeException('Le montant de l’échéance doit être supérieur à zéro.');
  if($method==='')throw new \RuntimeException('Choisissez un mode de règlement.');
  $pdo=Database::connection();
  $pdo->beginTransaction();
  try{
   $lock=$pdo->prepare("SELECT id FROM cda_invoices WHERE id=? AND organisation_id=? AND deleted_at IS NULL FOR UPDATE");
   $lock->execute([$invoice,$org]);
   if(!$lock->fetchColumn())throw new \RuntimeException('Facture introuvable.');
   $q=$pdo->prepare("SELECT COALESCE(MAX(installment_number),0)+1 FROM cda_payment_schedules WHERE invoice_id=?");
   $q->execute([$invoice]);$n=(int)$q->fetchColumn();
   $insert=$pdo->prepare("INSERT INTO cda_payment_schedules(organisation_id,invoice_id,installment_number,due_date,amount,payment_method,cheque_number,drawer_bank,created_by) VALUES(?,?,?,?,?,?,?,?,?)");
   $insert->execute([$org,$invoice,$n,$date,$amount,$method,trim((string)($v['cheque_number']??''))?:null,trim((string)($v['drawer_bank']??''))?:null,$user]);
   $pdo->commit();
  }catch(\Throwable $e){if($pdo->inTransaction())$pdo->rollBack();throw $e;}
 }
 public static function due(int $org):array {$q=Database::connection()->prepare("SELECT s.*,i.document_number,c.nom,c.prenom FROM cda_payment_schedules s JOIN cda_invoices i ON i.id=s.invoice_id JOIN clients c ON c.id=i.client_id WHERE s.organisation_id=? AND s.status IN('planned','due','late') ORDER BY s.due_date");$q->execute([$org]);return $q->fetchAll();}
}
