<?php

namespace App\Http\Controllers\Reports;

use App\Cawangan;
use App\Http\Controllers\Controller;
use App\imbangdugabackup;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Services\Reports\ImbangDugaService;
use Illuminate\Support\Facades\Log;

class BalanceSheetsController extends Controller
{

    public function getBalanceSheetsList(Request $request){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();

        $list_imbangan = imbangdugabackup::on($cawangan['mysql'])
            ->where([['tarikh','>=',$request->mula],['tarikh','<=',$request->hingga]])
            ->paginate(5);

        return json_encode($list_imbangan);
    }

    public function insertBalanceSheets(Request $request){
        $igService = new ImbangDugaService($request->kodcaw,$request->tarikh);
        $insert_imbangduga = $igService->setImbangDugaBackup();
        
        return $insert_imbangduga;
    }

    public function updateIGBalanceSheets(Request $request){
        $cawangan = Cawangan::on('mysql7')->where('version','v2')->get();
        $date = Carbon::create($request->year)->month($request->month);
        $lastDay =  (clone $date)->endOfMonth();

        try{
            foreach($cawangan as $caw){
                $igService = new ImbangDugaService($caw['kodcaw'],$lastDay->toDateString());
                $insert_imbangduga = $igService->setImbangDugaBackup();
            }
        }catch(\Exception $e){
            Log::error($e->getMessage());
        }
        

        return response('success');
    }

}
