<?php

namespace App\Http\Controllers\Reports;

use App\Http\Controllers\Controller;
use App\Cawangan;
use App\Gadai;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\Reports\GadaianService as ReportGadaianService;
use App\Helper;
use App\Tebus;
use Illuminate\Support\Carbon;

class SaringanGadaianController extends Controller
{

    public function getLaporanGadai(Request $request)
    {
        $startDate = $request->startDate ?? now()->startOfMonth()->toDateString();
        $endDate   = $request->endDate ?? now()->endOfMonth()->toDateString();

        $active_dbs = Helper::getActiveCawanganDbConnection();

        $cawangan = Cawangan::select('kodcaw', 'details_caw', 'mysql')
            ->whereIn('mysql', $active_dbs)
            ->get();

        $responses = [];

        foreach ($cawangan as $caw) {

            $db = $caw->mysql;

            $tgb = Tebus::on($db)
                ->join('gadai as g1', 'tebus.norujukan', '=', 'g1.norujukan')
                ->join('gadai as g2', function ($join) {
                    $join->on('g2.nokp', '=', 'g1.nokp')
                        ->on('g2.t_gadai', '=', 'tebus.t_tebus')
                        ->whereRaw('ABS(g2.berat - g1.berat) <= 0.02')
                        ->whereColumn('g2.norujukan', '!=', 'g1.norujukan');
                })
                ->whereBetween('tebus.t_tebus', [$startDate, $endDate])
                ->groupBy('tebus.norujukan')
                ->selectRaw("
                tebus.norujukan as norujukan_tebus,
                MAX(g2.norujukan) as norujukan_gadai_balik,
                MAX(g2.nokp) as nokp,
                MAX(g2.berat) as berat,
                MAX(g2.nilaimarhun) as nilaimarhun,
                MAX(g2.pinjaman) as pinjaman,
                MAX(g2.t_gadai) as t_gadai,
                MAX(g1.taglel) as taglel_lama
            ")
                ->get()
                ->map(function ($row) {
                    return [
                        'norujukan_tebus'       => $row->norujukan_tebus,
                        'norujukan_gadai_balik' => $row->norujukan_gadai_balik,
                        'nokp'                  => $row->nokp,
                        'berat'                 => (float) $row->berat,
                        'nilaimarhun'           => (float) $row->nilaimarhun,
                        'pinjaman'              => (float) $row->pinjaman,
                        'taglel_lama'           => $row->taglel_lama,
                        't_gadai'               => $row->t_gadai,
                        'jenis'                 => $row->taglel_lama == 1 ? 'TGB_LELONG' : 'TGB_BIASA',
                    ];
                })
                ->toArray();

            $tgb_norujukan = array_column($tgb, 'norujukan_gadai_balik');


            $gadai_biasa = DB::connection($db)
                ->table('gadai')
                ->whereBetween('t_gadai', [$startDate, $endDate])
                ->whereNotIn('norujukan', $tgb_norujukan)
                ->select([
                    DB::raw('NULL as norujukan_tebus'),
                    'norujukan as norujukan_gadai_balik',
                    'nokp',
                    'berat',
                    'nilaimarhun',
                    'pinjaman',
                    DB::raw('NULL as taglel_lama'),
                    't_gadai',
                ])
                ->get()
                ->map(function ($row) {
                    return [
                        'norujukan_tebus'       => null,
                        'norujukan_gadai_balik' => $row->norujukan_gadai_balik,
                        'nokp'                  => $row->nokp,
                        'berat'                 => (float) $row->berat,
                        'nilaimarhun'           => (float) $row->nilaimarhun,
                        'pinjaman'              => (float) $row->pinjaman,
                        'taglel_lama'           => null,
                        't_gadai'               => $row->t_gadai,
                        'jenis'                 => 'GADAI_BIASA',
                    ];
                })
                ->toArray();


            $details = collect($tgb)
                ->merge($gadai_biasa)
                ->unique('norujukan_gadai_balik')
                ->sortBy(['jenis', 't_gadai'])
                ->values()
                ->all();


            $responses[] = [
                'kodcaw'              => $caw->kodcaw,
                'details_caw'         => $caw->details_caw,
                'jumlah_surat'        => count($details),
                'total_tgb_lelong'    => collect($details)->where('jenis', 'TGB_LELONG')->count(),
                'total_tgb_biasa'     => collect($details)->where('jenis', 'TGB_BIASA')->count(),
                'total_gadai_biasa'   => collect($details)->where('jenis', 'GADAI_BIASA')->count(),
                'sum_berat'           => collect($details)->sum('berat'),
                'sum_nilai_marhun'    => collect($details)->sum('nilaimarhun'),
                'sum_pinjaman'        => collect($details)->sum('pinjaman'),
                'details'             => $details,
            ];
        }

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