<?php

namespace App\Http\Controllers\Reports;

use App\Cawangan;
use App\Gadai;
use App\Helper;
use App\Http\Controllers\Controller;
use App\Services\Reports\AnsuranService as ReportAnsuranService;
use App\Transaction;
use Illuminate\Http\Request;

class AnsuranController extends Controller
{

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

    public function getSummaryLaporanAnsuran(Request $request)
{
    $online_array_db_connection = Helper::getOnlineArrahnConnection();
    $cawangan_available = Cawangan::on($online_array_db_connection)->select('kodcaw', 'details_caw', 'mysql')->get();

    $kodcaw_array = array_column($cawangan_available->toArray(), 'kodcaw');
    $kod_caw_with_cawangan_detail_array = $cawangan_available->pluck('details_caw', 'kodcaw')->toArray();

    // Step 1: Fetch the ansuran data grouped by cawangan
    $ansuran_query = Transaction::on($online_array_db_connection)
        ->leftJoin('transaksi_keuntungan', function ($join) {
            $join->on('transaction.norujukan', '=', 'transaksi_keuntungan.norujukan');
            $join->on('transaction.created_at', '=', 'transaksi_keuntungan.tarikh_bayaran');
        })
        ->where('transaction.trans_type', '=', 'A')
        ->whereDate('transaction.created_at', '>=', date($request->startDate))
        ->whereDate('transaction.created_at', '<=', date($request->endDate))
        ->selectRaw('
            transaction.kodcaw as kod_cawangan,
            count(transaction.norujukan) as bilangan_ansuran,
            sum(transaksi_keuntungan.bayaran_pembiayaan) as bayaran_pembiayaan,
            sum(transaksi_keuntungan.bayaran_keuntungan) as bayaran_kos_keuntungan,
            sum(transaction.duit_masuk) as jumlah_bayaran,
            GROUP_CONCAT(transaction.norujukan) as norujukan_list
        ')
        ->groupBy('transaction.kodcaw')
        ->get();

    $total_nilai_marhun_by_cawangan = [];

    // Step 2: Loop through ansuran_query and fetch nilai_marhun per kodcaw
    foreach ($ansuran_query as $ansuran_cawangan) {
        $kodcaw = $ansuran_cawangan->kod_cawangan;
        $norujukan_list = explode(',', $ansuran_cawangan->norujukan_list); // Convert to array

        // Get database connection for this branch
        $mysql_connection = $cawangan_available->where('kodcaw', $kodcaw)->first()->mysql ?? null;
        if (!$mysql_connection) {
            continue;
        }

        // Sum nilai_marhun for matching norujukan in gadai table
        $total_nilai_marhun_by_cawangan[$kodcaw] = Gadai::on($mysql_connection)
            ->whereIn('norujukan', $norujukan_list)
            ->sum('nilaimarhun');
    }

    // Step 3: Merge ansuran summary with total_nilai_marhun
    $summary_ansuran_by_cawangan = $ansuran_query
        ->filter(function ($ansuran_cawangan) use ($kodcaw_array) {
            return in_array($ansuran_cawangan['kod_cawangan'], $kodcaw_array);
        })
        ->map(function ($ansuran_cawangan) use ($kod_caw_with_cawangan_detail_array, $total_nilai_marhun_by_cawangan) {
            $kodcaw = $ansuran_cawangan->kod_cawangan;
            $ansuran_cawangan->cawangan_detail = $kod_caw_with_cawangan_detail_array[$kodcaw] ?? 'Unknown';
            $ansuran_cawangan->total_nilai_marhun = $total_nilai_marhun_by_cawangan[$kodcaw] ?? 0;
            unset($ansuran_cawangan->norujukan_list); // Remove unnecessary field
            return $ansuran_cawangan;
        })
        ->values();

    // Step 4: Calculate overall totals
    $total_summary = [
        'bilangan_ansuran' => 0,
        'bayaran_pembiayaan' => 0,
        'bayaran_kos_keuntungan' => 0,
        'jumlah_bayaran' => 0,
        'total_nilai_marhun' => 0,
    ];

    foreach ($summary_ansuran_by_cawangan as $ansuran_cawangan) {
        $total_summary['bilangan_ansuran'] += $ansuran_cawangan->bilangan_ansuran ?? 0;
        $total_summary['bayaran_pembiayaan'] += $ansuran_cawangan->bayaran_pembiayaan ?? 0;
        $total_summary['bayaran_kos_keuntungan'] += $ansuran_cawangan->bayaran_kos_keuntungan ?? 0;
        $total_summary['jumlah_bayaran'] += $ansuran_cawangan->jumlah_bayaran ?? 0;
        $total_summary['total_nilai_marhun'] += $ansuran_cawangan->total_nilai_marhun ?? 0;
    }

    // Step 5: Prepare the overall ansuran summary
    $summary_ansuran = [
        'bilangan_ansuran' => $total_summary['bilangan_ansuran'],
        'bayaran_pembiayaan' => $total_summary['bayaran_pembiayaan'],
        'bayaran_kos_keuntungan' => $total_summary['bayaran_kos_keuntungan'],
        'jumlah_bayaran' => $total_summary['jumlah_bayaran'],
        'total_nilai_marhun' => $total_summary['total_nilai_marhun'],
    ];

    $response = [
        'summary_ansuran_by_cawangan' => $summary_ansuran_by_cawangan,
        'summary_ansuran' => $summary_ansuran, // Now contains the grand totals
    ];

    return json_encode($response);
}


}
