<?php

namespace App\Services\Reports;

use App\Cawangan;
use App\CawanganDetail;
use App\Customer;
use App\Helper;
use App\Tebus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PenebusanService
{

    public $kod_cawangan;
    public $startDate;
    public $endDate;

    public function __construct($kod_cawangan, Request $request)
    {
        $this->kod_cawangan = $kod_cawangan;
        $this->startDate = $request->startDate;
        $this->endDate = $request->endDate;
    }

    public function getCawanganReport()
    {
        $cawangan_connection = Cawangan::where('kodcaw', $this->kod_cawangan)->first()->mysql;

        $query_total_penebusan = Tebus::on($cawangan_connection);

        $query_total_penebusan->join('gadai', 'tebus.norujukan', '=', 'gadai.norujukan');

        $query_total_penebusan->where('gadai.upah12', '!=', null);
        $query_total_penebusan->when(!empty($this->startDate) and !empty($this->endDate), function ($q) {
            return $q->where('t_tebus', '>=', $this->startDate)
                ->where('t_tebus', '<=', $this->endDate);
        });

        $total_penebusan = $this->getTotalPenebusan($query_total_penebusan);
        $total_summary_penebusan_teller = $this->getTotalSummaryPenebusanGroupByTeller($query_total_penebusan);
        $total_summary_penebusan = $this->getTotalSummaryPenebusan($query_total_penebusan);
        $customer_info = $this->getCustomerInfo($total_penebusan);
        $cawangan_detail = $this->getCawanganDetail($cawangan_connection);

        $total_penebusan = $total_penebusan->zip($customer_info)->map(function ($data) {

            [$tebus, $customer_info] = $data;

            return [
                'no_rujukan' => $tebus['norujukan'],
                'nama' => $customer_info['nama'],
                'no_kp' => $tebus['nokp'],
                'tarikh_gadai' => $tebus['t_gadai'],
                'jbg' => $tebus['jbg'],
                'nilai_pinjaman' => $tebus['nilai_pinjaman'],
                'baki_pinjaman' => $tebus['baki_pinjaman'],
                'kos_keuntungan' => $tebus['kos_keuntungan'],
                'kos_keuntungan_rebet' => $tebus['kos_keuntungan_rebet'],
                'bayaran_penebusan' => $tebus['bayaran_penebusan'],
                'nilai_marhun' => $tebus['nilai_marhun'],
                'jenis_tebus' => $tebus['jenis_tebus'],
                'teller' => $tebus['teller'],
            ];

        });

        $total_penebusan = $total_penebusan->groupBy('teller');

        $penebusan_tellers = $total_penebusan->keys();

        $total_penebusan = $total_penebusan
            ->zip($total_summary_penebusan_teller)
            ->map(function ($data) {

                [$penebusan, $summary] = $data;

                return [
                    'penebusan' => $penebusan,
                    'summary_penebusan_teller' => $summary,
                ];
            });

        $total_penebusan = $penebusan_tellers->combine($total_penebusan);

        $data = [
            'query' => [
                'startDate' => Helper::formatDate($this->startDate),
                'endDate' => Helper::formatDate($this->endDate),
            ],
            'cawangan_detail' => $cawangan_detail,
            'penebusan' => $total_penebusan,
            'summary_penebusan' => $total_summary_penebusan,
        ];

        return json_encode($data);

    }

    private 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[0];

    }

    private function getTotalSummaryPenebusan(Builder $query_total_penebusan)
    {

        $total_summary_penebusan = (clone $query_total_penebusan)
            ->select(
                DB::raw('sum(gadai.bakipjm) as nilai_pinjaman'),
                DB::raw('sum(tebus.pinjaman) as baki_pinjaman'),
                DB::raw('sum(tebus.bakiupah) as kos_keuntungan'),
                DB::raw('sum(tebus.bakipjm - gadai.bakipjm) as kos_keuntungan_rebet'),
                DB::raw('sum(gadai.bakipjm) + sum(tebus.bakipjm - gadai.bakipjm) as bayaran_penebusan'),
                DB::raw('sum(tebus.nilaimarhun) as nilai_marhun'),
            )
            ->get()
            ->toArray();

        return $total_summary_penebusan[0];
    }
    private function getTotalSummaryPenebusanGroupByTeller(Builder $query_total_penebusan)
    {

        $total_summary_penebusan_groupByTeller = (clone $query_total_penebusan)
            ->select(
                DB::raw('sum(gadai.bakipjm) as nilai_pinjaman'),
                DB::raw('sum(tebus.pinjaman) as baki_pinjaman'),
                DB::raw('sum(tebus.bakiupah) as kos_keuntungan'),
                DB::raw('sum(tebus.bakipjm - gadai.bakipjm) as kos_keuntungan_rebet'),
                DB::raw('sum(gadai.bakipjm) + sum(tebus.bakipjm - gadai.bakipjm) as bayaran_penebusan'),
                DB::raw('sum(tebus.nilaimarhun) as nilai_marhun'),
                'tebus.teller',
            )
            ->groupBy('tebus.teller')
            ->get();

        return $total_summary_penebusan_groupByTeller;
    }

    private function getTotalPenebusan(Builder $query_total_penebusan)
    {

        $total_penebusan = (clone $query_total_penebusan)
            ->select(
                'tebus.norujukan',
                'gadai.nokp',
                'gadai.t_gadai',
                'gadai.jbg',
                'gadai.bakipjm as nilai_pinjaman',
                'tebus.pinjaman as baki_pinjaman',
                'tebus.bakiupah as kos_keuntungan',
                DB::raw('(tebus.bakipjm - gadai.bakipjm) as kos_keuntungan_rebet'),
                DB::raw('gadai.bakipjm + (tebus.bakipjm - gadai.bakipjm) as bayaran_penebusan'),
                'tebus.nilaimarhun as nilai_marhun',
                'tebus.jenistebus as jenis_tebus',
                'tebus.teller',
            )
            ->orderBy('tebus.teller')
            ->orderBy('gadai.sirig')
            ->get();

        return $total_penebusan;
    }

    private function getCustomerInfo($total_penebusan)
    {

        $extract_nokp = $total_penebusan->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;
    }

}
