<?php

namespace App\Http\Controllers\Reports;

use App\Http\Controllers\Controller;
use App\Cawangan;
use App\Lelong;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\Reports\LelonganService as ReportLelonganService;
use App\Helper;


class LelonganController extends Controller
{

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

    public function getSummaryLaporanLelong(Request $request)
{
    $onDate = $request->onDate;
    $startDate = $request->startDate;
    $endDate = $request->endDate;

    // Get active branches in the order we want
    $active_cawangan_db_connection = Helper::getActiveCawanganDbConnection();

    // Preserve keys while mapping database names
    $active_cawangan_db_name = array_combine(
        $active_cawangan_db_connection,
        array_map(function ($db_connection) {
            return config('database.connections.' . $db_connection . '.database');
        }, $active_cawangan_db_connection)
    );
    // dd($active_cawangan_db_name);

    // Retrieve branch details and re-index by db_name
    $active_cawangan_detail = Cawangan::select('kodcaw', 'details_caw', 'db_name')
        ->whereIn('db_name', array_values($active_cawangan_db_name))
        ->get()
        ->keyBy('db_name')
        ->toArray();
    // dd($active_cawangan_detail);

    // Retrieve lelong summary data and re-index by db_connection
    $summary_lelongan_data = [];
    foreach ($active_cawangan_db_connection as $db_connection) {
        $query = Lelong::on($db_connection)
            ->join('gadai', 'gadai.norujukan', '=', 'lelong.norujukan') 
            ->select(DB::raw('count(lelong.norujukan) as total_lelongan, 
            sum(lelong.berat) as sum_berat, 
            sum(lelong.nilaimarhun) as sum_nilai_marhun, 
            sum(gadai.pinjaman) as sum_pinjaman, 
            sum(lelong.pinjaman) as sum_bakipjm,
            sum(lelong.bakiupah) as sum_bakiupah,
            sum(lelong.cajlain) as sum_cajlain,
            sum(lelong.cajlelong) as sum_cajlelong,
            sum(lelong.hargajual) as sum_hargajual,
            sum(lelong.hargaasas) as sum_hargaasas,
            sum(lelong.baki) as sum_baki'));
       

        if ($request->filled('startDate') && $request->filled('endDate')) {
            $query->whereBetween('lelong.t_jual', [$request->startDate, $request->endDate]);
        }

        $summary_lelongan_data[$db_connection] = $query->first()->toArray();
    }

    // Ensure data is sorted according to getActiveCawanganDbConnection()
    $response = [];
    foreach ($active_cawangan_db_connection as $db_connection) {
        $db_name = $active_cawangan_db_name[$db_connection] ?? null;
        if ($db_name && isset($active_cawangan_detail[$db_name])) {
            $response[] = array_merge(
                $active_cawangan_detail[$db_name], 
                $summary_lelongan_data[$db_connection] ?? []
            );
        }
    }

    return json_encode($response);
}

public function getSummaryLaporanBakiLelongBelumTuntut(Request $request)
    {
        $onDate = $request->onDate;
        $startDate = $request->startDate;
        $endDate = $request->endDate;

        // Get active branches in the order we want
        $active_cawangan_db_connection = Helper::getActiveCawanganDbConnection();

        // Preserve keys while mapping database names
        $active_cawangan_db_name = array_combine(
            $active_cawangan_db_connection,
            array_map(function ($db_connection) {
                return config('database.connections.' . $db_connection . '.database');
            }, $active_cawangan_db_connection)
        );
        // dd($active_cawangan_db_name);

        // Retrieve branch details and re-index by db_name
        $active_cawangan_detail = Cawangan::select('kodcaw', 'details_caw', 'db_name')
            ->whereIn('db_name', array_values($active_cawangan_db_name))
            ->get()
            ->keyBy('db_name')
            ->toArray();
        // dd($active_cawangan_detail);

        // Retrieve lelong summary data and re-index by db_connection
        $summary_lelongan_data = [];
        foreach ($active_cawangan_db_connection as $db_connection) {
            $query = Lelong::on($db_connection)
                ->join('gadai', 'gadai.norujukan', '=', 'lelong.norujukan') 
                ->select(DB::raw('count(lelong.norujukan) as total_lelongan, 
                sum(lelong.berat) as sum_berat, 
                sum(lelong.nilaimarhun) as sum_nilai_marhun, 
                sum(gadai.pinjaman) as sum_pinjaman, 
                sum(lelong.pinjaman) as sum_bakipjm,
                sum(lelong.bakiupah) as sum_bakiupah,
                sum(lelong.cajlain) as sum_cajlain,
                sum(lelong.cajlelong) as sum_cajlelong,
                sum(lelong.hargajual) as sum_hargajual,
                sum(lelong.baki) as sum_baki'))
                ->where(function ($query) use ($request) {
                $query->whereNull('lelong.trkhtuntut')
                    ->orWhere('lelong.trkhtuntut', '>', $request->endDate); // or use a specific date: '2025-06-01'
                })
                ->where('lelong.baki', '>', 0.00)
                ->orderBy('lelong.norujukan', 'asc');
        

            if ($request->filled('startDate') && $request->filled('endDate')) {
                $query->whereBetween('lelong.t_lelong', [$request->startDate, $request->endDate]);
            }

            $summary_lelongan_data[$db_connection] = $query->first()->toArray();
        }

        // Ensure data is sorted according to getActiveCawanganDbConnection()
        $response = [];
        foreach ($active_cawangan_db_connection as $db_connection) {
            $db_name = $active_cawangan_db_name[$db_connection] ?? null;
            if ($db_name && isset($active_cawangan_detail[$db_name])) {
                $response[] = array_merge(
                    $active_cawangan_detail[$db_name], 
                    $summary_lelongan_data[$db_connection] ?? []
                );
            }
        }

        return json_encode($response);
    }

     public function getLaporanBakiLelongBelumTuntutCawangan(string $kod_cawangan, Request $request)
    {
        $reportLelonganService = new ReportLelonganService($kod_cawangan, $request);
        return $reportLelonganService->getCawanganReportBakiLelongBelumTuntut();
    }

}
