<?php

namespace App\Http\Controllers;

use App\Audit;
use App\Marhun;
use App\BankMaster;
use App\Customer;
use App\Gadai;
use App\Lelong;
use App\Cawangan;
use App\Poskod;
use App\Blacklist;
use App\AuditCustomer;
use Illuminate\Http\Request;
use App\TuntutBaki;
use Illuminate\Support\Facades\Auth;
use App\Anggota;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

use DB;

class CustomerController extends Controller
{

    public function showAllCustomers(Request $request)
    {
        $nama = $request->query('nama');
        $kodcaw = $request->query('kodcaw');

        $query = Customer::on('mysql7');

        if ($nama) {
            $query->where('nama', 'LIKE', '%' . $nama . '%');
        }

        if ($kodcaw) {
            $query->where('kodcaw', $kodcaw);
        }

        $customer = $query->get();

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


    public function getLatestCustomer($kodcaw){
        $customer = Customer::on('mysql7')->orderBy('tarikhdaftar','desc')->orderBy('nosiri','desc')->first();

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

    public function showAllCustomersByCawangan($kodcaw){
        $customer = Customer::on('mysql7')->get();

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

    public function showOneCustomerByIC($ic){
        $customer = Customer::on('mysql7')
        ->where('kplama','=',$ic)
        ->orWhere('kpbaru','=',$ic)
        ->first();

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

    public function showOneCustomerByICAdmin(Request $request){

        $customer = Customer::on('mysql7')
        ->where('kplama','=',$request->ic)
        ->orWhere('kpbaru','=',$request->ic)
        ->first();

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

    public function showOneCustomerByICMobile($ic){

        $cawangan_all = Cawangan::on('mysql7')->get();
        $customer_all = [];
        foreach($cawangan_all as $index=>$cawangan){
            $customer = Customer::on($cawangan['mysql'])
            ->where('kplama','=',$ic)
            ->orWhere('kpbaru','=',$ic)
            ->first();
            if($customer != null){
                array_push($customer_all,$customer);
            }
        }
        $customer_detail['nama'] = $customer_all[0]['nama'];
        $customer_detail['nokp'] = $customer_all[0]['kpbaru'];
        $customer_detail['nopelanggan'] = $customer_all[0]['nopelanggan'];
        $customer_detail['telefon'] = $customer_all[0]['telefon'];
        $customer_detail['telefon2'] = $customer_all[0]['telefon2'];
        $customer_detail['alamat'] = $customer_all[0]['alamat1'];
        $customer_detail['poskod'] = $customer_all[0]['poskod'];

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

    public function showOneCustomerGadai($ic,$status){
        if($status == 'belum_tebus'){
            $gadai_status = '';
        }elseif($status == 'sudah_tebus'){
            $gadai_status = 'T';
        }elseif($status == 'lelong'){
            $gadai_status = 'L';
        }

        $cawangan_all = Cawangan::on('mysql7')->get();
        $gadai_all = [];
        foreach($cawangan_all as $index=>$cawangan){
            if($status == 'belum_tebus' || $status == 'sudah_tebus'){
                $gadai = Gadai::on($cawangan['mysql'])
                    ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                    ->get();
                if(sizeof($gadai) != 0){
                    array_push($gadai_all,$gadai);
                }
            }elseif($status == 'lelong'){
                $gadai = Gadai::on($cawangan['mysql'])
                    ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                    ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                    ->get();
                if(sizeof($gadai) != 0){
                    array_push($gadai_all,$gadai);
                }
            }
        }

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

    public function show6BlnGadai($ic){
        $cawangan_all = Cawangan::on('mysql7')->get();
        $gadai_all=[];
        foreach($cawangan_all as $index=>$cawangan){
            $gadai = Gadai::on($cawangan['mysql'])
                    ->where([['sttebus','=',''],['nokp','=',$ic],['jbg','>=',6]])
                    ->get();
            if(sizeof($gadai) != 0){
                foreach($gadai as $index => $gadai_detail){
                    array_push($gadai_all,['norujukan'=>$gadai_detail['norujukan'],'hargajualan'=>$gadai_detail['hargajualan'],'bakihargajualan'=>$gadai_detail['bakihargajualan']]);
                }
            }
        }

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

    public function showOneCustomerGadaiByCawangan($ic,$status,$kodcaw){
        if($status == 'belum_tebus'){
            $gadai_status = '';
        }elseif($status == 'sudah_tebus'){
            $gadai_status = 'T';
        }elseif($status == 'lelong'){
            $gadai_status = 'L';
        }

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

	if($status == 'belum_tebus'){
            $gadai = Gadai::on($cawangan['mysql'])
            ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
            ->get();
        }elseif($status == 'sudah_tebus'){
            $gadai = Gadai::on($cawangan['mysql'])
                ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                ->orderBy('t_update', 'desc')
                ->take(100)->get();
        }elseif($status == 'lelong'){
            $gadai = Gadai::on($cawangan['mysql'])
                ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                ->get();
            if(!$gadai->isEmpty()){
            if($gadai[0]['trkhtuntut'] != NULL){
                    $tuntutbaki = TuntutBaki::on($cawangan['mysql'])
                    ->where('norujukan','=',$gadai[0]['norujukan'])
                    ->first();
                    $gadai[0]['datatuntut'] = $tuntutbaki;
                }
            }
        }
        return response()->json($gadai);
    }

    public function showOneCustomerGadaiMobile($ic,$status){
        if($status == 'belum_tebus'){
            $gadai_status = '';
        }elseif($status == 'sudah_tebus'){
            $gadai_status = 'T';
        }elseif($status == 'lelong'){
            $gadai_status = 'L';
        }

        $cawangan_all = Cawangan::on('mysql7')->get();
        $gadai_all = [];
        foreach($cawangan_all as $index=>$cawangan){
            if($status == 'belum_tebus' || $status == 'sudah_tebus'){
                $gadai = Gadai::on($cawangan['mysql'])
                    ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                    ->get();
                if(sizeof($gadai) != 0){
                    foreach($gadai as $index => $gadai_detail){
                        array_push($gadai_all,['norujukan'=>$gadai_detail['norujukan'],'hargajualan'=>$gadai_detail['hargajualan'],'bakihargajualan'=>$gadai_detail['bakihargajualan']]);
                    }
                }
            }elseif($status == 'lelong'){
                $gadai = Gadai::on($cawangan['mysql'])
                    ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                    ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                    ->get();
                if(sizeof($gadai) != 0){
                    foreach($gadai as $index => $gadai_detail){
                        array_push($gadai_all,['norujukan'=>$gadai_detail['norujukan'],'hargajualan'=>$gadai_detail['hargajualan'],'bakihargajualan'=>$gadai_detail['bakihargajualan']]);
                    }
                }
            }
        }

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

    public function marhun($cawangan, $norujukan)
    {
        $barang = array();
        $marhun = Marhun::on($cawangan['mysql'])
        ->where([['norujukan','=',$norujukan]])
        ->rightJoin('jemas','marhun.marhun', '=', 'jemas.marhun')
        ->get();

        if(!empty($marhun))
        {
            foreach($marhun as $mar)
            {

                array_push($barang, array(
                    'descpt' => $mar->descpt,
                    'berat' => $mar->berat,
                    'karat' => $mar->karat,
                    'n_marhuns' => $mar->n_marhuns,
                    ));
            }
        }

        return $barang;
    }

    public function gadaiTebusLelongByCawanganMobile($ic,$kodcaw)
    {

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $sttebus_ = [];
        $sttebus_T = [];
        $sttebus_L = [];
        $array_all = [];

        $gadai = Gadai::on($cawangan['mysql'])
        ->where([['nokp','=',$ic]])
        ->get();

        if(!empty($gadai))
        {

            foreach($gadai as $gd)
            {

                if($gd->sttebus == '' || empty($gd->sttebus))
                {

                    array_push($sttebus_, array(
                        'norujukan' => $gd->norujukan,
                        'pembiayaan' => number_format($gd->pinjaman,2),
                        'tarikhgadai' => $gd->t_gadai,
                        'hargajualan' => $gd->hargajualan,
                        'bakihargajualan' => $gd->bakihargajualan,
                        'barang' => $this->marhun($cawangan, $gd->norujukan) ?? ' tiada data',
                        ));

                }
                elseif($gd->sttebus == 'T')
                {
                    array_push($sttebus_T, array(
                        'norujukan' => $gd->norujukan,
                        'pembiayaan' => number_format($gd->pinjaman,2),
                        'tarikhgadai' => $gd->t_gadai,
                        'hargajualan' => $gd->hargajualan,
                        'bakihargajualan' => $gd->bakihargajualan,
                        'barang' => $this->marhun($cawangan, $gd->norujukan) ?? ' tiada data',
                        ));
                }
                elseif($gd->sttebus == 'L')
                {
                    array_push($sttebus_L, array(
                        'norujukan' => $gd->norujukan,
                        'pembiayaan' => number_format($gd->pinjaman,2),
                        'tarikhgadai' => $gd->t_gadai,
                        'hargajualan' => $gd->hargajualan,
                        'bakihargajualan' => $gd->bakihargajualan,
                        'barang' => $this->marhun($cawangan, $gd->norujukan) ?? ' tiada data',
                        ));

                }
            }
        }
        else
        {
            return response()->json('Data Not Found');
        }

        array_push($array_all, array(
            'gadai' => $sttebus_,
            'tebus' => $sttebus_T,
            'lelong' => $sttebus_L,
        ));

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

    public function getLaporanCustomers($kodcaw, $tarikh)
    {
        $gadai = Customer::on('mysql7')
                ->where([['tarikhdaftar','=',$tarikh],['kodcaw',$kodcaw]])
                ->orderBy('tarikhdaftar', 'desc')
                ->get();

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

    public function createCustomer($kodcaw,Request $request){
        $current = Carbon::now();
        $current = new Carbon();

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

        $customer = Customer::on('mysql7')->create([
            'kodcaw' => $request->kodcaw,
            'tarikhdaftar' => $current->toDateString(),
            'nopelanggan' => $request->nopelanggan,
            'kpbaru' => $request->nokpbaru,
            'kplama' => $request->nokplama,
            'nama' => $request->nama,
            't_lahir' => $request->t_lahir,
            'jantina' => $request->jantina,
            'alamat1' => $request->alamat,
            'poskod' => $request->poskod,
            'koddaerah' => $request->koddaerah,
            'kodnegeri' => $request->kodnegeri,
            'telefon' => $request->telefon,
            'bumiputra' => $request->bumiputra,
            'warganegara' => $request->warganegara,
            'bangsa' => $request->bangsa,
            'kodugama' => $request->kodugama,
            'kodbank' => $request->kodbank,
            'noakaun' => $request->noakaun,
            'teller' => $request->teller,
            'aktif' => 'A',
            'telefon2' => $request->telefon2,
            'nosiri'=>$request->nosiri,
            'nota'=>$request->nota,
            'kodkerja'=>$request->kodkerja,
            'nota_pekerjaan'=>$request->nota_pekerjaan,
            // 'nota_arcc'=>$request->nota_arcc,
            'tujuangadai'=>$request->tujuangadai
        ]);

        $audit = new Audit();
        $audit->users = $request->teller;
        $audit->actions = "Daftar Pelanggan Baru";
        $audit->new_data = json_encode($customer);
        $audit->kodcaw = $kodcaw;
        $audit->created_at = $current;
        $audit->updated_at = $current;
        $audit->save();

        return response()->json($customer, 201);
    }

    public function customerUpdate($nokp,Request $request){
        $poskod = Poskod::on('mysql7')->where('poskod','=',$request->poskod)->first();
        $customer_update = Customer::on('mysql7')
        ->where('kplama','=',$nokp)
        ->orWhere('kpbaru','=',$nokp)
        ->update(array(
            'alamat1' => $request->alamat,
            'alamat2' => '',
            'poskod' => $request->poskod,
            'koddaerah' => $poskod['koddaerah'],
            'kodnegeri' => $poskod['kodnegeri'],
            'kodkerja'=>$request->kodkerja,
            'nota_pekerjaan'=>$request->nota_pekerjaan,
            // 'nota_arcc'=>$request->nota_arcc,
            'telefon' => $request->telefon1,
            'telefon2' => $request->telefon2,
            'telefon2' => $request->telefon2,
        ));

        return response()->json($customer_update, 200);
    }

    public function assignAnggota($noic, Request $request)
{
    // Semak sama ada pelanggan wujud
    $customer = Customer::on('mysql7')
        ->where('kpbaru', $noic)
        ->orWhere('kplama', $noic)
        ->first();

    if (!$customer) {
        return response()->json([
            'success' => false,
            'message' => 'Pelanggan tidak dijumpai.'
        ], 404);
    }

    // Kemaskini tag_anggota
    $customer->tag_anggota = 1;
    $customer->save();

    return response()->json([
        'success' => true,
        'message' => 'Tag anggota berjaya dikemaskini.',
        'data' => $customer
    ], 200);
}
    }

    public function assignAnggota($noic, Request $request)
{
    // Semak sama ada pelanggan wujud
    $customer = Customer::on('mysql7')
        ->where('kpbaru', $noic)
        ->orWhere('kplama', $noic)
        ->first();

    if (!$customer) {
        return response()->json([
            'success' => false,
            'message' => 'Pelanggan tidak dijumpai.'
        ], 404);
    }

    // Kemaskini tag_anggota
    $customer->tag_anggota = 1;
    $customer->save();

    return response()->json([
        'success' => true,
        'message' => 'Tag anggota berjaya dikemaskini.',
        'data' => $customer
    ], 200);
}

    public function customerUpdateKaunter($nokp,$kodcaw, Request $request){
        $current = Carbon::now();

        DB::connection('mysql7')->beginTransaction();

        try{
            $poskod = Poskod::on('mysql7')->where('poskod','=',$request->poskod)->first();

            $customer_info = DB::connection('mysql7')->table('customer')
            ->select('kodcaw','kodkerja','nota_pekerjaan','tarikhdaftar','nopelanggan','kpbaru','kplama','nama','t_lahir','jantina','alamat1','poskod','telefon','telefon2')
            ->where('kplama','=',$nokp)
            ->orWhere('kpbaru','=',$nokp)
            ->get()->toArray();


            $old_data = json_encode($customer_info);

            $customer_update = Customer::on('mysql7')
            ->where('kplama','=',$nokp)
            ->orWhere('kpbaru','=',$nokp)
            ->update(array(
                'telefon' => $request->telefon1,
                'telefon2' => $request->telefon2,
                'kodbank' => $request->kodbank,
                'kodkerja' => $request->kodkerja,
                // 'nota_pekerjaan' => $request->nota_pekerjaan,
                'nota_pekerjaan' => $request->kodkerja === '6' ? $request->nota_pekerjaan : null,
                // 'nota_arcc' => $request->nota_arcc,
                'noakaun' => $request->noakaun,
                'nota' => $request->nota,
                'alamat1' => $request->alamat,
                'poskod' => $request->poskod,
                'koddaerah' => $poskod['koddaerah'],
                'kodnegeri' => $poskod['kodnegeri']
            ));

            if($customer_update)
            {
                $customer_info_new = DB::connection('mysql7')->table('customer')
                ->select('kodcaw','kodkerja','nota_pekerjaan','tarikhdaftar','nopelanggan','kpbaru','kplama','nama','t_lahir','jantina','alamat1','poskod','telefon','telefon2')
                ->where('kplama','=',$nokp)
                ->orWhere('kpbaru','=',$nokp)
                ->get()->toArray();

                $new_data = json_encode($customer_info_new);

                $audit_customer = DB::connection('mysql7')
                ->table('audit_customer')
                ->insert([
                    'username' => $request->namateller,
                    'old_data' => $old_data,
                    'new_data' => $new_data,
                    'kodcaw' => $customer_info[0]->kodcaw,
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString(),
                    'customer_name' => $customer_info[0]->nama,
                    'customer_nokp' => $nokp,
                ]);
            }

            $audit = new Audit();
            $audit->users = $request->namateller;
            $audit->actions = "Kemaskini Pelanggan";
            $audit->new_data = json_encode($customer_info_new);
            $audit->kodcaw = $kodcaw;
            $audit->created_at = $current;
            $audit->updated_at = $current;
            $audit->save();

            DB::connection('mysql7')->commit();

            return response()->json($customer_update, 200);

        }catch (\Exception $e) {
            DB::connection('mysql7')->rollback();
            return response()->json($e->getMessage(),400);

        }
    }

    public function customerUpdateKhazanah($nokp,Request $request){

        DB::connection('mysql7')->beginTransaction();

        try{
            $poskod = DB::connection('mysql7')->table('poskod')->where('poskod','=',$request->poskod)->first();

            $customer_info = DB::connection('mysql7')->table('customer')
            ->select('kodcaw','tarikhdaftar','nopelanggan','kpbaru','kplama','nama','t_lahir','jantina','alamat1','poskod','telefon','telefon2')
            ->where('kplama','=',$nokp)
            ->orWhere('kpbaru','=',$nokp)
            ->get()->toArray();

            $old_data = json_encode($customer_info);

            $customer_update = DB::connection('mysql7')
            ->table('customer')
            ->where('kplama','=',$nokp)
            ->orWhere('kpbaru','=',$nokp)
            ->update(array(
                'telefon' => $request->telefon1,
                'telefon2' => $request->telefon2,
                'kodbank' => $request->kodbank,
                'kodkerja' => $request->kodkerja,
                'nota_pekerjaan' => $request->nota_pekerjaan,
                // 'nota_arcc' => $request->nota_arcc,
                'noakaun' => $request->noakaun,
                'nota' => $request->nota,
                'nama' => $request->nama,
                'alamat1' => $request->alamat,
                'poskod' => $request->poskod,
                'koddaerah' => $poskod->koddaerah,
                'kodnegeri' => $poskod->kodnegeri
            ));


            if($customer_update)
            {
                $customer_info_new = DB::connection('mysql7')->table('customer')
                ->select('kodcaw','tarikhdaftar','nopelanggan','kpbaru','kplama','nama','t_lahir','jantina','alamat1','poskod','telefon','telefon2')
                ->where('kplama','=',$nokp)
                ->orWhere('kpbaru','=',$nokp)
                ->get()->toArray();

                $new_data = json_encode($customer_info_new);

                $audit_customer = DB::connection('mysql7')
                ->table('audit_customer')
                ->insert([
                    'username' => $request->namakhazanah,
                    'old_data' => $old_data,
                    'new_data' => $new_data,
                    'kodcaw' => $request->kodcaw,
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString(),
                    'customer_name' => $request->nama,
                    'customer_nokp' => $nokp,
                ]);
            }


            DB::connection('mysql7')->commit();

            return response()->json($customer_update, 200);

        }catch (\Exception $e) {
            DB::connection('mysql7')->rollback();
            return response()->json($e->getMessage(),400);

        }

    }

    public function customerUpdateAdmin(Request $request){
        $poskod = Poskod::on('mysql7')->where('poskod','=',$request->poskod)->first();

        if($request->ic_asal != $request->icno){

            $existing_customer = Customer::on('mysql7')
            ->where('kplama','=',$request->icno)
            ->orWhere('kpbaru','=',$request->icno)
            ->get();

            if($existing_customer->isEmpty()){
                $cawangan_all = Cawangan::on('mysql7')->get();
                foreach($cawangan_all as $index=> $cawangan){
                    $gadai = Gadai::on($cawangan['mysql'])->where('nokp',$request->ic_asal)->update([
                        'nokp'=>$request->icno
                    ]);
                }

                $data_asal = $customer_update = Customer::on('mysql7')
                ->where('kplama','=',$request->ic_asal)
                ->orWhere('kpbaru','=',$request->ic_asal)
                ->first();

                if($data_asal['kpbaru'] != null){
                    $customer_update = Customer::on('mysql7')
                    ->where('kplama','=',$request->ic_asal)
                    ->orWhere('kpbaru','=',$request->ic_asal)
                    ->update(array(
                        'kpbaru' => $request->icno,
                        'telefon' => $request->telefon1,
                        'telefon2' => $request->telefon2,
                        'kodbank' => $request->kodbank,
                        'noakaun' => $request->noakaun,
                        'nota' => $request->nota,
                        'nama' => $request->nama,
                        'alamat1' => $request->alamat,
                        'poskod' => $request->poskod,
                        'koddaerah' => $poskod['koddaerah'],
                        'kodnegeri' => $poskod['kodnegeri']
                    ));
                }else{
                    $customer_update = Customer::on('mysql7')
                    ->where('kplama','=',$request->ic_asal)
                    ->orWhere('kpbaru','=',$request->ic_asal)
                    ->update(array(
                        'kplama' => $request->icno,
                        'telefon' => $request->telefon1,
                        'telefon2' => $request->telefon2,
                        'kodbank' => $request->kodbank,
                        'noakaun' => $request->noakaun,
                        'nota' => $request->nota,
                        'nama' => $request->nama,
                        'alamat1' => $request->alamat,
                        'poskod' => $request->poskod,
                        'koddaerah' => $poskod['koddaerah'],
                        'kodnegeri' => $poskod['kodnegeri']
                    ));
                }
            }else{
                return response()->json('existing');
            }
        }else if($request->ic_asal == $request->icno){
            $customer_update = Customer::on('mysql7')
            ->where('kplama','=',$request->icno)
            ->orWhere('kpbaru','=',$request->icno)
            ->update(array(
                'telefon' => $request->telefon1,
                'telefon2' => $request->telefon2,
                'kodbank' => $request->kodbank,
                'noakaun' => $request->noakaun,
                'nota' => $request->nota,
                'nama' => $request->nama,
                'alamat1' => $request->alamat,
                'poskod' => $request->poskod,
                'koddaerah' => $poskod['koddaerah'],
                'kodnegeri' => $poskod['kodnegeri']
            ));
        }

        return response()->json($customer_update, 200);
    }

    public function listNorujukanMobile($nokp){
        $cawangan_all = Cawangan::on('mysql7')->get();
        $array_norujukan = [];
        foreach($cawangan_all as $index=>$cawangan){
            $gadai = Gadai::on($cawangan['mysql'])->where([['nokp','=',$nokp],['sttebus','=','']])->get();
            if(sizeof($gadai) != 0){
                foreach($gadai as $index=>$gadai_detail){
                    array_push($array_norujukan,['norujukan'=>$gadai_detail['norujukan'],'kodcaw'=>$gadai_detail['kodcaw']]);
                }
            }
        }

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


    public function countNorujukanMobile($nokp){
        $cawangan_all = Cawangan::on('mysql7')->get();
        $bilangan_sag = 0;
        foreach($cawangan_all as $index=>$cawangan){
            $gadai = Gadai::on($cawangan['mysql'])->where([['nokp','=',$nokp],['sttebus','=','']])->count('norujukan');
            $bilangan_sag += $gadai;
        }

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

    public function getGadaiDetailMobile(Request $request)
    {
        $array_norujukan = $request->norujukan;
        $array_kodcaw = $request->kodcaw;
        $array_gadai = [];
        $gadai_payment = [];

        foreach($array_norujukan as $index=>$norujukan)
        {
            array_push($array_gadai,['norujukan'=>$norujukan,'kodcaw'=>$array_kodcaw[$index]]);
        }

        foreach($array_gadai as $index=>$gadai)
        {
            $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$gadai['kodcaw'])->first();
            $gadai_detail = Gadai::on($cawangan['mysql'])->where('norujukan','=',$gadai['norujukan'])->first();

            $keuntungan_semasa = $gadai_detail['jbg'] * ($gadai_detail['pinjaman'] * ($gadai_detail['kadarupah']/100));
            $keuntungan_semasa_format = substr(number_format($keuntungan_semasa,2),0,-1) . '0';
            $nilai_marhun = $gadai_detail['nilaimarhun'];
            $harga_jual = $gadai_detail['pinjaman'] + $keuntungan_semasa_format;
            $baki_pinjaman = $nilai_marhun * 0.1;


            if ($baki_pinjaman < 50)
            {
                $max_pembayaran = $gadai_detail['pinjaman'] - 50.00;
            }
            else
            {
                $max_pembayaran = $gadai_detail['pinjaman'] - ($nilai_marhun * 0.1);
            }

            array_push($gadai_payment,['norujukan'=>$gadai['norujukan'],'cawangan'=>$cawangan['details_caw'],'pembiayaan'=>number_format($gadai_detail['pinjaman'],2),'pembayaran_keuntungan'=>$keuntungan_semasa_format,'bayaran_max'=>number_format($max_pembayaran,2), 'harga_jual'=>number_format($harga_jual,2),'nilai_marhun'=>number_format($nilai_marhun,2)]);
        }
        return response()->json($gadai_payment);
    }


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

        Customer::on('mysql7')->where('kplama','=',$nokp)->orWhere('kpbaru','=',$nokp)->delete();

        return response('Deleted Successfully', 200);
    }

    public function akaunBankMobile($nokp)
    {
        $customer_detail = [];
        $cawangan_all = Cawangan::on('mysql7')->get();

        foreach($cawangan_all as $cawangan)
        {
           $customer = Customer::on($cawangan['mysql'])
            ->where('kplama','=',$nokp)
            ->orWhere('kpbaru','=',$nokp)
            ->rightJoin(config('tennant_database.master_db') . '.bank', 'bank.id', '=', 'customer.kodbank')
            ->first();

            if(!empty($customer))
            {
                $customer_detail['noakaun'] = $customer['noakaun'];
                $customer_detail['namabank'] = $customer['name'];
                $customer_detail['kodbank'] = $customer['id'];
                return response()->json($customer_detail);
            }
            else
            {
                return $customer_detail;
            }
        }
    }

    public function bankListMobile()
    {
        $bank_array = [];
        $cawangan_all = Cawangan::on('mysql7')->get();
        foreach($cawangan_all as $cawangan)
        {
            $bank = BankMaster::get();
                if(!empty($bank))
                {
                    //loop each array
                    foreach($bank as $banklist)
                    {
                        array_push($bank_array, array(
                            'kodbank' => $banklist->id,
                            'namabank' => $banklist->name,
                        ));
                    }
                    return response()->json($bank_array);
                }
                else
                {
                    return response()->json('Data Not Found');
                }
        }
    }

    public function insertAkaunBankMobile(Request $request)
    {
        $customer = Customer::on('mysql7')
        ->where('kplama','=',$request->nokp)
        ->orWhere('kpbaru','=',$request->nokp)
        ->first();

        if(!empty($customer))
        {
            $customer->kodbank = $request->kodbank;
            $customer->noakaun = $request->noakaun;
            $customer->save();
        }

        return response()->json($customer, 200);
    }

    public function jumlahPembiayaanMobile($nokp)
    {
        $cawangan_all = Cawangan::on('mysql7')->get();
        $jumlahPembiayaan = 0;
        foreach($cawangan_all as $index=>$cawangan){
            $gadai = Gadai::on($cawangan['mysql'])->where([['nokp','=',$nokp],['sttebus','=','']])->sum('pinjaman');
            $jumlahPembiayaan += $gadai;
        }
        return response()->json(number_format($jumlahPembiayaan,2));
    }

    public function jumlahBakiLelongMobile($nokp)
    {
        $cawangan_all = Cawangan::on('mysql7')->get();
        $jumlahBakiLelong = 0;
        foreach($cawangan_all as $index=>$cawangan)
        {
            $bakilelong = Gadai::on($cawangan['mysql'])
                ->where('nokp','=',$nokp)
                ->where('sttebus','=','L')
                ->where('baki', 'not like', '-%')
                ->where('tagtbaki','=','1')
                ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                ->sum('baki');
            $jumlahBakiLelong += $bakilelong;
        }
        return response()->json(number_format($jumlahBakiLelong,2));
    }

    public function blacklistCustomer(Request $request){

        $blacklist = Blacklist::where('nokp',$request->nokp)->first();

        
        // $audit = new Audit();
        // $audit->users = $request->namateller;
        // $audit->actions = "Senarai Hitam Pelanggan";
        // $audit->new_data = json_encode($blacklist);
        // $audit->kodcaw = $kodcaw;
        // $audit->created_at = $current;
        // $audit->updated_at = $current;
        // $audit->save();

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

    public function anggotaKoperasi(Request $request){

        $anggota = Anggota::where('noic',$request->noic)->first();

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


    public function anggotaKoperasi(Request $request){

        $anggota = Anggota::where('noic',$request->noic)->first();

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


    public function showCustomerByEachCawangan($ic)
    {
        $cawangan_all = Cawangan::on('mysql7')->get();
        $custcawangan = array();

        foreach($cawangan_all as $index=>$cawangan)
        {
            $customer = Gadai::on($cawangan['mysql'])
                ->select('kodcaw')
                ->where('nokp', '=', $ic)
                ->first();

            if($customer)
                array_push($custcawangan,['kodcaw' => $customer['kodcaw'], 'namacawangan' => $cawangan['details_caw']]);
        }

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

    public function getTotalNewCustomerToday(){
        $current = Carbon::now();
        $current = new Carbon();
        $harini = $current->toDateString();
        $lastweek = $current->subWeek()->toDateString();

        $newcustomertoday = Customer::on('mysql7')->where('tarikhdaftar',$harini)->count();
        $newcustomerlastweek = Customer::on('mysql7')->where('tarikhdaftar',$lastweek)->count();

        $diffCustomerPercent = 0;
        if($newcustomerlastweek != 0){
            $diffCustomerPercent = (($newcustomertoday - $newcustomerlastweek)/$newcustomerlastweek)*100;
        }
        $dataCustomer = [];
        array_push($dataCustomer,['newCustomerToday'=>$newcustomertoday,'percentDiff'=>$diffCustomerPercent]);

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


    public function AdminsearchCustomerByName(Request $request)
    {
        $nama = strtoupper($request->nama);

        if(empty($nama))
        {
            $customer = [];
        }else{
            $customer = Customer::on('mysql7')
            ->where('nama','like',$nama.'%')
            ->orWhere('nama','like','%'.$nama)
            ->orWhere('nama','like','%'.$nama.'%')
            ->take(3)
            ->get();
        }

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

    public function AdminsearchCustomerByIC(Request $request)
    {
        if(isset($request->kodcaw))
        {
            $customer = Customer::on('mysql7')
            ->where([['kplama','like',$request->ic.'%'],['kodcaw','=',$request->kodcaw]])
            ->orWhere([['kpbaru','like',$request->ic.'%'],['kodcaw','=',$request->kodcaw]])
            ->take(3)
            ->get();
        }else{
            $customer = Customer::on('mysql7')
            ->where('kplama','like',$request->ic.'%')
            ->orWhere('kpbaru','like',$request->ic.'%')
            ->take(3)
            ->get();
        }


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

public function AdminsearchCustomerBySAG(Request $request) 
{
    // Ambil kodcaw dari user login
    $kodcaw = $request->kodcaw;
    // $norujukan = $request->input('norujukan');

    // Cari connection untuk cawangan
    $cawangan = Cawangan::on('mysql7')->where('kodcaw', $kodcaw)->first();
    if (!$cawangan) {
        return response()->json([], 404);
    }

    $gadai = optional(Gadai::on($cawangan['mysql'])->where('norujukan',$request->norujukan)->first())->toArray() ?? [];

    if(!empty($gadai)){
        $customer = optional(Customer::on('mysql7')->where(function ($query) use ($gadai) {
            $query->where('kpbaru',$gadai['nokp'])
            ->orWhere('kplama',$gadai['nokp']);
        })->first())->toArray() ?? [];    
    }else{
        return response()->json(['success' => false,'message' => 'norujukan tidak dijumpainya'], 404);
    }

    // cara fifi ajar
    $result = [[
        'id' => $customer['id'],
        'kodcaw' => $gadai['kodcaw'],
        'norujukan' => $gadai['norujukan'],
        'teller' => $gadai['teller'],
        'nota' => $customer['nota'],
        'pinjaman' => $gadai['pinjaman'],
        'nilaimarhun' => $gadai['nilaimarhun'],
        'jbg' => $gadai['jbg'],
        'tunggakan' => $gadai['tunggakan'],
        'tunggakanonepercent' => $gadai['tunggakanonepercent'],
        'tunggakanujrah' => $gadai['tunggakanujrah'],
        'nama' => $customer['nama'],
        'kplama' => $customer['kplama'],
        'kpbaru' => $customer['kpbaru'],
    ]];

    // saya buat sendiri
    // Join customer + gadai ikut nokp
    // $result = DB::connection($cawangan['mysql'])
    //     ->table('gadai')
    //     ->join('online_arrahn.customer as c', function($join) {
    //         $join->on('gadai.nokp', '=', 'c.kpbaru')
    //              ->orOn('gadai.nokp', '=', 'c.kplama');
    //     })
    //     ->where('norujukan', $request->norujukan)
    //     ->select(
    //         'id',
    //         'gadai.kodcaw','gadai.norujukan','gadai.teller',
    //         'c.nota','gadai.pinjaman','gadai.nilaimarhun','gadai.jbg',
    //         'gadai.tunggakan','gadai.tunggakanonepercent','gadai.tunggakanujrah',
    //         'c.nama','c.kpbaru','c.kplama'
    //     )
    //     ->take(5)
    //     ->get();

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

    public function changepassword(Request $request, $kodcaw, $id) {

        $current = Carbon::now();
        // log::info ($request->name);
        $audit = new Audit();
        $audit->users = $request->nama;
        $audit->actions = "Tukar Kata Laluan";
        // $audit->new_data = json_encode($request->new_password);
        $audit->kodcaw = $kodcaw;
        $audit->created_at =  $current;
        $audit->updated_at =  $current;
        $audit->save();
    }

    public function TukarCawangan(Request $request, $kodcaw)
    {

    $current = Carbon::now();
    $current = new Carbon();

    // Log::info('dalam tukar taraf');
    $audit = new Audit();
    $audit->users = $request->namaoperasi;
    $audit->actions = "Tukar Cawangan";
    $audit->old_data = json_encode($request->old_data);
    $audit->new_data = json_encode($request->new_data);
    $audit->kodcaw = $kodcaw;
    $audit->created_at = $current;
    $audit->updated_at = $current;
    $audit->save();

    return json_encode(['status'=> 'success']);

    }

    public function kakitangan(Request $request, $kodcaw)
    {
    $current = Carbon::now();

    // Log::info('pegesahan kakitangan');
    $audit = new Audit();
    $audit->users = $request->namaoperasi;
    $audit->actions = "pengesahan kakitangan";
    $audit->old_data = json_encode($request->old_data);
    $audit->new_data = json_encode($request->new_data);
    $audit->kodcaw = $kodcaw;
    $audit->created_at = $current;
    $audit->updated_at = $current;
    $audit->save();

    return json_encode(['status'=> 'success']);

    }
    
    public function TukarTaraf(Request $request, $kodcaw)
    {

    // return json_encode(['test'=> 'taraf']);
    //setiap request perlu htr something
    $current = Carbon::now();
    $current = new Carbon();


    // Log::info('dalam tukar taraf');

    $audit = new Audit();
    $audit->users = $request->namaoperasi;
    $audit->actions = "Tukar Taraf";
    $audit->old_data = json_encode($request->old_data);
    $audit->new_data = json_encode($request->new_data);
    $audit->kodcaw = $kodcaw;
    $audit->created_at = $current;
    $audit->updated_at = $current;
    $audit->save();

    return json_encode(['status'=> 'success']);

    }

    public function searchByName(Request $request)
    {
        $nama = $request->query('nama');
        $kodcaw = $request->query('kodcaw');

        $query = Customer::query();
        
        if ($kodcaw) {
            $query->where('kodcaw', $kodcaw);
        }

        if ($nama) {
            $query->where('nama', 'like', '%' . $nama . '%');
        }

        $results = $query->get();

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

    public function updateTagPdpa(Request $request)
    {
        $tarikh_cetak_pdpa = Carbon::now()->toDateString();

        $no_ic = $request->input('no_ic');

        $customer = Customer::where('kplama', $no_ic)
            ->orWhere('kpbaru', $no_ic)
            ->first();

        if (!$customer) {
            return response()->json(['error' => 'Customer not found.'], 404);
        }

        $customer->tag_pdpa = $request->input('tag_pdpa');
        $customer->tarikh_cetak_pdpa = $tarikh_cetak_pdpa;
        $customer->save();

        return response()->json(['message' => 'Customer PDPA updated successfully.'], 200);
    }

//     public function createNotaArcc($kodcaw, Request $request)
// {
//     $current = Carbon::now();

//     $customer = Customer::on('mysql7')->create([
//         'kodcaw' => $kodcaw,
//         'tarikhdaftar' => $current->toDateString(),
//         'nota_arcc' => $request->nota_arcc,
//         'teller' => $request->teller,
//         'aktif' => 'A'
//     ]);

//     return response()->json($customer, 201);
// }


}
