<?php
session_start();
//include "inc/config.php";
include "../../../inc/config.php";
$token = get_token();
		$requestData= $_REQUEST;

		$sSearch = $requestData['search']['value'];
$filter = "";
$semester = "";
$search_filter = "";
$prodi = "";
$keyword = "";
$status = "";
$id_sms = "";
$filter_count = "";
$kode_mk = "";
$kelas = "";
$jumlah = 0;
$and_id_prodi = "";
$id_reg_pd = "nothing";
$and_semester = "";
$and_kelas = "";
//dump($data_dic);
$filter_kelas = "nothing";
$id_reg_pd = "nothing";

if ($sSearch!='') {
	$search_filter = "and (nim like '%".$sSearch."%' or lower(nama_mahasiswa) like '%".strtolower($sSearch)."%')";
}
$old_kode_mk = "";

if ($_POST['kode_mk']!='all') {
	$kode_mk = "and id_matkul='".$_POST['kode_mk']."'";
	$old_kode_mk = "and id_mk='".$_POST['kode_mk']."'";
}
if ($_POST['kelas']!='all') {
	$kelas = "and id_kelas_kuliah='".$_POST['kelas']."'";
}

if ($_POST['jurusan']=='all') {
$id_sms = '';
$and_id_sms = '';
if ($_SESSION['level']!=1) {
	$id_sms = "and id_prodi='".$_SESSION['id_sms']."'";
	$and_id_sms = "and id_sms='".$_SESSION['id_sms']."'";
}

} else {
	$id_sms = "and id_prodi='".$_POST['jurusan']."'";
	$and_id_sms = "and id_sms='".$_POST['jurusan']."'";
}

		
		//$Data = $this->input->get('columns');
		//$orders = $requestData['order'];
		//$temp_order = 


		$iStart = $requestData['start'];
		$iLength = $requestData['length'];

		$temp_limit = $iLength;
		$temp_offset = $iStart?$iStart : 0;

		
		$order_by = "id_periode desc";



		if ($_POST['nim']!='all') {
			//check nim
			$id_sms_mhs = "";
			if ($_POST['jurusan']!='all') {
				$id_sms_mhs = "and id_prodi='".$_POST['jurusan']."'";
			}
			$data_dic = [
			'act' => 'GetListMahasiswa',
		    'token' => $token,
		    'filter' => "nim='".$_POST['value_nim']."' $id_sms_mhs"
			];
			$check_mhs = service_request($data_dic);
			
			if (!empty($check_mhs->data)) {
				$id_reg_pd = $check_mhs->data[0]->id_registrasi_mahasiswa;
				$id_prodi = $check_mhs->data[0]->id_prodi;
				
				if ($_POST['semester']!='') {
					$and_semester = "and id_semester='".$_POST['semester']."'";
				}
				if ($_POST['kelas']!='all') {
					$and_kelas = "and id_kelas_kuliah='".$_POST['kelas']."'";
				}
				$and_id_prodi = "and id_prodi='".$id_prodi."'";
				
				$filter_kelas = "id_registrasi_mahasiswa='$id_reg_pd' $and_id_prodi $and_semester  $kode_mk $and_kelas";
			}
			
		} else {
			if ($_POST['kelas']!='all') {
				$filter_kelas = "id_kelas_kuliah='".$_POST['kelas']."' $search_filter";
				//$filter_kelas = "id_kelas_kuliah in(select id_kls from kelas_kuliah where id_kls='".$_POST['kelas']."') $keyword";
			} else {
				$filter_kelas = "id_semester='".$_POST['semester']."' $id_sms $kode_mk $search_filter";
			}
		}

		//echo $filter_kelas;
		

		$data_dics = [
			'act' => 'GetDetailNilaiPerkuliahanKelas',
		    'token' => $token,
		    'filter' => $filter_kelas."
		    AND EXISTS (
  SELECT 1
  FROM nilai_smt_mhs n
  JOIN kelas_kuliah k
    ON n.id_kls = k.id_kls
  WHERE k.id_smt = '".$_POST['semester']."'
    AND id_registrasi_mahasiswa = id_reg_pd
    AND id_matkul =  k.id_mk 
    AND id_kelas_kuliah <> n.id_kls
    and n.soft_delete='0'
)
",
		    'order' => 'nim asc',
		    'limit' => $temp_limit,
		    'offset' => $temp_offset

		];

	
		$temp_data = service_request($data_dics);



		if ($_POST['nim']!='all') {
			//check nim
			if ($_POST['semester']!='') {
				$and_semester = "and id_semester='".$_POST['semester']."'";
			}
			$data_dic = [
			'act' => 'GetCountNilaiPerkuliahanKelas',
		    'token' => $token,
		    'filter' => "id_registrasi_mahasiswa='".$id_reg_pd."' $and_semester  $and_id_prodi $kode_mk $and_kelas AND EXISTS (
  SELECT 1
  FROM nilai_smt_mhs n
  JOIN kelas_kuliah k
    ON n.id_kls = k.id_kls
  WHERE  id_registrasi_mahasiswa = id_reg_pd
    AND id_matkul =  k.id_mk 
    AND id_kelas_kuliah <> n.id_kls
    and n.soft_delete='0'
)",
			];
			//dump($data_dic);
			$check_krs = service_request($data_dic);
			$filter_kelas = "nothing";
			if (!empty($check_krs->data)) {
				$jumlah = $check_krs->data;
			}
			//$jumlah = 100;
			
		} else {

			if ($_POST['kelas']!='all') {
			$filter_kelas = "id_kelas_kuliah='".$_POST['kelas']."' $search_filter";
			//$filter_kelas = "id_kelas_kuliah in(select id_kls from kelas_kuliah where id_kls='".$_POST['kelas']."') $keyword";
			$array_count = array(
			  'act' => 'GetCountPesertaKelasKuliah',
			  'token' => $token,
			  'filter' => $filter_kelas,
		        'order' => '',
		        'limit' => '1',
		        'offset' => '0'
			);

			$temp_count = service_request($array_count);
			$jumlah = $temp_count->data;
			} else {
/*				$filter_kelas = "id_kelas_kuliah in(select id_kls from kelas_kuliah where id_smt='".$_POST['semester']."' $and_id_sms $old_kode_mk) $search_filter";
				$array_count = array(
				  'act' => 'GetCountPesertaKelasKuliah',
				  'token' => $token,
				  'filter' => $filter_kelas,
			        'order' => '',
			        'limit' => '1',
			        'offset' => '0'
				);
				$temp_count = service_request($array_count);
				$jumlah = $temp_count->data;*/
				$jumlah = count($temp_data->data);
		}

	}


			$totalData = $jumlah;
			$totalFiltered = $totalData;

			//echo "id_kelas_kuliah in(select id_kls from kelas_kuliah where id_smt='".$_POST['semester']."' and id_sms='".$_POST['jurusan']."') $kode_mk $keyword";


		$temp_datas = array();
		$i=0;
		
if (!empty($temp_data->data)) {
    // 1️⃣ Kelompokkan berdasarkan kombinasi id_registrasi_mahasiswa + id_matkul
    $groups = [];
    foreach ($temp_data->data as $dt) {
    		if ($_POST['filter_by']=='id_matkul') {
    			$key = $dt->id_registrasi_mahasiswa . '|' . $dt->id_matkul;
    		} else {
    			$key = $dt->id_registrasi_mahasiswa . '|' . $dt->kode_mata_kuliah;
    		}
        
        $groups[$key][] = $dt;
    }

    // 2️⃣ Tentukan nilai tertinggi di setiap grup berdasarkan nilai_indeks, lalu nilai_angka
    $best_scores = [];
    $best_ids = []; // To store the unique identifier of the row with the highest nilai_indeks and nilai_angka
    foreach ($groups as $key => $items) {
        $max_indeks = -INF;
        $max_angka = -INF;
        $best_item_id = null;
        foreach ($items as $it) {
            $indeks = floatval($it->nilai_indeks ?? 0);
            $angka = floatval($it->nilai_angka ?? 0);
            // Compare nilai_indeks first, then nilai_angka if nilai_indeks is equal
            if ($indeks > $max_indeks || ($indeks == $max_indeks && $angka > $max_angka)) {
                $max_indeks = $indeks;
                $max_angka = $angka;
                // Store the unique identifier for the row with the highest nilai_indeks and nilai_angka
                $best_item_id = $it->id_kelas_kuliah . '$' . $it->id_registrasi_mahasiswa;
            }
        }
        $best_scores[$key] = ['indeks' => $max_indeks, 'angka' => $max_angka];
        $best_ids[$key] = $best_item_id; // Save the ID of the row with the highest score
    }

    // 3️⃣ Loop utama dan buat tabel + checkbox
    $temp_datas = [];
    $i = 0;

    foreach ($temp_data->data as $dt) {
       
        if ($_POST['filter_by']=='id_matkul') {
    			 $key = $dt->id_registrasi_mahasiswa . '|' . $dt->id_matkul;
    		} else {
    			 $key = $dt->id_registrasi_mahasiswa . '|' . $dt->kode_mata_kuliah;
    		}
        $nilai_indeks = floatval($dt->nilai_indeks ?? 0);
        $nilai_angka = floatval($dt->nilai_angka ?? 0);
        $current_id = $dt->id_kelas_kuliah . '$' . $dt->id_registrasi_mahasiswa;

        // Check if this row is NOT the one with the highest nilai_indeks (or nilai_angka if indeks is tied)
        $checkedAttr = ($current_id !== $best_ids[$key]) ? "checked" : "";

        $temps = [];
        $temps[] = ++$i + $temp_offset . " <input type='checkbox' class='deleteRow' value='" .
            $dt->id_kelas_kuliah . "$" . $dt->id_registrasi_mahasiswa . "' $checkedAttr />";
        $temps[] = $dt->id_semester;
        $temps[] = $dt->nim;
        $temps[] = $dt->nama_mahasiswa;
        $temps[] = $dt->kode_mata_kuliah;
        $temps[] = $dt->nama_mata_kuliah;
        $temps[] = $dt->nama_kelas_kuliah;
        $temps[] = round($dt->nilai_angka, 2);
        $temps[] = $dt->nilai_indeks;
        $temps[] = $dt->nilai_huruf;
        $temps[] = $dt->nama_program_studi;
        $temps[] = $dt->id_kelas_kuliah . "$" . $dt->id_registrasi_mahasiswa;

        $temp_datas[] = $temps;
    }
}

			$temp_output = array(
									'draw' => intval($requestData['draw']),
									'recordsTotal' => intval( $totalData ),
									'recordsFiltered' => intval( $totalFiltered ),
									'data' => $temp_datas
				);

			echo json_encode($temp_output);