<?php

namespace App\Imports;

use App\Models\Cloture;
use App\Models\Exercices;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;

class BalanceOuvertureImport implements ToCollection, WithHeadingRow
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {   
        

      /* $val = Validator::make($collection->toArray(), [
            '*.compte' => 'required',
            '*.solde'  => 'required',
        ])->validate();

        if($val->fails()) {
           dd('error');
        }
        */
        /*if ($validator->stopOnFirstFailure()->fails()) {
            // ...
        }*/


      
           /* User::create([
                'name' => $row[0],
            ]); */
            //$d .= $row['compte'].'_'.$row['solde'].'--' ;

            $exercice_n1 = intval(getExercice()) - 1; 
            
            try {
                DB::beginTransaction();

                Exercices::create([
                    'exercice'  => $exercice_n1 ,
                    'is_closed' => 1,
                    'is_auto'   => 1,
                    'start_date' => $exercice_n1.'-01-01',
                    'end_date'   => $exercice_n1.'-12-31',
                    'id_app' => get_id_app(),
                    'user_crea' => get_pseudo(),
                    'user_closed' => 'SYSADMIN',
                ]);

                foreach ($collection as $row) 
                {
                    Cloture::create([
                        'exercice' => $exercice_n1 ,
                        'fk_num_compte' => $row['compte'],
                        'solde' => $row['solde'],
                        'devise' => $row['devise'],
                        'fk_idworkday' => 1,
                        'user_crea' => get_pseudo(),
                        'id_app' => get_id_app()
                    ]);
                }

                DB::commit() ;
            } catch (\Throwable $th) {
                //throw $th;

                dd($th);
              //  DB::rollBack();
            }
    
    }
}
