<?php

use App\Cawangan;
use App\Customer;
use App\Gadai;
use App\Helper;

$tarikh = '2023-11-01';

$active_cawangan_db_connection = Helper::getActiveCawanganDbConnection();

$active_cawangan_db = array_map(function($connection){
   return config('database.connections.' . $connection)['database'];
}, $active_cawangan_db_connection);

$active_cawangan_name = Cawangan::whereIn('db_name', $active_cawangan_db)->pluck('details_caw')->toArray();

$gadai_data = array_map(function ($db_connection) use ($tarikh) {
    $gadai = Gadai::on($db_connection)->select('t_gadai', 'norujukan', 'nokp', 'semakbarcode', 'masa', 'berat', 'nilaimarhun', 'pinjaman', 'upah12', 'percentpinj', 'teller', 'nokp')
        ->where('t_gadai', '=', $tarikh)
        ->orderBy('teller')
        ->orderBy('sirig')
        ->get();

   return $gadai->toArray();
}, $active_cawangan_db_connection);

$gadai_data_with_key = array_combine($active_cawangan_name, $gadai_data);

$overall_data_gadai = array_map(function ($gadaian_cawangan) {
    return array_map(function ($gadai) {

        $customer_info = Customer::on('mysql7')->where('kplama', '=', $gadai['nokp'])->orWhere('kpbaru', '=', $gadai['nokp'])->first()->toArray();

        return [
            "t_gadai" => $gadai['t_gadai'],
            "norujukan" => $gadai['norujukan'],
            "nama" => $customer_info['nama'],
            "nokp" => $gadai['nokp'],
            "semakbarcode" => $gadai['semakbarcode'],
            "masa" => $gadai['masa'],
            "berat" => $gadai['berat'],
            "nilaimarhun" => $gadai['nilaimarhun'],
            "pinjaman" => $gadai['pinjaman'],
            "upah12" => $gadai['upah12'],
            "percentpinj" => $gadai['percentpinj'],
            "alamat1" => $customer_info['alamat1'],
            "teller" => $gadai['teller'],
        ];

    }, $gadaian_cawangan);

}, $gadai_data_with_key);

dump($overall_data_gadai);
return $overall_data_gadai;
