<?php


namespace App\Services\OnlinePayments;


use App\Models\PaymentManagement\PaymentTransaction;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;


trait CanSaveResponseInJsonFile {

    public function getDisk(){
        return Storage::disk("payments-transactions");
    }

    /**
     * @param PaymentTransaction $transaction
     * @param array $data
     * @param string $path
     * @return bool
     */
    public function saveDataTofile(PaymentTransaction $transaction ,array $data,$path = ''){
        $disk =  $this->getDisk();

        $reference = $transaction->reference;
        $fileName = "$reference.json";

        $filePath = $this->getFilePathToday($path);
        $fullFilePath= "$filePath/$fileName";

        // enregistre sous format json les donnees recues.
        $disk->put($fullFilePath,json_encode($data));

        //sauvegarde le lien du fichier en bd
        return $transaction->update(['file' => $fullFilePath]);

    }

    public function getFilePathToday($fileName)  {

        $disk =  $this->getDisk();
        $today = date('d-m-Y');
        $period = date("m-Y");
        $year = date('Y');

        /* chemin du sous-dossier parent [2021/06-2021/26-06-2022] ou sera stocké
               le fichier qui contient toutes les commandes de la journée */
        $pathToday = "$year/$period/$today/$fileName";

        if (!$disk->exists($pathToday)){
            $disk->makeDirectory($pathToday);

        }
        return $pathToday;
    }


}
