<?php

namespace App\Http\Controllers;

use App\Audit;
use App\Mohon;
use App\Cawangan;
use App\Mohonid;
use App\MohonAnggota;
use App\Customer;

use Carbon\Carbon;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class KelulusanController extends Controller
{
   public function list($kodcaw)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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

      $kelulusan=Mohon::on($cawangan['mysql'])
               ->where('tarikh','=',$harini->toDateString())
               ->where('masalulus','=','')
               ->where('pelulus','!=','operasi')
               ->get();

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

   public function listdahlulus($kodcaw,$norujukan,Request $request)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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


         $kelulusan=Mohon::on($cawangan['mysql'])
         ->where('tarikh','=',$harini->toDateString())
         ->where('norujukan','=',$norujukan)
         ->where('masalulus','<>','')
         ->get();

        // $audit = new Audit();
        // $audit->users = $request->teller;
        // $audit->actions = "test";
        // $audit->new_data = $kelulusan;
        // $audit->kodcaw = $kodcaw;
        // $audit->created_at = $harini;
        // $audit->updated_at = $harini;
        // $audit->save();

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


   public function listlatestlulus($kodcaw,$norujukan)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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


         $kelulusan=Mohon::on($cawangan['mysql'])
         ->where('tarikh','=',$harini->toDateString())
         ->where('norujukan','=',$norujukan)
         ->orderBy('siri','desc')
         ->first();

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


   public function rekodlepas($kodcaw)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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

      $kelulusan=Mohon::on($cawangan['mysql'])
               ->where('tarikh','<',$harini->toDateString())
               ->where('pelulus','=','khazanah')
               ->where('peloperasi','=','')
               ->where('masalulus','<>','')
               ->get();

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

   public function update($kodcaw,$norujukan,Request $request)
   {
      $harini = Carbon::now();
      $harini = new Carbon;
      $kelulusan = null; 

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

      if($pengesahan == 'khazanah')
      {
         if($request->pembatalan == null)
         {

            $kelulusan=Mohon::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('norujukan','=',$norujukan)
            ->where('siri','=',$request->siri)
            ->update(array(
                     'masalulus' => $harini->toTimeString(),
                     'pelulus' => 'khazanah',
                     'khazanah' => $request->namakhazanah
            ));

         }else{

            $kelulusan=Mohon::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('norujukan','=',$norujukan)
            ->where('siri','=',$request->siri)
            ->update(array(
                     'masalulus'=> 'batal',
                     'pelulus'=> 'khazanah',
                     'khazanah' => $request->namakhazanah
            ));

         }

      }
      else if($pengesahan == 'operasi')
      {
         if($request->pembatalan == null)
         {
            $kelulusan=Mohon::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('norujukan','=',$norujukan)
            ->where('siri','=',$request->siri)
            ->update(array(
                     'pelulus' => 'operasi',
                     'khazanah' => $request->namakhazanah

            ));

         }
         else
         {
            $kelulusan=Mohon::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('norujukan','=',$norujukan)
            ->where('siri','=',$request->siri)
            ->update(array(
                     'pelulus' => 'operasi',
                     'masalulus' => 'batal',
                     'khazanah' => $request->namakhazanah
            ));
         }

         $audit = new Audit();
         $audit->users = (isset($request->namaoperasi) ? $request->namaoperasi : '');
         $audit->actions = "pengesahan kelulusan 75%";
         $audit->new_data = json_encode($kelulusan);
         $audit->kodcaw = $kodcaw;
         $audit->created_at = $harini;
         $audit->updated_at = $harini;
         $audit->save();
      }

      if($request->sahkan === 1)
      {
         $kelulusan=Mohon::on($cawangan['mysql'])
         ->where('tarikh','=',$harini->toDateString())
         ->where('norujukan','=',$norujukan)
         ->where('siri','=',$request->siri)
         ->update(array(
                  'pelulus' => 'dahlulus',
                  'operasi' => $request->namaoperasi,
                  'masalulus'=> $harini->toTimeString()
         ));
      }else if($request->sahkan === 2){
         $kelulusan=Mohon::on($cawangan['mysql'])
         ->where('tarikh','=',$harini->toDateString())
         ->where('norujukan','=',$norujukan)
         ->where('siri','=',$request->siri)
         ->update(array(
                  'pelulus' => 'dahlulus',
                  'operasi' => $request->namaoperasi,
                  'masalulus'=> 'batal'
         ));
      }

      $audit = new Audit();
      $audit->users = (isset($request->namakhazanah) ? $request->namakhazanah : '');
      $audit->actions = $request->actions ?? "pengesahan kelulusan 75%";
      
      // Only prepare detailed audit data for Pampasan approval
      if($request->actions == 'Pengesahan Pembayaran Pampasan') {
         // Prepare data for audit - ensure it's an array
         $auditData = [];
         
         // If kelulusan is a scalar (update result), create array structure
         if (is_scalar($kelulusan) || is_null($kelulusan)) {
             $auditData = ['update_result' => $kelulusan];
         } else {
             $auditData = $kelulusan;
         }
         
         // Add namapelulus and norujukanasal to the audit data
         if(isset($request->namaoperasi)) {
            $auditData['namapelulus'] = !empty($request->namaoperasi) ? $request->namaoperasi : null;
         }
         if(isset($request->norujukan)) {
            $auditData['norujukan'] = !empty($request->norujukan) ? $request->norujukan : null;
         }
      } else {
         // For other actions, use simple kelulusan data
         $auditData = $kelulusan;
      }
      
      $audit->new_data = json_encode($auditData);
      $audit->kodcaw = $kodcaw;
      $audit->created_at = $harini;
      $audit->updated_at = $harini;
      $audit->save();

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

 public function updateAnggota($kodcaw, Request $request)
{
    $harini = Carbon::now();

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

    if (!$cawangan) {
        return response()->json(['success' => false, 'message' => 'Kod cawangan tidak sah'], 404);
    }

    $nokp        = $request->nokp;
    $komen       = $request->komenkelulusan;
    $namaoperasi = $request->namaoperasi;
    $status      = $request->sahkan; // 1 = Lulus, 2 = Batal

    // Debug log masuk
    Log::info('UpdateKelulusanAnggota triggered', [
        'kodcaw' => $kodcaw,
        'nokp' => $nokp,
        'status' => $status,
        'komen' => $komen,
        'namaoperasi' => $namaoperasi
    ]);

    // Kalau LULUS
    if ($status == 1) {
        $kelulusan = MohonAnggota::on($cawangan['mysql'])
            ->where('nokp', '=', $nokp)
            ->update([
                'status'            => 'DILULUSKAN',
                'komen'             => $komen,
                'peloperasi'        => $namaoperasi,
                'datetime_pelulus'  => $harini,
                'updated_at'        => $harini,
            ]);

        // Update CUSTOMER di pusat (mysql7)
        Customer::on('mysql7')
            ->where('kpbaru', '=', $nokp)
            ->update([
                'tag_anggota' => 1,
            ]);
    }
    // Kalau BATAL / TOLAK
    else if ($status == 2) {
        $kelulusan = MohonAnggota::on($cawangan['mysql'])
            ->where('nokp', '=', $nokp)
            ->update([
                'status'            => 'DITOLAK',
                'komen'             => $komen,
                'peloperasi'        => $namaoperasi,
                'datetime_pelulus'  => $harini,
                'updated_at'        => $harini,
            ]);
    } else {
        return response()->json(['success' => false, 'message' => 'Status tidak sah'], 400);
    }

    // 🧾 Simpan audit log
    $audit = new Audit();
    $audit->users = $namaoperasi;
    $audit->actions = ($status == 1)
        ? "Kelulusan anggota oleh operasi (tag_anggota=1)"
        : "Pembatalan / tolak anggota oleh operasi";
    $audit->new_data = json_encode([
        'nokp' => $nokp,
        'status' => $status,
        'komen' => $komen,
    ]);
    $audit->kodcaw = $kodcaw;
    $audit->created_at = $harini;
    $audit->updated_at = $harini;
    $audit->save();

    Log::info('Kelulusan anggota dikemas kini', [
        'nokp' => $nokp,
        'status' => $status,
        'updated_tag_anggota' => ($status == 1) ? 1 : 0
    ]);

    return response()->json([
        'success' => true,
        'status' => ($status == 1) ? 'DILULUSKAN' : 'DITOLAK',
        'updated_rows' => $kelulusan
    ], 200);
}



   public function updatekomen($kodcaw,$norujukan,Request $request)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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

      $kelulusan=Mohon::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('norujukan','=',$norujukan)
            ->where('siri','=',$request->siri)
            ->update(array(
                     'komen' => $request->komen
            ));

      return response()->json($kelulusan,201);

   }

public function create(REQUEST $request,$kodcaw,$norujukan,$roles)
   {
      $harini = Carbon::now();

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

      if($roles == "khazanah")
      {
         $createData = [
                  'tarikh'=> $harini->toDateString(),
                  'norujukan'=> $norujukan,
                  'siri' => $request->siri,
                  'komen' => $request->komen,
                  'margin' => $request->margin,
                  'nilaimarhun' => $request->nilaimarhun,
                  'berat' => $request->berat,
                  'status' => $request->status,
                  'bilgad' => $request->bilgadai,
                  'jumpinj' => $request->jumpinjam,
                  'jenistebus' => $request->jenistebus,
                  'teller' => $request->teller,
                  'pelulus' => ($request->pelulus) ? $request->pelulus : ''
         ];

         // Add peloperasi if status is Kelulusan Pengeluaran Pampasan
         if($request->status == 'Kelulusan Pengeluaran Pampasan' && isset($request->peloperasi)) {
            $createData['peloperasi'] = $request->peloperasi;
         }

         $kelulusan=Mohon::on($cawangan['mysql'])->create($createData);
      }
      else if($roles == "operasi")
      {
         $kelulusan=Mohon::on($cawangan['mysql'])
         ->create([

                  'tarikh'=> $harini->toDateString(),
                  'norujukan'=> $norujukan,
                  'siri' => $request->siri,
                  'komen' => $request->komen,
                  'margin' => $request->margin,
                  'nilaimarhun' => $request->nilaimarhun,
                  'berat' => $request->berat,
                  'status' => $request->status,
                  'bilgad' => $request->bilgadai,
                  'jumpinj' => $request->jumpinjam,
                  'jenistebus' => $request->jenistebus,
                  'teller' => $request->teller,
                  'pelulus' => 'minta',
                  'peloperasi' => ($request->peloperasi) ? $request->peloperasi : ''

         ]);
      }

      $audit = new Audit();
      $audit->users = (isset($request->teller) ? $request->teller : '');
      $audit->actions = $request->actions ?? "Minta Pengesahan kelulusan 75%";
      $audit->new_data = json_encode($kelulusan);
      $audit->kodcaw = $kodcaw;
      $audit->created_at = $harini;
      $audit->updated_at = $harini;
      $audit->save();

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

 public function createKelulusanAnggota(Request $request, $kodcaw)
{
    try {
        $harini = Carbon::now();

        // ✅ Dapatkan maklumat cawangan (database connection)
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $kodcaw)->first();

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

        // ✅ Simpan ke dalam model MohonAnggota
        $kelulusan = new MohonAnggota();
        $kelulusan->setConnection($cawangan['mysql']); // guna connection cawangan dinamik
        $kelulusan->tarikh = $harini->toDateString();
        $kelulusan->nokp = $request->nokp;
        $kelulusan->nama = $request->nama ?? null;
        $kelulusan->status = 'MENUNGGU OPERASI';
        $kelulusan->komen = $request->komen;
        $kelulusan->teller = $request->teller;
        $kelulusan->peloperasi = null;
        $kelulusan->created_at = $harini;
        $kelulusan->updated_at = $harini;
        $kelulusan->save();

        // ✅ Simpan audit trail
        $audit = new Audit();
        $audit->users = $request->teller;
        $audit->actions = 'Mohon kelulusan anggota';
        $audit->new_data = json_encode(['mohon_anggota_id' => $kelulusan->id]);
        $audit->kodcaw = $kodcaw;
        $audit->created_at = $harini;
        $audit->updated_at = $harini;
        $audit->save();

        // ✅ Return JSON response ke frontend
        return response()->json([
            'success' => true,
            'message' => 'Permohonan kelulusan anggota berjaya dihantar kepada operasi.',
            'data' => [
                'id' => $kelulusan->id,
                'nokp' => $kelulusan->nokp,
                'status' => $kelulusan->status,
                'komen' => $kelulusan->komen,
                'teller' => $kelulusan->teller,
            ],
        ], 201);

    } catch (\Throwable $th) {
        Log::error('❌ createKelulusanAnggota error: ' . $th->getMessage());
        return response()->json([
            'success' => false,
            'message' => $th->getMessage(),
        ], 500);
    }
}

   //KEPOHONAN EDIT DAN HAPUS

   public function kepohonancreate(REQUEST $request,$kodcaw,$norujukan)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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

      $mohonid=Mohonid::on($cawangan['mysql'])
      ->create([
               'tarikh'=> $harini->toDateString(),
               'mohon' => $request->mohon,
               'norujukan' => $norujukan,
               'katalaluan' => $request->komen,
               'pinjaman' => $request->pinjaman,
               'nilaimarhun' => $request->nilaimarhun,
               'berat' => $request->berat,
               'margin' => $request->margin,
               'benar' => '0',
               'teller' => $request->teller,
               'tagoperasi'=> ($request->tagoperasi) ? true : false,
               'masa' => $harini->toTimeString(),
               'ansuran' => ($request->ansuran) ? $request->ansuran : 0.00,
      ]);

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

   public function updatekepohonankhazanah($kodcaw,$norujukan,Request $request)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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

      if($request->pembatalan != null)
      {
         $kelulusan=Mohonid::on($cawangan['mysql'])
         ->where('tarikh','=',$harini->toDateString())
         ->where('norujukan','=',$norujukan)
         ->where('recno','=',$request->recno)
         ->update(array(
               'katalaluan' => $request->komen,
               'benar' => '2',
               'id' => $request->khazanah,
               'timestamp_approved_by_pc' => $harini,
         ));
      }else{
         $benar = ($request->tagoperasi == 1) ? 0 : 1;

         $kelulusan=Mohonid::on($cawangan['mysql'])
         ->where('tarikh','=',$harini->toDateString())
         ->where('norujukan','=',$norujukan)
         ->where('recno','=',$request->recno)
         ->update(array(
               'benar' => $benar,
               'id' => $request->khazanah,
               'timestamp_approved_by_pc' => $harini,
         ));
      }

      return response()->json($kelulusan,202);
   }

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

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

      $kelulusan=Mohonid::on($cawangan['mysql'])
               ->where('tarikh','=',$harini->toDateString())
               ->where('norujukan','=',$request->norujukan)
               ->orderBy('recno','desc')
               ->first();

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

   public function listkepohonan($kodcaw)
   {
      $harini = Carbon::now();
      $harini = new Carbon;

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

      $kelulusan=Mohonid::on($cawangan['mysql'])
      ->where('tarikh','=',$harini->toDateString())
      ->where('benar','=', 0)
      ->orderBy('recno','desc')
      ->get();

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

   public function listoperasi()
   {
      $harini = Carbon::now();
      $harini = new Carbon;

      $cawangan_all = Cawangan::on('mysql7')->get();
      $arraykelulusan = [];

      foreach($cawangan_all as $index=>$cawangan){
         $kelulusan = Mohon::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('masalulus','=','')
            ->where('pelulus','=','operasi')
            ->get();

         $mohonid_data = Mohonid::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->whereNotNull('id')
            ->whereNotNull('timestamp_approved_by_pc')
            ->where('tagoperasi', '1')
            ->whereNull('operasi')
            ->get();

         // Check if EITHER has data (not just $kelulusan)
         if(sizeof($kelulusan) != 0 || sizeof($mohonid_data) != 0){
            array_push($arraykelulusan,[
                  "kelulusanall" => $kelulusan,
                  "kelulusanMohonid" => $mohonid_data,
                  "cawangan" => $cawangan['details_caw'],
                  "cawangankod" => $cawangan['kodcaw']
            ]);
         }
      }

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

   public function listoperasikelulusan()
   {
      $harini = Carbon::now();
      $harini = new Carbon;

      $cawangan_all = Cawangan::on('mysql7')->get();
      $arraykelulusan = [];

      foreach($cawangan_all as $index=>$cawangan){
         $kelulusan=Mohon::on($cawangan['mysql'])
               ->where('peloperasi','=','operasi')
               ->where('operasi','!=','')
               ->get();

         if(sizeof($kelulusan) != 0){
             array_push($arraykelulusan,["kelulusanall" => $kelulusan,"cawangan" => $cawangan['details_caw'],"cawangankod" => $cawangan['kodcaw']]);
         }
     }

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

   public function UpdateHapusAnsuranOperasi(Request $request){
      $harini = Carbon::now();

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

      if($request->sahkan === 1){
         $kelulusan=Mohonid::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('norujukan','=',$request->norujukan)
            ->where('recno','=',$request->siri)
            ->where('tagoperasi', '=', 1)
            ->update(array(
               'operasi' => $request->namaoperasi,
               'timestamp_approved_by_operasi' => $harini,
               'benar' => 1,
         ));
      }else if($request->sahkan === 2){
         $kelulusan=Mohonid::on($cawangan['mysql'])
            ->where('tarikh','=',$harini->toDateString())
            ->where('norujukan','=',$request->norujukan)
            ->where('recno','=',$request->siri)
            ->where('tagoperasi', '=', 1)
            ->update(array(
               'operasi' => $request->namaoperasi,
               'timestamp_approved_by_operasi' => $harini,
               'benar' => 2,
         ));
      }

      return response()->json($kelulusan,202);

   }

   public function getApproval(Request $request){
      $harini = Carbon::now();
      $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
      $kelulusan = Mohonid::on($cawangan['mysql'])
         ->where('tarikh','=',$harini->toDateString())
         ->where('teller','=',$request->teller)
         ->where('mohon','=',$request->mohon)
         ->where('benar','=',0)
         ->latest('masa')
         ->first();
      
      return response()->json($kelulusan, 200);
   }

   public function getApprovalList(Request $request){
      $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
      $kelulusan = Mohonid::on($cawangan['mysql'])
         ->groupBy('mohon')
         ->pluck('mohon');
      
      return response()->json($kelulusan, 200);
   }

   public function getApprovalLaporan(Request $request){
      $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
      $kelulusan = Mohonid::on($cawangan['mysql'])
         ->selectRaw('recno, benar, tarikh, onlineid, mohon, norujukan, id, katalaluan, benar, operasi, pinjaman, ansuran, nilaimarhun, berat, margin, teller ,masa, timestamp_approved_by_pc, timestamp_approved_by_operasi')
         ->whereBetween('tarikh', [$request->tarikh_mula, $request->tarikh_akhir])
         ->where('mohon', $request->mohon)
         ->orderBy('tarikh', 'desc')
         ->orderBy('masa', 'desc')
         ->get();

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

   public function listKelulusanAnggota(Request $request)
{
    $harini = Carbon::now();
    Log::info($request->all());
    $cawangan = Cawangan::on('mysql7')->get();

    $array_kelulusan = [];

    foreach ($cawangan as $caw) {
        
        $kelulusan = MohonAnggota::on($caw['mysql'])
            ->whereDate('tarikh', $harini->toDateString())
            ->where(function ($query) {
                $query->where('peloperasi', '=', 0)
                      ->orWhereNull('peloperasi');
            })
            ->orderBy('id', 'desc')
            ->get();

        if ($kelulusan->isNotEmpty()) {

            // Kumpul semua nokp daripada senarai kelulusan
            $nokpList = $kelulusan->pluck('nokp')->unique()->toArray();

            // Ambil semua nama daripada table customer (main DB)
            $customers = Customer::whereIn('kpbaru', $nokpList)
                ->pluck('nama', 'kpbaru')
                ->toArray();

            // Masukkan nama ke dalam setiap item kelulusan
            $kelulusan = $kelulusan->map(function ($item) use ($customers) {
                $item->nama = $customers[$item->nokp] ?? '-';
                return $item;
            });

            // Tambah ke array utama
            $array_kelulusan[] = [
                "kelulusanall" => $kelulusan,
                "cawangan" => $caw['details_caw'],
                "cawangankod" => $caw['kodcaw']
            ];
        }
    }

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




}
