<?php session_start();
if(!isset($_COOKIE['ADMIN_KEY']) && !isset($_COOKIE['KEY'])){
  header('location:./login');
  exit;
} else{
    require_once'../../../sw-library/sw-config.php';
    require_once'../../../sw-library/sw-function.php';

    $filterParts = [];
    $from   = isset($_POST['from']) ? date('Y-m-d', strtotime(strip_tags($_POST['from']))) : date('Y-m-d', strtotime($date));
    $to     = isset($_POST['to']) ? date('Y-m-d', strtotime(strip_tags($_POST['to']))) : date('Y-m-d', strtotime($date));

    
    if (!empty($_POST['siswa'])) {
        $siswa = htmlentities(epm_decode($_POST['siswa']??'-'));
        $filterParts[] = "user.user_id='$siswa'";
        $filter = 'WHERE ' . implode(' AND ', $filterParts);

    }else if(!empty($_POST['kelas'])) {
        $kelas = htmlentities($_POST['kelas']);
        $filterParts[] = "user.kelas='$kelas'";
        $filter = 'WHERE ' . implode(' AND ', $filterParts);
    }else{
        $filter = '';
    }


    $aColumns = ['user.user_id', 'user.nama_lengkap', 'kelas.nama_kelas'];
    $sJoin = " LEFT JOIN kelas ON user.kelas = kelas.nama_kelas";
    $sIndexColumn = "user.user_id";
    $sTable = "user";
    
    $gaSql['user'] = DB_USER;
    $gaSql['password'] = DB_PASSWD;
    $gaSql['db'] = DB_NAME;
    $gaSql['server'] = DB_HOST;

    $gaSql['link'] =  new mysqli($gaSql['server'], $gaSql['user'], $gaSql['password'], $gaSql['db']);

    $sLimit = "";
    if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1')
    {
        $sLimit = "LIMIT ".mysqli_real_escape_string($gaSql['link'], $_GET['iDisplayStart']).", ".
            mysqli_real_escape_string($gaSql['link'], $_GET['iDisplayLength']);
    }

    $sOrder = "ORDER BY user.nama_lengkap ASC";
    if (isset($_GET['iSortCol_0']))
    {
        $sOrder = "ORDER BY user.nama_lengkap ASC";
        for ($i=0; $i<intval($_GET['iSortingCols']) ; $i++)
        {
            if ($_GET['bSortable_'.intval($_GET['iSortCol_'.$i])] == "true")
            {
                $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i])]."
                    ".mysqli_real_escape_string($gaSql['link'], $_GET['sSortDir_'.$i]) .", ";
            }
        }

        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY user.nama_lengkap ASC")
        {
            $sOrder = "ORDER BY user.nama_lengkap ASC";
        }
    }

    $sWhere = "$filter";
    if (isset($_GET['sSearch']) && $_GET['sSearch'] != "")
    {
        $sWhere = "WHERE (";
        for ($i=0; $i<count($aColumns); $i++)
        {
            $sWhere .= $aColumns[$i]." LIKE '%".mysqli_real_escape_string($gaSql['link'], $_GET['sSearch'])."%' OR ";
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ')';
    }

    for ($i=0 ; $i<count($aColumns); $i++)
    {
        if (isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '')
        {
            if ($sWhere == "")
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." LIKE '%".mysqli_real_escape_string($gaSql['link'], $_GET['sSearch_'.$i])."%' ";
        }
    }

    $sQuery = " SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM $sTable
        $sJoin
        $sWhere
        $sOrder
        $sLimit ";
    $rResult = mysqli_query($gaSql['link'], $sQuery);

    $sQuery = "SELECT FOUND_ROWS()";
    $rResultFilterTotal = mysqli_query($gaSql['link'], $sQuery);
    $aResultFilterTotal = mysqli_fetch_array($rResultFilterTotal);
    $iFilteredTotal = $aResultFilterTotal[0];

    $sQuery = "SELECT COUNT(".$sIndexColumn.") FROM   $sTable";
    $rResultTotal = mysqli_query($gaSql['link'], $sQuery);
    $aResultTotal = mysqli_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];

    $output = array( 
       // "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    $no = 0;
    
    while ($aRow = mysqli_fetch_array($rResult)){$no++;
      extract($aRow);
        $row = array();
        
        $query_pelanggaran ="SELECT SUM(bobot) AS total_bobot FROM pelanggaran WHERE user_id='$aRow[user_id]' AND tanggal  BETWEEN '$from' AND '$to'";
        $result_pelanggaran = $connection->query($query_pelanggaran);
        $data_pelanggaran = $result_pelanggaran->fetch_assoc();

        $query_absen = "SELECT COUNT(*) AS jumlah_hadir FROM absen  WHERE user_id = '$aRow[user_id]'
        AND kehadiran = 'Hadir' AND tanggal BETWEEN '$from' AND '$to'";
        $result_absen = $connection->query($query_absen);
        $data_absen = $result_absen->fetch_assoc();
        $total_bobot = ($data_pelanggaran['total_bobot']??'0');

        if ($data_pelanggaran['total_bobot'] > 50) {
            $warna = "<span class='badge badge-danger'>$total_bobot</span>";
        } 
        elseif ($data_pelanggaran['total_bobot'] > 20) {
            $warna = "<span class='badge badge-warning'>$total_bobot</span>";
        } 
        else {
            $warna = "<span class='badge badge-info'>$total_bobot</span>";
        }


        $row[] = '<div class="text-center">'.$no.'</div>';
        $row[] = strip_tags($aRow['nama_lengkap']??'-');
        $row[] = strip_tags($aRow['nama_kelas']??'-');
        $row[] = $warna;
        $row[] = '<span class="badge badge-info">'.($data_absen['jumlah_hadir']??'0').'</span>';
    
        $output['aaData'][] = $row;
   
    }
    echo json_encode($output);
}