<?php

namespace App\Http\Controllers;

use App\WTDDraft;
use App\TuntutBaki;
use App\Cawangan;
use App\Customer;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Helper;
use App\SerahBaki;
use App\WTD;

use Illuminate\Support\Facades\Http;

class WTDController extends Controller
{
    public function getDraftWTD(Request $request){
        $sagwtddraft = WTDDraft::where('norujukan',$request->norujukan)->first();

        if($sagwtddraft){
            return 'yes';
        }else{
            return 'no';
        }
    }

    public function getCustomerWTD(Request $request){

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();


        $tuntutbaki = TuntutBaki::on($cawangan['mysql'])
                ->select('teller')
                ->where('norujukan',$request->norujukan)
                ->get();

        return response()->json($tuntutbaki);
    }

    public function getSummaryWtd(Request $request){

        $startDate = $request->startDate ?? now()->startOfMonth()->toDateString();
        $endDate   = $request->endDate ?? now()->endOfMonth()->toDateString();

        $active_dbs = Helper::getActiveCawanganDbConnection();

        $cawangan = Cawangan::select('kodcaw', 'details_caw', 'mysql')
            ->whereIn('mysql', $active_dbs)
            ->get();

        $responses = [];

        foreach ($cawangan as $caw) {

            $db = $caw->mysql;

            $tuntutbaki = TuntutBaki::on($db)
                ->join('serahbaki', 'serahbaki.t_jual', '=', 'tuntutbaki.tarikh')
                ->join('gadai', 'gadai.norujukan', '=', 'tuntutbaki.norujukan')
                ->whereBetween('tuntutbaki.tarikh', [$startDate, $endDate])
                ->where('tuntutbaki.teller', 'DM')
                ->where('serahbaki.aktif', 1)
                ->selectRaw("
                    gadai.nokp as nokp,
                    tuntutbaki.norujukan as norujukan,
                    tuntutbaki.jumlah as jumlah,
                    serahbaki.batchno as batchno,
                    serahbaki.t_jual as t_jual,
                    serahbaki.t_htr_ag as t_htr_ag
                ")
                ->orderByRaw('CAST(serahbaki.batchno AS UNSIGNED)')
                ->orderBy('tuntutbaki.norujukan')
                ->get();
            
            $nokps = $tuntutbaki
                ->pluck('nokp')
                ->filter()      // elak null
                //->unique()
                ->values();
                
            $customers = Customer::on('mysql7')
                ->whereIn('kplama', $nokps)
                ->orWhereIn('kpbaru', $nokps)
                ->get()
                ->keyBy(function ($item) {
                    return $item->kpbaru ?: $item->kplama;
                });

            $wtd_det = [];

            foreach ($tuntutbaki as $tuntut) {

                $nokp = $tuntut->nokp;
                $cust = $customers->get($nokp);

                $wtd_det[] = [
                    "norujukan" => $tuntut->norujukan,
                    "nokp"      => $nokp,
                    "jumlah"    => (float) $tuntut->jumlah,
                    "batchno"   => $tuntut->batchno,
                    "t_proses"  => $tuntut->t_jual,
                    "t_htr_ag"  => $tuntut->t_htr_ag,
                    "nama_cust" => $cust->nama ?? null,
                ];
            }

            $details = collect($wtd_det)
                ->values()
                ->all();
             
            $responses[] = [
                'kodcaw'       => $caw->kodcaw,
                'details_caw'  => $caw->details_caw,
                // WEB
                'jumlah_surat' => count($details),
                'sum_baki'     => collect($details)->sum('jumlah'),
                // EXCEL
                'details'      => $details,
            ];
        }
        return response()->json($responses);
    
    }

    public function getDebugWtd(Request $request){

        $startDate = $request->startDate ?? now()->startOfMonth()->toDateString();
        $endDate   = $request->endDate ?? now()->endOfMonth()->toDateString();

        $active_dbs = Helper::getActiveCawanganDbConnection();

        $cawangan = Cawangan::select('kodcaw', 'details_caw', 'mysql')
            ->whereIn('mysql', $active_dbs)
            ->get();

        $responses = [];

        foreach ($cawangan as $caw) {

            $db = $caw->mysql;

            $serahbaki = SerahBaki::on($db)
            ->whereBetween('t_jual', [$startDate, $endDate])
            ->where('aktif', 1)
            //->selectRaw("baki as serahb")
            ->sum('baki');;
            //->get();
            
            $tuntutbaki = TuntutBaki::on($db)
            ->whereBetween('tarikh', [$startDate, $endDate])
            ->where('teller', 'DM')
            //->selectRaw("jumlah as tuntutb")
            ->sum('jumlah');
            //->get();

            $twtd = WTD::on($db)
            ->whereBetween('tarikh', [$startDate, $endDate])
            //->selectRaw("wtd as twtd")
            ->sum('wtd');
            //->get();

            $wtd_det = [];

                $wtd_det[] = [
                    "serahb" => $serahbaki,
                    "tuntutb"   => $tuntutbaki,
                    "twtd"    => $twtd,
                ];

            $details = collect($wtd_det)
                ->values()
                ->all();
                //dd($details);
             
            $responses[] = [
                'kodcaw'       => $caw->kodcaw,
                'details_caw'  => $caw->details_caw,
                //collect($details)->sum('jumlah'),
                // WEB
                'serahb' => collect($details)->sum('serahb'),
                'tuntutb' => collect($details)->sum('tuntutb'),
                'twtd' => collect($details)->sum('twtd'),
                //'debugwtd' => $details,
            ];
        }
        return response()->json($responses);
    
    }
}
