<?php

use App\Cawangan;
use App\CawanganDetail;
use App\Customer;
use App\Gadai;
use App\Marhun;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Helper;

// test variable
$request = new Request();
$request->all();
$request->merge([
    'startDate' => '2023-8-21',
    'endDate' => '2023-10-22',
    'kod_cawangan' => 'KB2',
]);
// test variable

function getCawanganDetail($cawangan_connection)
{
    $cawangan_detail = CawanganDetail::on($cawangan_connection)->get()
        ->map(function ($detail) {
            return [
                'nama' => $detail['namacaw'],
                'code' => $detail['kodcaw'] . ' Ar-Rahn ' . $detail['cawangan'],
                'alamat' => $detail['alamat1'],
                'waktu_operasi' => $detail['alamat4'],
            ];
        });

    return $cawangan_detail;

}

function getTotalSummaryGadaian(Builder $query_total_gadaian)
{
    $formatNumber = function ($amount) {
        $formattedAmount = number_format($amount, 2, '.', ',');

        return $formattedAmount;
    };

    $total_summary_gadaian = (clone $query_total_gadaian)
        ->selectRaw('sum(berat) as total_berat, sum(nilaimarhun) as total_nilai_marhun, sum(pinjaman) as total_pembiayaan')
        ->get()
        ->map(function ($x) use ($formatNumber) {
            return [
                'total_berat' => $formatNumber($x['total_berat']),
                'total_nilai_marhun' => $formatNumber($x['total_nilai_marhun']),
                'total_pembiayaan' => $formatNumber($x['total_pembiayaan']),
            ];
        });

    return $total_summary_gadaian;
}

function getTotalSummaryGadaianGroupByTeller(Builder $query_total_gadaian)
{

    $total_summary_gadaian_groupByTeller = (clone $query_total_gadaian)
        ->selectRaw('sum(berat) as total_berat, sum(nilaimarhun) as total_nilai_marhun, sum(pinjaman) as total_pembiayaan')
        ->groupBy('teller')
        ->get();
    return $total_summary_gadaian_groupByTeller;
}

function getTotalGadaian(Builder $query_total_gadaian)
{
    $total_gadaian = (clone $query_total_gadaian)
        ->select('t_gadai', 'norujukan', 'nokp', 'semakbarcode', 'masa', 'berat', 'nilaimarhun', 'pinjaman', 'upah12', 'percentpinj', 'teller', 'nokp')
        ->orderBy('teller')
        ->orderBy('sirig')
        ->get();
    return $total_gadaian;
}

function getCustomerInfo($total_gadaian)
{

    $extract_nokp = $total_gadaian->pluck('nokp');

    $customer_info = Customer::on('mysql7')
        ->select(['nama', 'alamat1', 'kpbaru', 'kplama'])
        ->where(function ($query) use ($extract_nokp) {
            $query->whereIn('kpbaru', $extract_nokp)
                ->orWhereIn('kplama', $extract_nokp);
        })
        ->get();

    $customer_info = collect($extract_nokp)->map(function ($nokp) use ($customer_info) {
        return $customer_info->where('kpbaru', $nokp)->first() ?? $customer_info->where('kplama', $nokp)->first();
    })->toArray();

    return $customer_info;
}

function getMarhunGadaian($total_gadaian, $cawangan_connection)
{

    $extract_norujukan = $total_gadaian->pluck('norujukan');

    $marhun_gadaian = Marhun::on($cawangan_connection)
        ->select('norujukan', 'bil', 'marhun')
        ->whereIn('norujukan', $extract_norujukan)
        ->get()
        ->groupBy('norujukan')
        ->toArray();

    $marhun_gadaian = array_map(function ($gadaian) {
        return array_map(function ($norujukan) {
            return $norujukan['bil'] . ' ' . $norujukan['marhun'];
        }, $gadaian);
    }, $marhun_gadaian);

    $marhun_gadaian = array_map(function ($gadaian) {
        return implode(',', $gadaian);
    }, $marhun_gadaian);

    return $marhun_gadaian;
}

function getReportGadaian(Request $request)
{
$cawangan_connection = Cawangan::where('kodcaw', $request->kod_cawangan)->first()->mysql;

$query_total_gadaian = Gadai::on($cawangan_connection);

$query_total_gadaian->when($request->filled('startDate') and $request->filled('endDate'), function ($q) use ($request) {
    return $q->where('t_gadai', '>=', $request->startDate)
        ->where('t_gadai', '<=', $request->endDate);
});

$total_gadaian = getTotalGadaian($query_total_gadaian);
$total_summary_gadaian_teller = getTotalSummaryGadaianGroupByTeller($query_total_gadaian);
$total_summary_gadaian = getTotalSummaryGadaian($query_total_gadaian);
$customer_info = getCustomerInfo($total_gadaian);
$marhun_gadaian = getMarhunGadaian($total_gadaian, $cawangan_connection);
$cawangan_detail = getCawanganDetail($cawangan_connection);

$total_gadaian = $total_gadaian->zip($customer_info, $marhun_gadaian)->map(function ($data) {

    [$gadai, $customer_info, $marhun_gadaian] = $data;

    return [
        'no_rujukan' => $gadai['norujukan'],
        'nama' => $customer_info['nama'],
        'alamat' => $customer_info['alamat1'],
        'no_kp' => $gadai['nokp'],
        'masa' => $gadai['masa'],
        'marhun' => $marhun_gadaian,
        'berat' => Helper::formatNumber($gadai['berat']),
        'nilai_marhun' => Helper::formatNumber($gadai['nilaimarhun']),
        'pembiayaan' => Helper::formatNumber($gadai['pinjaman']),
        'peratusan_margin_pinjaman' => $gadai['percentpinj'],
        'teller' => $gadai['teller'],
    ];

});

$total_gadaian = $total_gadaian
    ->groupBy('teller')
    ->zip($total_summary_gadaian_teller)
    ->map(function ($data) {
        [$gadaian, $summary] = $data;

        return [$gadaian, $summary];
    });

$data = [
    'query' => [
        'startDate' => Helper::formatDate($request->startDate),
        'endDate' => Helper::formatDate($request->endDate),
    ],
    'cawangan_detail' => $cawangan_detail,
    'gadaian' => $total_gadaian,
    'summary_gadaian' => $total_summary_gadaian,
];

return json_encode($data);

}
