<?php

namespace App\Console\Commands\PaymentTransactions;

use App\Models\PaymentManagement\PaymentTransaction;
use App\Models\SettingManagement\PaymentTransactionStatus;
use App\Models\Statut;
use App\Models\TransactionCommande;
use Illuminate\Console\Command;

class DeleteTransaction extends Command{

    protected $signature = 'payments-transactions:delete';

    protected $description = 'Supprime les transactions en echec dans la table payment_transactions';


    public function __construct(){
        parent::__construct();
    }


    public function handle(){

        $dir_log = '/transactions/delete/';
        $statuts = [
            PaymentTransactionStatus::FAILED,
            PaymentTransactionStatus::APPROVED,
            PaymentTransactionStatus::UNDER_PROCESS,
        ];
        $transactions  = PaymentTransaction::whereIn("status_code",$statuts)->get();
        $messages['errors'] = null;
        $age = 3;

        $nbre_tours = 1;
        /*s'il ya des transactions*/
        if (!blank($transactions)){
            set_time_limit(600); // 10 min

            foreach ($transactions as $transaction) : // pour chaque transaction
                try {
                    $reference_transaction = $transaction->reference_transaction;
                    $created_at = $transaction->created_at->format('Y-m-d');
                    $date_cmd = date_create($created_at);
                    $now = date_create(date('Y-m-d'));
                    $date_diff = date_diff($date_cmd,$now); // diff entre les 2 dates
                    $nb_days =  $date_diff->d; // nbre de jour entre les 2 date
                    $nb_months =  $date_diff->m; // nbre de mois entre les 2 date

                    $nb_days += ($nb_months * 30);

                    $this->info("tour = $nbre_tours ref = $reference_transaction");

                    /*si la reference a été crée 03 jrs avant l'execution du script
                        elle doit etre supprimée*/
                    if ($nb_days >= $age){
                        $transaction->delete();
                        $message = __("ref  = $reference_transaction a été supprimé. created_at = $created_at");
                        write_log("$dir_log/success",$message,'info');
                    }
                }catch (\Exception $exception){
                    write_log("$dir_log/errors",$exception,'error');
                }
                $nbre_tours++;
            endforeach;

        }
    }
}
