<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Style\PaperSize;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use App\Models\Syarikat;
use App\Models\LesenPenjaja;
use App\Models\BilPelbagai;
use App\Models\BilPelbagaiItem;
use App\Models\EpbtBpBil;
use App\Models\EpbtEcasResit;
use App\Models\BorangUlasanIk;
use App\Models\MesyuaratPelesenan;
use App\Models\Kawasan;
use App\Models\EpbtPelanggan;
use App\Models\EpbtElsnAkaun;

class PtPenjajaController extends Controller
{
    //

    public function simpanWangProses(Request $request)
    {
        $mohon = LesenPenjaja::find($request->permohonan_id);
        $mohon->status_progress = 'menunggu bayaran proses';
        $mohon->save();

        $bil_p = BilPelbagai::firstOrCreate(
            ['no_akaun_bilpelbagai' => $request->no_bil_pelbagai, 'lesen_penjaja_id' => $request->permohonan_id],
            ['no_akaun_bilpelbagai' => $request->no_bil_pelbagai, 'lesen_penjaja_id' => $request->permohonan_id, 
                'cara_jana' => 'epbt', 'status_mylesen'=>'1', 'jenis_bil' => 'wang proses']
        );

        try {
            DB::connection('second_mysql')->getPdo();

            if($bil_p->wasRecentlyCreated){
                $epbtbil = EpbtBpBil::where('noakaun', $request->no_bil_pelbagai)->first();

                if($epbtbil){
                    $bil_p->status_mylesen_error = ''; 
                    $bil_p->ref_no = $epbtbil->norujukan; 
                    $bil_p->description = $epbtbil->keterangan; 
                    $bil_p->pay_status = $epbtbil->statusbyr; 
                    $bil_p->jabatan = $epbtbil->dept_code; 
                    $bil_p->ent_opr = $epbtbil->ent_opr; 
                    $bil_p->no_bilpelbagai = $epbtbil->nobil; 
                    $bil_p->jenis_bil = 'wang proses'; 
                    $bil_p->save();

                    foreach($epbtbil->bil_items as $epbtbil_item){
                        $bilitem = BilPelbagaiItem::create([
                            'bil_pelbagai_id' => $bil_p->id,
                            'itemno' => $epbtbil_item->noitem, 
                            'itemdesc' => $epbtbil_item->keterangan, 
                            'itemprice' => $epbtbil_item->amaun, 
                            'gst_type' => $epbtbil_item->jenis_gst, 
                            'gst_code' => $epbtbil_item->kod_gst, 
                            'cr_code' => $epbtbil_item->kodcr, 
                            'dr_code' => $epbtbil_item->koddr, 
                            'cost_center' => $epbtbil_item->pusatkos, 
                            'exp_date' => $epbtbil_item->tamat_tempoh
                        ]);                   
                    }

                }

            }

            $bp_bayar = EpbtEcasResit::whereHas('resitItems', function($query) use ($request){
                                                    $query->where('noakaun', $request->no_bil_pelbagai);
                                        })->select('noresit', 'tarikh','amaun')
                                        ->orderBy('tarikh')
                                        ->first();
            if(!is_null($bp_bayar)){  //cek no resit daripada epbt..klu ada, kita simpan rekod    
                $bil_p->dt_bayar = $bp_bayar->tarikh; 
                $bil_p->no_resit = $bp_bayar->noresit;
                $bil_p->amaun_bayar = $bp_bayar->amaun;       

                $bil_p->save();
                
                $mohon->status_progress = 'semakan bayaran proses';  
                $mohon->save();  
            }    
        } catch (\Exception $e) {
            return back()->with('error', 'Sambungan ke pangkalan data gagal. Sila cuba sebentar lagi.');
        }
                   

        return redirect(route('admin.papar-wangproses', ['id'=>$request->permohonan_id]))->with('success', 'No Bil Pelbagai '.$request->no_bil_pelbagai.' telah ditambah');

    }

    public function simpanNoFail(Request $request){

        $mohon = LesenPenjaja::find($request->permohonan_id);

        $mohon->no_akaun_lesen = $request->no_akaun_lesen;
        if(is_null($mohon->penempatan_id)){
            $mohon->kawasan_id = $request->kawasan;

            if($request->taman != ''){
                $mohon->taman_id = $request->taman;
            }

            if($request->jalan != ''){
                $mohon->jalan_id = $request->jalan;
            }
        }
        else{
            $mohon->no_petak = $request->no_petak;
        }
        $mohon->jenis_jualan_id = $request->jenis_jualan;


        $mohon->save();


        return redirect(route('admin.papar-wangproses', ['id'=>$request->permohonan_id]))->with('success', 'Maklumat fail '.$mohon->no_akaun_lesen.' telah disimpan');
    }

    public function simpanNoLesen(Request $request){

        $mohon = LesenPenjaja::find($request->permohonan_id);

        $mohon->no_akaun_lesen = $request->no_akaun_lesen;
        $mohon->kod_lesen = $request->kod_lesen;

        try {
            DB::connection('second_mysql')->getPdo();

            $epbtlsn = EpbtElsnAkaun::where('noakaun', $request->no_akaun_lesen)->where('statusaktif', 'A')->first();
            if(!is_null($epbtlsn)){ 
                $mohon->dt_lesen_dikeluarkan = $epbtlsn->ent_date;

                $bil_kpi = $mohon->kiraKpi();
            }
            
        } catch (\Exception $e) {
            //return back()->with('error', 'Sambungan ke pangkalan data gagal. Sila cuba sebentar lagi.');
        }

        $mohon->save();


        return redirect(route('admin.papar-lesen', ['id'=>$request->permohonan_id]))->with('success', 'Maklumat fail '.$mohon->no_fail_lesen.' telah disimpan');
    }

    public function hantarPPK(Request $request){

        $mohon = LesenPenjaja::find($request->permohonan_id);
        $mohon->status_progress = 'lawatan tapak';
        $mohon->save();

        $borang = new BorangUlasanIK;
        $borang->lesen_penjaja_id = $request->permohonan_id;
        $borang->dt_rujuk_ppkp = now();
        $borang->save();

        return redirect(route('admin.papar-wangproses', ['id'=>$request->permohonan_id]))->with('success', 'Permohonan '.$mohon->no_akaun_lesen.' telah dihantar untuk tindakan IK.');

    }

    public function simpanPetak(Request $request){

        $permohonan = LesenPenjaja::find($request->permohonan_id);
        $permohonan->longitude = $request->longitude;
        $permohonan->latitude = $request->latitude;
        $permohonan->save();

        return redirect(route('admin.papar-map', [$request->permohonan_id]))->with('success', 'Lokasi telah dikemaskini.');

    }

    public function simpanMesyuarat(Request $request){

        $mesyuarat = MesyuaratPelesenan::firstOrCreate([
            'tahun' => $request->tahun,
            'bil_mesyuarat' => $request->bil_mesyuarat,
            'dt_mesyuarat' => $request->dt_mesyuarat,
        ]);

        if($request->dt_mesyuarat != ''){
            $mesyuarat->dt_mesyuarat = $request->dt_mesyuarat;
        }        

        return redirect(route('pt.bawa-mesyuarat', [$mesyuarat->id]))->with('success', 'Mesyuarat Bilangan '.$request->bil_mesyuarat.'/'.$request->tahun.' telah direkod.');

    }

    public function simpanSenaraiBawaMesyuarat(Request $request){
        $meeting = MesyuaratPelesenan::find($request->mesyuarat_id);
        //$arr_insert = [];
        $jum = 0;
        foreach($request->tambah_mesyuarat as $permohonan_id){
            $meeting->lesen_penjajas()->attach($permohonan_id, [
                'keputusan_mesyuarat' => '',
                'by_law' => $request->bylaw,
                'kodlesen' => $request->kodlesen,
                'kadar_lesen' => $request->kadar_lesen,
                'kadar_sampah' => $request->kadar_sampah,
                'kadar_sewa_petak' => $request->kadar_sewa_petak,
                'kadar_patil' => $request->kadar_patil,                
            ]);
            $jum++;
           // $arr_insert[] = $permohonan_id;
        }


        return redirect(route('pt.bawa-mesyuarat', [$request->mesyuarat_id]))->with('success', 'Sebanyak '.$jum.' permohonan ditambah dalam mesyuarat bilangan '.$request->bil_mesyuarat.'/'.$request->tahun.'.');

    }

    public function tambahKeMesyuarat(Request $request, $permohonan_id, $mesyuarat_id){
        $meeting = MesyuaratPelesenan::find($mesyuarat_id);

        $meeting->lesen_penjajas()->attach($permohonan_id, [
            'keputusan_mesyuarat' => '',
        ]);

        return redirect(route('pt.bawa-mesyuarat', [$mesyuarat_id]))->with('success', 'Permohonan telah dimasukkan');

    }

    public function buangDariMesyuarat(Request $request, $permohonan_id, $mesyuarat_id){
        $permohonan = LesenPenjaja::find($permohonan_id);

        $permohonan->mesyuarats()->detach($mesyuarat_id);

        return redirect(route('pt.bawa-mesyuarat', [$mesyuarat_id]))->with('success', 'Permohonan telah dikeluarkan');

    }

   /*public function cetakLampiranB(Request $request, $mesyuarat_id){
        $permohonan = LesenPenjaja::find($permohonan_id);

        $permohonan->mesyuarats()->detach($mesyuarat_id);

        return redirect(route('pt.bawa-mesyuarat', [$mesyuarat_id]))->with('success', 'Permohonan telah dikeluarkan');

    }*/

    public function exportWord(Request $request)
    {
        $headText = ['name' => 'Arial', 'size' => 10];
        
        $phpWord = new PhpWord();

        $phpWord->setDefaultFontName('Arial');   // Jenis font
        $phpWord->setDefaultFontSize(8);         // Saiz font kecil

        $phpWord->addTitleStyle(
            1, // heading level (1 = Heading1)
            NULL,
            ['alignment' => 'center']
        );

        $section = $phpWord->addSection([
                'orientation' => 'landscape',  
                'marginLeft' => 500,
                'marginRight' => 500,  
            ]);
        $mesyuarat = MesyuaratPelesenan::findOrFail($request->mesyuarat_id);

        $section->addTitle('PERMOHONAN LESEN PENJAJA SEMENTARA', 1);
        $section->addTitle('UNTUK MAKLUMAN DAN KELULUSAN DALAM MESYUARAT JAWATANKUASA KESIHATAN DAN PELESENAN', 1);
        $section->addTitle('BIL '. $mesyuarat->bil_mesyuarat.'/'.$mesyuarat->tahun, 1);

        $section->addText(' ' );
        $section->addText('JENIS LESEN: PENJAJA SEMENTARA', $headText);

        $i = 0;
        $kaws = Kawasan::all();

        foreach($kaws as $kaw){

            $apps = $mesyuarat->applicationsInKawasan($kaw->id);
            if((!is_null($apps))&&(count($apps) > 0)){

                $section->addText($kaw->id.' '.$kaw->nama, $headText);

                // Create table with 7 columns
                $table = $section->addTable([
                    'borderSize' => 6,
                    'borderColor' => '999999',
                    'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER,
                    'cellMargin' => 80,
                ]);

                $row = $table->addRow();
                
                $row->addCell(500)->addText('BIL'); // Col 1
                $row->addCell(2000)->addText('TARIKH MOHON'); // Col 2
                $row->addCell(2000)->addText('NO FAIL MBIP(L)(PS)'); // Col 3
                $row->addCell(4000)->addText('BUTIR-BUTIR PEMOHON LESEN PENJAJA SEMENTARA'); // Col 3
                $row->addCell(4000)->addText('PERIHAL PERNIAGAAN'); // Col 3
                $row->addCell(3000)->addText('KADAR BAYARAN 6 BULAN PERTAMA (JAN-JUN)'); // Col 3
                $row->addCell(1200)->addText('KEPUTUSAN MESYUARAT JKKL '.$mesyuarat->bil_mesyuarat.'/'.$mesyuarat->tahun); // Col 3


                foreach($apps as $penjaja){
                    $i++;
                    // Add a single row----------
                    $row = $table->addRow();
                    
                    $row->addCell(500)->addText($i); // Col 1
                    $row->addCell(2000)->addText($penjaja->tarikhmohon); // Col 2
                    $row->addCell(2000)->addText($penjaja->no_fail_lesen); // Col 3
        //-------------------
                    $applicantCell = $row->addCell(4000);
                    $innerTable = $applicantCell->addTable([
                            'cellMarginTop' => 0,
                            'cellMarginBottom' => 0,
                            'cellMarginLeft' => 80,
                            'cellMarginRight' => 80,]);

                    $innerTable->addRow();
                    $innerTable->addCell(1500)->addText('Nama Pemohon:', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(200)->addText(': ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(2300)->addText($penjaja->user->name, null, ['spaceAfter' => 0,]);

                    $innerTable->addRow();
                    $innerTable->addCell(1500)->addText('Lokasi Perniagaan:', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(200)->addText(': ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(2300)->addText($penjaja->lokasi_penjajaan(), null, ['spaceAfter' => 0,]);

                    $innerTable->addRow();
                    $innerTable->addCell(1500)->addText('Masa Perniagaan:', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(200)->addText(': ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(2300)->addText(substr($penjaja->masa_jualan_mula, 0, 5).' - '.substr($penjaja->masa_jualan_tamat, 0, 5), null, ['spaceAfter' => 0,]);
        //-----------------------


        //-------------------
                    $bisnesCell = $row->addCell(4000);
                    $innerTable = $bisnesCell->addTable([
                            'cellMarginTop' => 0,
                            'cellMarginBottom' => 0,
                            'cellMarginLeft' => 80,
                            'cellMarginRight' => 80,]);

                    $innerTable->addRow();
                    $innerTable->addCell(1500)->addText('Jenis Perniagaan:', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(200)->addText(': ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(2300)->addText($penjaja->jenis_penjaja->jenis, null, ['spaceAfter' => 0,]);

                    $innerTable->addRow();
                    $innerTable->addCell(1500)->addText('By-Law Lesen:', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(200)->addText(': ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(2300)->addText($penjaja->pivot->by_law, null, ['spaceAfter' => 0,]);

                    $innerTable->addRow();
                    $innerTable->addCell(1500)->addText('Kod Lesen:', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(200)->addText(': ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(2300)->addText($penjaja->pivot->kodlesen, null, ['spaceAfter' => 0,]);
        //-----------------------


                    $kadarCell = $row->addCell(3000);
                    $innerTable = $kadarCell->addTable([
                            'cellMarginTop' => 0,
                            'cellMarginBottom' => 0,
                            'cellMarginLeft' => 80,
                            'cellMarginRight' => 80,]);
                    // Cell 6: License fees
                    $innerTable->addRow();
                    $innerTable->addCell(1400)->addText('Lesen', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(700)->addText(': RM ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(900)->addText(number_format($penjaja->pivot->kadar_lesen, 2, '.', ','), 
                                                        null, 
                                                        ['alignment' => 'right', 'spaceAfter' => 0,]
                                                    );

                    $innerTable->addRow();
                    $innerTable->addCell(1400)->addText('Sampah', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(700)->addText(': RM ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(900)->addText(number_format($penjaja->pivot->kadar_sampah, 2, '.', ','), 
                                                        null, 
                                                        ['alignment' => 'right', 'spaceAfter' => 0,]
                                                    );

                    $innerTable->addRow();
                    $innerTable->addCell(1400)->addText('Sewa Petak', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(700)->addText(': RM ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(900)->addText(number_format($penjaja->pivot->kadar_sewa_petak, 2, '.', ','), 
                                                        null, 
                                                        ['alignment' => 'right', 'spaceAfter' => 0,]
                                                    );

                    $innerTable->addRow();
                    $innerTable->addCell(1400)->addText('Patil', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(700)->addText(': RM ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(900)->addText(number_format($penjaja->pivot->kadar_patil, 2, '.', ','), 
                                                        null, 
                                                        ['alignment' => 'right', 'spaceAfter' => 0,]
                                                    );

                    $jumlah = $penjaja->pivot->kadar_lesen + $penjaja->pivot->kadar_sampah + $penjaja->pivot->kadar_sewa_petak + $penjaja->pivot->kadar_patil;

                    $innerTable->addRow();
                    $innerTable->addCell(1400)->addText('Jumlah', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(700)->addText(': RM ', null, ['spaceAfter' => 0,]);
                    $innerTable->addCell(900)->addText(number_format($jumlah, 2, '.', ','), 
                                                        null, 
                                                        ['alignment' => 'right', 'spaceAfter' => 0,]
                                                    );


                    $resultCell = $row->addCell(1200);
                    $innerTable = $resultCell->addTable();
                    // Cell 6: License fees
                    $innerTable->addRow();
                    $innerTable->addCell(1200)->addText('[  ] Lulus');
                    $innerTable->addRow();
                    $innerTable->addCell(1200)->addText('[  ] Tangguh');
                    $innerTable->addRow();
                    $innerTable->addCell(1200)->addText('[  ] Tolak');

                }
                
                $section->addText(' ' );
            }
        }

        $filename = 'lesenku-' . $mesyuarat->id . '.docx';
        $path = storage_path('app/public/' . $filename);
        
        $writer = IOFactory::createWriter($phpWord, 'Word2007');
        $writer->save($path);

        return response()->download($path)->deleteFileAfterSend(true);
    }

    public function sahkanSenarai(Request $request){

        $mesyuarat = MesyuaratPelesenan::find($request->mesyuarat_id);
        $mesyuarat->kunci_senarai = '1';
        $mesyuarat->save();

        foreach($mesyuarat->lesen_penjajas as $permohonan){
            $permohonan->status_progress = 'menunggu keputusan mesyuarat';
            $permohonan->save();
        }
        

        return redirect(route('pt.keputusanmesyuarat', [$request->mesyuarat_id]))->with('success', 'Mesyuarat Bilangan '.$request->bil_mesyuarat.'/'.$request->tahun.' telah direkod.');

    }

    public function simpanKeputusanMesyuarat(Request $request){

        $i = 0;
        $mesyuarat = MesyuaratPelesenan::find($request->mesyuarat_id);
//`status_progress`, `status_mesyuarat`
        foreach($mesyuarat->lesen_penjajas as $permohonan){
            $keputusan_dia = $request->keputusan[$permohonan->id];
            $permohonan->status_progress = 'keputusan diperolehi';
            if($keputusan_dia == 'ditangguhkan'){
                $permohonan->status_mesyuarat = 'ditangguhkan';
                $permohonan->pivot->keputusan_mesyuarat = 'menangguhkan';
            }
            elseif($keputusan_dia == 'diluluskan'){
                $permohonan->status_mesyuarat = 'diluluskan';
                $permohonan->pivot->keputusan_mesyuarat = 'meluluskan';
            }
            elseif($keputusan_dia == 'ditolak'){
                $permohonan->status_mesyuarat = 'ditolak';
                $permohonan->pivot->keputusan_mesyuarat = 'menolak';
            }
            $i++;
            $permohonan->save();
        }
        

        return redirect(route('pt.dapat-keputusan-mesyuarat', [$request->mesyuarat_id]))->with('success', 'Keputusan Mesyuarat Bilangan '.$request->bil_mesyuarat.'/'.$request->tahun.' telah direkod untuk '.$i.' permohonan.');

    }

    public function searchPelanggan(Request $request){
        $no_pelanggans = null;
        if(isset($request->carian)){
            $no_pelanggans = EpbtPelanggan::where('nokpdaftar', 'LIKE', "%".$request->carian."%")->orWhere('nama', 'LIKE', "%".$request->carian."%")->get();
        }
//dd($no_pelanggans);
        return view('admin.penjaja.cekbilpel', ['no_pelanggans' => $no_pelanggans]);
    }
 

    public function ajaxUpdateNoFailLesen(Request $request, $permohonanId): JsonResponse
    {
        // Optional: authorization ikut role/policy
        // $this->authorize('update', ...);

        $validated = $request->validate([
            'no_fail_lesen' => ['nullable', 'string', 'max:100'],
        ]);

        $lesen = LesenPenjaja::where('id', $permohonanId)->first();

        if (!$lesen) {
            // Kalau kau nak auto-create record bila belum wujud:
            // $lesen = LesenPenjaja::create(['permohonan_id' => $permohonanId, 'no_fail_lesen' => $validated['no_fail_lesen'] ?? null]);
            return response()->json([
                'ok' => false,
                'message' => 'Rekod lesen_penjajas untuk permohonan ini tidak dijumpai.'
            ], 404);
        }

        $lesen->no_fail_lesen = $validated['no_fail_lesen'] ?? null;
        $lesen->save();

        return response()->json([
            'ok' => true,
            'message' => 'No fail lesen berjaya disimpan.',
            'no_fail_lesen' => $lesen->no_fail_lesen,
        ]);
    }

}
