<?php

use App\Cawangan;
use App\Gadai;
use Illuminate\Support\Facades\DB;
use App\Helper;

$tarikh = '2023-11-01';
$active_cawangan_db_connection = Helper::getActiveCawanganDbConnection();

$active_cawangan_db_name = array_map(function($db_connection){
    return config('database.connections' . '.' . $db_connection. '.' . 'database' );
}, $active_cawangan_db_connection);

$active_cawangan_detail = Cawangan::select('kodcaw', 'details_caw')->whereIn('db_name', $active_cawangan_db_name)->get()->toArray();

$summary_gadaian_data = array_map(function ($db_connection) use ($tarikh) {
    $gadai = Gadai::on($db_connection)
        ->select(DB::raw('count(norujukan) as total_gadaian, sum(berat) as sum_berat, sum(nilaimarhun) as sum_nilai_marhun, sum(pinjaman) as sum_pinjaman'))
        ->where('t_gadai', '=', $tarikh)
        ->get();

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

$response = array_map(function($cawangan_detail, $summary_gadaian_data){
    return array_merge($cawangan_detail, $summary_gadaian_data[0]);
}, $active_cawangan_detail, $summary_gadaian_data);

return json_encode($response);
