<?php

namespace App\Http\Controllers\Reports;

use App\Cawangan;
use App\Helper;
use App\Http\Controllers\Controller;
use App\Services\Reports\PenebusanService as ReportPenebusanService;
use App\Tebus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PenebusanController extends Controller
{

    public function getLaporanCawangan(string $kod_cawangan, Request $request)
    {
        $reportGadaianService = new ReportPenebusanService($kod_cawangan, $request);
        return $reportGadaianService->getCawanganReport();
    }

    public function getSummaryLaporanTebus(Request $request)
    {
        // Get active branch DBs from helper
        $active_cawangan_db_connection = Helper::getActiveCawanganDbConnection();
    
        // Fetch branch details with mysql info
        $cawangan_available = Cawangan::select('kodcaw', 'details_caw', 'mysql')
            ->whereIn('mysql', $active_cawangan_db_connection)
            ->get();
    
        // Get db connections
        $active_cawangan_db_connection = array_column($cawangan_available->toArray(), 'mysql');
    
        // Map branch info for response
        $active_cawangan_detail = $cawangan_available->map(function ($c) {
            return [
                'kodcaw' => $c->kodcaw,
                'details_caw' => $c->details_caw,
            ];
        })->values()->toArray();

        $summary_penebusan_data = array_map(function ($db_connection) use ($request) {
            $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.pinjaman) as nilai_pinjaman,
                sum(gadai.bakipjm) 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);
    }
}
