<?php

use App\Cawangan;
use App\Helper;
use App\Tebus;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

$active_cawangan_db_connection = Helper::getActiveCawanganDbConnection();

$request->startDate = Carbon::now();
$request->endDate = Carbon::now();


$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_penebusan_data = array_map(function ($db_connection) use ($tarikh) {
    $penebusan = Tebus::on($db_connection)
        ->join('gadai', 'tebus.norujukan', '=', 'gadai.norujukan')
        ->where('gadai.upah12', '!=', null)
        ->where('tebus.t_tebus', '>=', $request->startDate)
        ->where('tebus.t_tebus', '<=', $request->endDate)
        ->select(DB::raw('
        count(tebus.norujukan) as bilangan_tebus,
        sum(gadai.berat) as berat,
        sum(gadai.bakipjm) as nilai_pinjaman,
        sum(tebus.pinjaman) as baki_pinjaman,
        sum(tebus.nilaimarhun) as nilai_marhun,
        sum(tebus.bakiupah) as keuntungan_asal,
        sum(tebus.bakipjm - gadai.bakipjm) as keuntungan_rebet,
        sum(gadai.bakipjm) + sum(tebus.bakipjm - gadai.bakipjm) as bayaran_penebusan
        '))
        ->get();


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

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

return json_encode($response);
