<?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';
    $onlick = "','";
    $onlick = explode(",",$onlick);
    $total_pembayaran = 0;

function hitung_total_bayar($connection, $master_spp) {
    $query_tagihan = mysqli_query($connection, "
        SELECT SUM(nominal) AS total_tagihan, tahun_ajaran
        FROM master_spp
        WHERE master_spp_id='$master_spp' AND status = 'Y'");
    $data_tagihan = mysqli_fetch_assoc($query_tagihan);
    $total_tagihan = (int) ($data_tagihan['total_tagihan'] ?? 0);
    return [
        'total_tagihan' => $total_tagihan,
        'tahun_ajaran'  => $data_tagihan['tahun_ajaran'],
    ];
}


$nisn               = isset($_POST['nisn']) ? (int)$_POST['nisn'] : 0;
$master_spp         = isset($_POST['master_spp']) ? $_POST['master_spp'] : '-';
$hasil              = hitung_total_bayar($connection, $master_spp);

   $aColumns = [
        'pembayaran.pembayaran_id',
        'pembayaran.admin_id',
        'user.user_id',
        'user.nisn',
        'user.nama_lengkap',
        'pembayaran.kelas',
        'pembayaran.bulan',
        'pembayaran.nominal',
        'pembayaran.tanggal',
        'pembayaran.time',
        'pembayaran.status'
    ];

    $sTable = "pembayaran INNER JOIN user ON user.user_id = pembayaran.user_id";
    $sIndexColumn = "pembayaran.pembayaran_id";
    $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($_POST['iDisplayStart']) && $_POST['iDisplayLength'] != '-1')
    {
        $sLimit = "LIMIT ".mysqli_real_escape_string($gaSql['link'], $_POST['iDisplayStart']).", ".
            mysqli_real_escape_string($gaSql['link'], $_POST['iDisplayLength']);
    }

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

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

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

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

    $sQuery = " SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM $sTable
        $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($_POST['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    $no = 0;
    while ($aRow = mysqli_fetch_array($rResult)){$no++;
      //extract($aRow);
        $row = array();

        $query_petugas  = "SELECT fullname FROM admin WHERE admin_id='$aRow[admin_id]'";
        $result_petugas = $connection->query($query_petugas);
        $data_petugas = $result_petugas->fetch_assoc();
    
        if ($aRow['status'] === 'berhasil') {
            $total_pembayaran += (int)$aRow['nominal'];
        }

        if($aRow['status'] == 'pending'){
            $status = '<span class="badge'.htmlspecialchars($aRow['pembayaran_id']).' badge badge-warning">Pending</span>';
        }elseif($aRow['status'] == 'berhasil'){
            $status = '<span class="badge'.htmlspecialchars($aRow['pembayaran_id']).' badge badge-success">Berhasil</span>';
        }elseif($aRow['status'] == 'cancel'){
            $status = '<span class="badge'.htmlspecialchars($aRow['pembayaran_id']).' badge badge-danger">Cancel</span>';
        }else{
            $status = '<span class="badge'.htmlspecialchars($aRow['pembayaran_id']).' badge badge-danger">Batal</span>';
        }

        $btn_status ='
        <div class="dropdown">
            <a class="btn btn-sm btn-icon-only text-light" href="javascript:void();" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="fas fa-ellipsis-v"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right dropdown-menu-arrow">
                <a class="dropdown-item btn-stts '.($aRow['status'] == 'pending' ? 'active' : '').'" href="javascript:void(0)" data-id="'.$aRow['pembayaran_id'].'" data-status="pending">Pending</a>
                <a class="dropdown-item btn-stts '.($aRow['status'] == 'berhasil' ? 'active' : '').'" href="javascript:void(0)" data-id="'.$aRow['pembayaran_id'].'" data-status="berhasil">Berhasil</a>
                <a class="dropdown-item btn-stts '.($aRow['status'] == 'cansel' ? 'active' : '').'" href="javascript:void(0)" data-id="'.$aRow['pembayaran_id'].'" data-status="cansel">Cancel</a>
                <a class="dropdown-item btn-stts '.($aRow['status'] == 'batal' ? 'active' : '').'" href="javascript:void(0)" data-id="'.$aRow['pembayaran_id'].'" data-status="batal">Batal</a>
            </div>
        </div>';

        
        $btn_hapus ='<a href="javascript:void(0)" class="table-action table-action-delete btn-tooltip btn-delete"  data-placement="top" title="Hapus" data-id="'.htmlentities(convert('encrypt',$aRow['pembayaran_id'])).'">
            <i class="fas fa-trash"></i>
        </a>';

        $btn_update = '<a href="javascript:void(0)" class="table-action table-action-primary btn-update btn-tooltip"   data-placement="left" title="Edit" data-id="'.htmlentities(convert('encrypt',$aRow['pembayaran_id'])).'">
                    <i class="fas fa-edit"></i>
                </a>';

        $row[] = '<div class="text-center">'.$no.'</div>';
        $row[] = ''.($aRow['nama_lengkap']??'-').'<br>NISN. '.($aRow['nisn']??'-').'';
        $row[] = ($aRow['kelas']??'-');
        $row[] = ($hasil['tahun_ajaran']??'-');
        $row[] = ambilbulan($aRow['bulan']??'-');
        $row[] = '<b>Rp '.format_angka($aRow['nominal']??'-').'</b>';
        $row[] = ''.date('d-m-Y', strtotime($aRow['tanggal'])).'<br>'.date('H:i:s', strtotime($aRow['time'])).'';
        $row[] = '<span class="badge badge-warning">'.($data_petugas['fullname']??'-').'</span>';
        $row[] = $status;
        $row[] = '<a href="javascript:void(0)" class="table-action table-action-info btn-tooltip btn-print"  data-placement="top" title="Print" data-id="'.convert('encrypt',$aRow['pembayaran_id']).'">
                <i class="fas fa-print"></i>
            </a>'.$btn_update.' '.$btn_hapus.'';
        
        $output['aaData'][] = $row;
    }

    $total_tagihan = (int) $hasil['total_tagihan']?? 0;  
    $sisa_tagihan = $total_tagihan - $total_pembayaran;
    
    if ($sisa_tagihan <= 0) {
        $status_pembayaran = 'LUNAS';
    } else {
        $status_pembayaran = 'BELUM LUNAS';
    }

    $output['status_pembayaran']    = $status_pembayaran;
    $output['total_pembayaran']     = format_angka($total_pembayaran ?? 0);
    $output['total_tagihan']        = format_angka($total_tagihan ?? 0);
    $output['sisa_tagihan']         = format_angka($sisa_tagihan ?? 0);
    
    echo json_encode($output);
  
}