<?php

namespace App\Http\Controllers\ACC;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\ACC\TempTRN;
use App\Models\ACC\AccTRN;
use App\Imports\ImportTRN;
use Maatwebsite\Excel\Facades\Excel;

class TempTRNController extends Controller
{
    //
    public function importtrndata(Request $request)
    {
        if(Excel::import(new importTRN,$request->file)){


            $dataimport = TempTRN::get();

            foreach($dataimport as $dim)
            {

                $repaire = AccTRN::all()->sortByDesc('id')->take(1)->toArray();
                $number = 1;
                foreach($repaire as $re)
                {
                    $number = $re['trn_id'];
                }
                if($number!=''){
                    $number1 = str_replace("INC","",$number);
                    $number2 = str_replace("EXP","",$number1);
                    $number3 = str_replace("CAP","",$number2);
                    $number4 = str_replace("CIN","",$number3);
                    $number = (int)$number4+1;
                    $length = 8;
                    $number = substr(str_repeat(0, $length).$number, - $length);
                }

                if($dim['trn_type'] =='income'){ $tnum = 'INC'; $dr = '571'; $cr = '707'; }
                elseif($dim['trn_type'] =='expense'){ $tnum = 'EXP'; $dr = '658'; $cr = '571'; }
                elseif($dim['trn_type'] =='capital'){ $tnum = 'CAP'; }
                elseif($dim['trn_type'] =='cincome'){ $tnum = 'CIN'; }

                
                //$accs->timestamps = false;
                $accs = new AccTRN([
                    'trn_id' => $tnum.$number,
                    'trn_type' => $dim['trn_type'],
                    'acc_trn_detail' => 'import: '.$dim['name'],
                    'amount' => (int)$dim['amount'],
                    'count' => (int)$dim['count'],
                    'sum' => (int)$dim['amount']*(int)$dim['count'],
                    'rate' => 1,
                    'dr' => $dr,
                    'cr' => $cr,
                    'user_id' => $dim['user_id'],
                   /// 'created_at' => $dim['year'].'-'.$dim['month'].'1',
                ]);
                $accs->save();
                $accs_id = $accs->id;

                $acc = AccTRN::find($accs_id);
                $acc->update(['created_at' => $dim['year'].'-'.$dim['month'].'-01 00:00:00' ]);



                //$post = Post::find($id)
                //$newDate = $post->created_at->format('d-m-Y');

            }

            //TempTRN::all()->delete();
            TempTRN::truncate();  
            return 'Ok';

        } else {
            return 'No';
        }

    }
}
