<?php

namespace App\Models\PaymentManagement;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PaymentReference extends Model{
    use HasFactory;

    protected $guarded = [] ;
    protected $keyType = "string";
    protected $primaryKey = "reference";
    public $timestamps = false ;
    public $incrementing = false ;
    protected $dates = ['created_at'];
    protected $table = "payment_mgt__references";


    public static function new($prefix = "", $lenght = 7, $c = 1){

        try {
            $ref = (string) random_int(1000, 9999999);
            $ref =  substr($ref,0,$lenght); // recupere une ref a $lenght (7) caractères

            $new_reference = strtoupper($prefix.$ref);
            $column = ($prefix == "IR") ? 'internal_reference' : 'provider_reference';

            if (Payment::where($column,$ref)->first()){ // si le paiement existe
                return self::new($prefix,$lenght,($c + 1));
            }
            //  write_log("momo","prefix = $prefix c = $c ref = $ref new_ref = $new_reference",'infos',"ici");

            /*si la reference générée n'existe pas encore dans le système*/
            if(!PaymentReference::find($new_reference)){
                /*on enregistre la reférence*/
                return PaymentReference::create(['reference'=> $new_reference , "created_at" => now()]);
            }
        } catch (\Exception $e) {
            write_log("new-paiement-reference",$e,"error","generation");
        }

        //return self::new($prefix,$lenght,($c + 1));
    }
}
