<?php

namespace App\Http\Controllers;

use App\Gadai;
use App\Marhun;
use App\Cawangan;
use App\Transaction;
use App\TransaksiKeuntungan;
use App\TransactionOnline;
use App\batalGadai;
use App\TuntutBaki;
use App\AnsRugi;
use App\Lelong;
use App\WTD;
use App\HapusKira;
use App\Tebus;
use App\Vault;
use App\Tunai;
use App\Komuditi;
use App\KawalanStokLama;
use App\KawalanStok;
use App\KadarUpah;
use App\Moratorium;
use App\Audit;
use App\Customer;
use App\KomuditiPurchase;
use App\KomuditiTransaksi;
use App\Advansur;
use App\BlastWasap;
use App\HistoryEmasSandaran;
use App\InOutMar;
use App\Jobs\WhatsappPelangganSAGLAMA;
use App\Jobs\SMSPelangganSAGLAMA;
use Illuminate\Http\Request;
use App\CawanganDetail;
use App\BlastSMS;
use App\Jobs\WhatsappPelangganSAGLAMAbysag;
use App\Jobs\SMSPelangganSAGLAMAbysag;

use App\Services\OnePercentServices;

use Illuminate\Support\Facades\DB;

use Carbon\Carbon;

class StokAuditController extends Controller
{
    public function LaporanAuditKhasAktif($kodcaw,Request $request)
    {
        // dd($request->kodcaw);
        $daritempoh = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $request->kodcaw)->first();

        // Query asal gadai
        $audit = Gadai::on($cawangan['mysql'])
            ->where([
                ['tagpalsu', '=', 0],
                ['tempoh', '>=', $daritempoh],
                ['tempoh', '<=', $hinggatempoh],
                ['sttebus', '=', ''],
                ['taglel', '=', 0],
            ])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC')
            ->get();

        // Dapatkan semua norujukan awal
        $arraynorujukan = $audit->pluck('norujukan')->toArray();

        // Dapatkan tarikh terkini untuk setiap norujukan ikut trans_type T
        $tarikhTerkiniT = Transaction::on('mysql7')
            ->select('norujukan', DB::raw('MAX(created_at) as tarikh_max'))
            ->where('trans_type', 'T')
            ->whereIn('norujukan', $arraynorujukan)
            ->groupBy('norujukan')
            ->pluck('tarikh_max', 'norujukan')
            ->toArray();

        // Dapatkan tarikh terkini untuk setiap norujukan ikut trans_type A
        $tarikhTerkiniA = Transaction::on('mysql7')
            ->select('norujukan', DB::raw('MAX(created_at) as tarikh_max'))
            ->where('trans_type', 'A')
            ->whereIn('norujukan', $arraynorujukan)
            ->groupBy('norujukan')
            ->pluck('tarikh_max', 'norujukan')
            ->toArray();
    
        // Filter audit ikut tarikh masing-masing
        $rekodaudit = $audit->filter(function ($item) use ($tarikhTerkiniT, $tarikhTerkiniA) {
            $norujukan = $item->norujukan;

            $adaTebusTerkini = isset($tarikhTerkiniT[$norujukan]) &&
                Transaction::on('mysql7')
                ->where('norujukan', $norujukan)
                ->where('trans_type', 'T')
                ->whereDate('created_at', '>=', date('Y-m-d', strtotime($tarikhTerkiniT[$norujukan])))
                ->exists();

            $adaAnsuranTerkini = isset($tarikhTerkiniA[$norujukan]) &&
                Transaction::on('mysql7')
                ->where('norujukan', $norujukan)
                ->where('trans_type', 'A')
                ->whereDate('created_at', '>=', date('Y-m-d', strtotime($tarikhTerkiniA[$norujukan])))
                ->exists();

            return !$adaTebusTerkini && !$adaAnsuranTerkini;
        })->values();

        // Gunakan hanya norujukan yang dah ditapis
        $arraynorujukan = $rekodaudit->pluck('norujukan')->toArray();

        $gadainokp = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
        ->select('nokp')
        ->groupBy('nokp')
        ->get();

        // dd($gadainokp);

        foreach ($gadainokp as $index1 => $cal) {
            $customer = Customer::on('mysql7')->where('kpbaru', '=', $cal['nokp'])
            ->orWhere('kplama', '=', $cal['nokp'])
            ->first();

            $listsag = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
           ->where('nokp', 'like', '%' . $cal['nokp'] . '%')
            ->get();

            $checkingnokp = null;
            foreach ($listsag as $index2 => $cal2) {
                if ($cal2) {
                $checkingnokp = BlastWasap::on('mysql7')
                ->where('nokp', '=', $cal['nokp'])
                ->where('norujukan', '=', $cal2['norujukan'])
                ->where('kodcaw', '=', $kodcaw)
                ->first();
                }
            }

            $gadainokp[$index1]['info'] = $customer;
            $gadainokp[$index1]['listsag'] = $listsag;
            $gadainokp[$index1]['blasted'] = $checkingnokp;
        }
        // Total dikira berdasarkan hasil audit yang telah ditapis
        $totalrekod = $rekodaudit->sum('pinjaman');
        $totalberat = $rekodaudit->sum('berat');
        $totalnilaimarhun = $rekodaudit->sum('nilaimarhun');
        $totalpinjaman = $rekodaudit->sum('pinjaman');
        $totalbakipjm = $rekodaudit->sum('bakipjm');
        $totaltunggakan = $rekodaudit->sum('tunggakan');

        $arrayrekod = [
            'rekod' => $gadainokp,
            'total' => $totalrekod,
            'totalberat' => $totalberat,
            'totalnilaimarhun' => $totalnilaimarhun,
            'totalpinjaman' => $totalpinjaman,
            'totalbakipjm' => $totalbakipjm,
            'totaltunggakan' => $totaltunggakan,
        ];
        return response()->json($arrayrekod, 200);
    }


    public function blastwasap($kodcaw,Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();
        $daritempoh = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;
        $namapengguna = $request->namapengguna;
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $cawangan_detail = CawanganDetail::on($cawangan['mysql'])->first();
        $caw_name = $cawangan->details_caw;
        $nofoncaw = $cawangan_detail->notel;
        // dd($cawangan_detail->notel);

        $audit = Gadai::on($cawangan['mysql'])
            ->where([['tagpalsu','=',0],['tempoh','>=',$daritempoh],['tempoh','<=',$hinggatempoh],['sttebus','=',''],['taglel','=',0]])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC');
            // ->get();
        // dd($audit);
        $rekodaudit = $audit->get();
        $arraynorujukan = $audit->pluck('norujukan')->toArray();
        $keybynorujukan = $rekodaudit->keyBy('norujukan');
        
        $gadainokp = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
        ->select('nokp')
        ->groupBy('nokp')
        ->get();
        $gadai_all_groupby_nokp = $rekodaudit->groupBy('nokp');
        // dd($gadai_all_groupby_nokp);

        // dd($gadainokp);

        foreach($gadainokp as $index1=>$cal){
            // dd($cal->nokp);
            if($gadai_all_groupby_nokp[$cal->nokp]){
                $gadainokp[$index1]['gadai'] = $gadai_all_groupby_nokp[$cal->nokp];
            }
            // dd($gadainokp[$index1]['gadai'][$index1]['norujukan']);


            $customer =  Customer::on('mysql7')->where('kpbaru','=',$cal['nokp'])
            ->orWhere('kplama','=',$cal['nokp'])
            ->first();
            $nokp=$cal['nokp'];

            foreach($gadainokp[$index1]['gadai'] as $index1=>$cal3){

                $checkingnokp = BlastWasap::on('mysql7')
                ->where('nokp','=',$cal['nokp'])
                ->where('norujukan','=',$cal3->norujukan)
                ->where('kodcaw','=',$kodcaw)
                ->first();

                if(!$checkingnokp){

                    if($customer->telefon != 'null'){
                        $telefon=$customer->telefon;

                            //log auditrail
                            $audit = new Audit();
                            $audit->users = $namapengguna;
                            $audit->actions = 'Blast Whatsapp & SMS';
                            $audit->norujukan = $cal3->norujukan;
                            $audit->new_data = $customer->telefon;
                            $audit->old_data = $nokp;
                            $audit->kodcaw = $kodcaw;
                            $audit->created_at = $current;
                            $audit->updated_at = $current;
                            $audit->save();

                        dispatch(new WhatsappPelangganSAGLAMA($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal3->norujukan,$cal3->tempoh));
                        dispatch(new SMSPelangganSAGLAMA($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal3->norujukan,$cal3->tempoh));
                    }
                }
                else{
                    return response()->json('failed');
                }
            }
        }
        return response()->json('success');

    }

    public function blastwasapbysag($kodcaw,Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();
        $daritempoh = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;
        $namapengguna = $request->namapengguna;
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $cawangan_detail = CawanganDetail::on($cawangan['mysql'])->first();
        $caw_name = $cawangan->details_caw;
        $nofoncaw = $cawangan_detail->notel;

        $audit = Gadai::on($cawangan['mysql'])
            ->where([['tagpalsu','=',0],['tempoh','>=',$daritempoh],['tempoh','<=',$hinggatempoh],['sttebus','=',''],['taglel','=',0]])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC');

        $rekodaudit = $audit->get();
        $arraynorujukan = $audit->pluck('norujukan')->toArray();
        $keybynorujukan = $rekodaudit->keyBy('norujukan');
        
        $gadainokp = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
        // ->select('nokp')
        // ->groupBy('nokp')
        ->get();
        // dd($gadainokp);
        $gadai_all_groupby_nokp = $rekodaudit->groupBy('nokp');

        foreach($gadainokp as $index1=>$cal){
            // dd($cal->nokp);
            if($gadai_all_groupby_nokp[$cal->nokp]){
                $gadainokp[$index1]['gadai'] = $gadai_all_groupby_nokp[$cal->nokp];
            }
            // dd($gadainokp[$index1]['gadai'][$index1]['norujukan']);

            $customer =  Customer::on('mysql7')->where('kpbaru','=',$cal['nokp'])
            ->orWhere('kplama','=',$cal['nokp'])
            ->first();
            $nokp=$cal['nokp'];

            // foreach($gadainokp[$index1]['gadai'] as $index1=>$cal3){

                $checkingnokp = BlastWasap::on('mysql7')
                ->where('nokp','=',$cal['nokp'])
                ->where('norujukan','=',$cal->norujukan)
                ->where('kodcaw','=',$kodcaw)
                ->first();

                if(!$checkingnokp){

                    if($customer->telefon != 'null'){
                        $telefon=$customer->telefon;

                            //log auditrail
                            $audit = new Audit();
                            $audit->users = $namapengguna;
                            $audit->actions = 'Blast Whatsapp & SMS';
                            $audit->norujukan = $cal->norujukan;
                            $audit->new_data = $customer->telefon;
                            $audit->old_data = $nokp;
                            $audit->kodcaw = $kodcaw;
                            $audit->created_at = $current;
                            $audit->updated_at = $current;
                            $audit->save();
                        

                        dispatch(new WhatsappPelangganSAGLAMAbysag($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal->norujukan,$cal->tempoh,$cal->t_matang,$cal->t_matang1,$cal->lelong_tawarruq));
                        dispatch(new SMSPelangganSAGLAMAbysag($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal->norujukan,$cal->tempoh,$cal->t_matang,$cal->t_matang1,$cal->lelong_tawarruq));
                    }
                }
                else{
                    return response()->json('failed');
                }
            // }
        }
        return response()->json('success');

    }

    public function rekodblast($kodcaw,Request $request)
    {
       
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $rekodblast = BlastWasap::on('mysql7')
                ->where('kodcaw','=',$kodcaw);
        $arraynorujukan = $rekodblast->pluck('norujukan')->toArray();
        $rekodaudit = $rekodblast->orderBy('id', 'asc')->get();
        $keybynorujukan = $rekodaudit->keyBy('norujukan');

        $gadainokp = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
        ->select('nokp')
        ->groupBy('nokp')
        ->get();
        $gadai_all_groupby_nokp = $rekodaudit->groupBy('nokp');
        // dd($gadai_all_groupby_nokp);

        foreach($gadainokp as $index1=>$cal){

            if($gadai_all_groupby_nokp[$cal->nokp]){
                $gadainokp[$index1]['rekodblast'] = $gadai_all_groupby_nokp[$cal->nokp];
            }
            $customer =  Customer::on('mysql7')->where('kpbaru','=',$cal['nokp'])
            ->orWhere('kplama','=',$cal['nokp'])
            ->first();

            $listsag = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
            ->where('nokp', 'like', '%'.$cal['nokp'].'%')
            ->get();
            // dd($listsag);
             $gadainokp[$index1]['info'] = $customer;
             $gadainokp[$index1]['listsag'] = $listsag;
        }
           
       if($listsag ?? ''){
        $totalrekod = $listsag->sum('pinjaman');
        $totalberat = $listsag->sum('berat');
        $totalnilaimarhun = $listsag->sum('nilaimarhun');
        $totalpinjaman = $listsag->sum('pinjaman');
        $totalbakipjm = $listsag->sum('bakipjm');
        $totaltunggakan = $listsag->sum('tunggakan');
        }

        $arrayrekod = ['rekod' => $gadainokp ?? null,
         'total' => $totalrekod ?? null,
         'totalberat' => $totalberat ?? null,
         'totalnilaimarhun' =>  $totalnilaimarhun ?? null,
         'totalpinjaman'=>$totalpinjaman ?? null,
         'totalbakipjm'=>$totalbakipjm ?? null,
         'totaltunggakan'=>$totaltunggakan ?? null];
        return response()->json($arrayrekod,200);
    }

    public function rekodblastsms($kodcaw,Request $request)
    {
       
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $rekodblast = BlastSMS::on('mysql7')
                ->where('kodcaw','=',$kodcaw);
        $arraynorujukan = $rekodblast->pluck('norujukan')->toArray();
        $rekodaudit = $rekodblast->orderBy('id', 'asc')->get();
        $keybynorujukan = $rekodaudit->keyBy('norujukan');

        $gadainokp = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
        ->select('nokp')
        ->groupBy('nokp')
        ->get();
        $gadai_all_groupby_nokp = $rekodaudit->groupBy('nokp');
        // dd($gadai_all_groupby_nokp);

        foreach($gadainokp as $index1=>$cal){

            if($gadai_all_groupby_nokp[$cal->nokp]){
                $gadainokp[$index1]['rekodblast'] = $gadai_all_groupby_nokp[$cal->nokp];
            }
            $customer =  Customer::on('mysql7')->where('kpbaru','=',$cal['nokp'])
            ->orWhere('kplama','=',$cal['nokp'])
            ->first();

            $listsag = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
            ->where('nokp', 'like', '%'.$cal['nokp'].'%')
            ->get();
            // dd($listsag);
             $gadainokp[$index1]['info'] = $customer;
             $gadainokp[$index1]['listsag'] = $listsag;
        }
           
       if($listsag ?? ''){
        $totalrekod = $listsag->sum('pinjaman');
        $totalberat = $listsag->sum('berat');
        $totalnilaimarhun = $listsag->sum('nilaimarhun');
        $totalpinjaman = $listsag->sum('pinjaman');
        $totalbakipjm = $listsag->sum('bakipjm');
        $totaltunggakan = $listsag->sum('tunggakan');
        }

        $arrayrekod = ['rekod' => $gadainokp ?? null,
         'total' => $totalrekod ?? null,
         'totalberat' => $totalberat ?? null,
         'totalnilaimarhun' =>  $totalnilaimarhun ?? null,
         'totalpinjaman'=>$totalpinjaman ?? null,
         'totalbakipjm'=>$totalbakipjm ?? null,
         'totaltunggakan'=>$totaltunggakan ?? null];
        return response()->json($arrayrekod,200);
    }


    public function LaporanAuditKhasByNorujukan($kodcaw, Request $request)
    {
        $daritempoh   = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $request->kodcaw)->first();

        // Ambil semua rekod gadai asas
        $audit = Gadai::on($cawangan['mysql'])
            ->where([
                ['tagpalsu', '=', 0],
                ['tempoh', '>=', $daritempoh],
                ['tempoh', '<=', $hinggatempoh],
                ['sttebus', '=', ''],
                ['taglel', '=', 0],
            ])
            ->orderBy('norujukan', 'ASC')   // susun ikut norujukan
            ->get();

        $arraynorujukan = $audit->pluck('norujukan')->toArray();

        // Tarikh terkini ikut trans_type T
        $tarikhTerkiniT = Transaction::on('mysql7')
            ->select('norujukan', DB::raw('MAX(created_at) as tarikh_max'))
            ->where('trans_type', 'T')
            ->whereIn('norujukan', $arraynorujukan)
            ->groupBy('norujukan')
            ->pluck('tarikh_max', 'norujukan')
            ->toArray();

        // Tarikh terkini ikut trans_type A
        $tarikhTerkiniA = Transaction::on('mysql7')
            ->select('norujukan', DB::raw('MAX(created_at) as tarikh_max'))
            ->where('trans_type', 'A')
            ->whereIn('norujukan', $arraynorujukan)
            ->groupBy('norujukan')
            ->pluck('tarikh_max', 'norujukan')
            ->toArray();

        // Filter audit
        $rekodaudit = $audit->filter(function ($item) use ($tarikhTerkiniT, $tarikhTerkiniA) {
            if ($item->lelong_tawarruq == 0) {
                return true;
            }
            $norujukan = $item->norujukan;

            $adaTebusTerkini = isset($tarikhTerkiniT[$norujukan]) &&
                Transaction::on('mysql7')
                    ->where('norujukan', $norujukan)
                    ->where('trans_type', 'T')
                    ->whereDate('created_at', '>=', date('Y-m-d', strtotime($tarikhTerkiniT[$norujukan])))
                    ->exists();

            $adaAnsuranTerkini = isset($tarikhTerkiniA[$norujukan]) &&
                Transaction::on('mysql7')
                    ->where('norujukan', $norujukan)
                    ->where('trans_type', 'A')
                    ->whereDate('created_at', '>=', date('Y-m-d', strtotime($tarikhTerkiniA[$norujukan])))
                    ->exists();

            return !$adaTebusTerkini && !$adaAnsuranTerkini;
        })->values();

        // Attach customer info + blast untuk setiap norujukan
        foreach ($rekodaudit as $index => $rekod) {
            $customer = Customer::on('mysql7')
                ->where('kpbaru', '=', $rekod->nokp)
                ->orWhere('kplama', '=', $rekod->nokp)
                ->first();

            $rekodaudit[$index]['customer'] = $customer;

            $rekodaudit[$index]['blasted'] = BlastWasap::on('mysql7')
                ->where('nokp', $rekod->nokp)
                ->where('norujukan', $rekod->norujukan)
                ->where('kodcaw', $kodcaw)
                ->first();

            // 👉 Kira keuntungan (tunggakan sebenar) guna function
            $upah = $this->kiraupahUjrahOnePercent($kodcaw, $rekod->norujukan);
            $keuntungan = $upah['ujrah'] + $upah['onepercent'];

            // Save ke dalam rekod
            $rekodaudit[$index]['tunggakan'] = $this->floorTo5SenFrom2dp($keuntungan);
        }

        // Summary total
        $summary = [
            'totalrekod'      => $rekodaudit->count(),
            'totalberat'      => $rekodaudit->sum('berat'),
            'totalnilaimarhun'=> $rekodaudit->sum('nilaimarhun'),
            'totalpinjaman'   => $rekodaudit->sum('pinjaman'),
            'totalbakipjm'    => $rekodaudit->sum('bakipjm'),
            'totaltunggakan'  => $rekodaudit->sum('tunggakan'),
        ];

        return response()->json([
            'rekod'   => $rekodaudit,
            'summary' => $summary,
        ]);
    }

     public function kiraupahUjrahOnePercent($kodcaw,$norujukan){
        $onepercentservices = new OnePercentServices();

        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        if($gadai_data['tempoh'] >= 12.0){
            $tempoh = 12;
        }else{
            $tempoh = $gadai_data['tempoh'];
        }

        $bilang_bln = $tempoh - $gadai_data['tempohbayar'];
        $array_upah = $onepercentservices->kiraanKeuntunganSebenar($gadai_data['pinjaman'],$gadai_data['nilaimarhun'],$gadai_data['kadarupah'],$gadai_data['percentpinj']);
        $ujrah = $bilang_bln * $array_upah['ujrah'];
        $onepercent = $bilang_bln * $array_upah['onepercent'];
        $onepercent_semasa = $onepercent;
        $ujrah_semasa = $ujrah;

        return ['ujrah' => $ujrah_semasa, 'onepercent' => $onepercent_semasa];
    }

    // dalam Controller (private/protected)
    private function floorTo5SenFrom2dp($amount)
    {
        // pastikan numeric
        $amount = (float) $amount;

        // 1) Tukar ke sen dan buang sebarang pecahan sen (hanya baca 2 dp)
        // tambah epsilon kecil untuk elak isu floating point
        $cents = (int) floor($amount * 100 + 0.0000001);

        // 2) Floor ke gandaan 5 sen
        $cents5 = (int) (floor($cents / 5) * 5);

        // balik ke ringgit
        return $cents5 / 100;
    }



}
