<?php

namespace App\Http\Controllers\Reports;

use App\Cawangan;
use App\Gadai;
use App\Helper;
use App\Http\Controllers\Controller;
use App\Services\Reports\AgingService as ReportAgingService;
use App\Transaction;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\StokAudit1;
use App\StokAudit2;
use App\StokAudit3;
use App\StokAudit4;
use App\StokAudit5;
use App\StokAudit6;
use App\StokAudit7;
use App\StokAudit8;
use App\StokAudit9;
use App\StokAudit10;
use App\StokAudit11;
use App\StokAudit12;

class AgingController extends Controller
{

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

    public function getSummaryLaporanAgingbackup(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_aging_by_cawangan' => $summary_ansuran_by_cawangan,
        'summary_aging' => $summary_ansuran, // Now contains the grand totals
    ];

    return json_encode($response);
}

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

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

    $current = Carbon::now();
    $endDate = Carbon::parse($request->endDate);
    $bulan = $endDate->month;
    $tahun = $endDate->year;

    $result = [];

    foreach ($kod_caw_with_cawangan_detail_array as $kodcaw => $details_caw) {
        $cawangan = $cawangan_available->firstWhere('kodcaw', $kodcaw);
        if (!$cawangan) {
            continue;
        }

        // Determine which table to query
        if ($current->month == $bulan && $current->year == $tahun) {
            $audit = Gadai::on($cawangan->mysql)
                ->where(function ($q) use ($endDate) {
                    $q->where([
                        ['tagpalsu', '=', 0],
                        ['t_gadai', '<=', $endDate->toDateString()],
                        ['sttebus', '=', '']
                    ])
                    ->orWhere([
                        ['tagpalsu', '=', 0],
                        ['t_update', '>', $endDate->toDateString()],
                        ['sttebus', '!=', ''],
                        ['t_gadai', '<=', $endDate->toDateString()]
                    ]);
                });
        } else {
            $tableMap = [
                1 => StokAudit1::class, 2 => StokAudit2::class, 3 => StokAudit3::class,
                4 => StokAudit4::class, 5 => StokAudit5::class, 6 => StokAudit6::class,
                7 => StokAudit7::class, 8 => StokAudit8::class, 9 => StokAudit9::class,
                10 => StokAudit10::class, 11 => StokAudit11::class, 12 => StokAudit12::class,
            ];

            $model = $tableMap[$bulan] ?? null;
            if (!$model) {
                continue;
            }

            $audit = $model::on($cawangan->mysql)->where('tahun', $tahun);
        }

        // Categorize data by tempoh
        $summary = [];

        for ($i = 1; $i <= 13; $i++) {
            $query = clone $audit;

            if ($i == 13) {
                $filtered = $query->where('tempoh', '>', 12);
            } elseif ($i == 1) {
                $filtered = $query->whereBetween('tempoh', [0.01, 1.5]);
            } elseif ($i == 12) {
                $filtered = $query->where('tempoh', 12);
            } else {
                $filtered = $query->where([['tempoh','>',$i-(0.5)],['tempoh','<=',$i+(0.5)]]);
            }

            $labelMap = [
                1 => '1 Bulan',
                2 => '2 Bulan',
                3 => '3 Bulan',
                4 => '4 Bulan',
                5 => '5 Bulan',
                6 => '6 Bulan',
                7 => '7 bulan',
                8 => '8 Bulan',
                9 => '9 Bulan',
                10 => '10 Bulan',
                11 => '11 Bulan',
                12 => '12 Bulan',
                13 => '> 12 Bulan'
            ];

            $summary[] = [
                 'label' => $labelMap[$i],
                'count' => $filtered->count(),
                'sum_bakipjm' => $filtered->sum('bakipjm'),
            ];
        }

        $result[] = [
            'kodcaw' => $kodcaw,
            'cawangan' => $details_caw,
            'tahun' => $tahun,
            'bulan' => $bulan,
            'summary_by_tempoh' => $summary
        ];
    }

    return response()->json($result);
}






}
