<?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';
require_once'../../login/user.php';
$total_nominal = 0;

function hitung_total_bayar($connection, $master_spp) {
    $query_tagihan = mysqli_query($connection, "
        SELECT SUM(nominal) AS total_tagihan
        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,
    ];
}


switch (@$_GET['action']){
case 'cek-nisn':
header('Content-Type: application/json');
if (isset($_POST['nisnVal'])) {
    $nisnVal = anti_injection($_POST['nisnVal']);
    $query = "SELECT * FROM user WHERE nisn='$nisnVal' LIMIT 1";
    $result = $connection->query($query);
    if ($result && $result->num_rows > 0) {
        $data = $result->fetch_assoc();
        
        echo json_encode([
            'status' => 'success',
            'data' => $data
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Data tidak ditemukan'
        ]);
    }
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Parameter tidak ditemukan'
    ]);
}


break;
case 'add':
$error = array();

$data_post = [
  'master_spp'     => 'Tahun Ajaran',
  'nisn'             => 'NISN',
  'user_id'          => 'Siswa',
  'kelas'            => 'Kelas',
  'bulan'            => 'Bulan',
  'jumlah_pembayaran'=> 'Jumlah Pembayaran',
];

// Validasi input
$error = [];
foreach ($data_post as $key => $label) {
    if (!isset($_POST[$key]) || ($_POST[$key] === '' && $_POST[$key] !== '0')) {
        $error[] = "$label tidak boleh kosong";
    } else {
        $$key = htmlentities(strip_tags($_POST[$key]));
    }
}

$bayar_sekarang = (int) format_hapus_titik($jumlah_pembayaran);

if (empty($error)) {
  
    $query_bayar = mysqli_query($connection, "
        SELECT SUM(nominal) AS total_bayar
        FROM pembayaran
        WHERE user_id='$user_id' AND status='berhasil'");
    $data_bayar = mysqli_fetch_assoc($query_bayar);
    $total_bayar = (int) ($data_bayar['total_bayar'] ?? 0);

    $hasil   = hitung_total_bayar($connection, $master_spp);
    $total_tagihan = $hasil['total_tagihan']?? 0;
    
    if (($total_bayar + $bayar_sekarang) > $total_tagihan) {
        echo "Pembayaran gagal! Total pembayaran sudah mencapai atau melebihi total tagihan.";
        exit; // hentikan proses insert
    }


  $add = "INSERT INTO pembayaran (
        master_spp_id,
        admin_id,
        user_id,
        kelas,
        bulan,
        nominal,
        tanggal,
        time,
        status
    ) VALUES (
        '$master_spp',
        '$admin_id',
        '$user_id',
        '$kelas',
        '$bulan',
        '$bayar_sekarang',
        '$date',
        '$time',
        'berhasil')";

      if ($connection->query($add) === TRUE) {
          echo "success";
      } else {
          echo "Error: " . $connection->error;
      }

} else {
    // Tampilkan error validasi
    foreach ($error as $values) {
        echo "$values\n";
    }
}


break;
case 'get-data-update':
if (isset($_POST['id'])) {
    $id = htmlentities(convert('decrypt', $_POST['id']));
    $query = " SELECT pembayaran.*, user.nama_lengkap, user.nisn, user.kelas
    FROM pembayaran
    INNER JOIN user ON pembayaran.user_id = user.user_id
    WHERE pembayaran.pembayaran_id = '$id'
    LIMIT 1";
    $result = $connection->query($query);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $query_kelas = "SELECT nama_kelas FROM kelas WHERE kelas_id='$row[kelas]' LIMIT 1";
        $result_kelas = $connection->query($query_kelas);
        $row_kelas = $result_kelas->fetch_assoc();

        $data = [
            'pembayaran_id'     => $row['pembayaran_id'] ?? 0,
            'user_id'           => $row['user_id'] ?? 0,
            'nama_siswa'        => ''.($row['nama_lengkap'] ?? '-').' ['.$row_kelas['nama_kelas'].']',
            'nisn'              => htmlspecialchars($row['nisn'] ?? '-'),
            'jenis_pembayaran'  => $row['jenis_pembayaran'] ?? 0,
            'nominal'           => format_angka($row['nominal'] ?? 0),
            'metode_pembayaran' => ($row['metode_pembayaran'] ?? '-'),
        ];
        echo json_encode([
            'status' => 'success',
            'data'   => $data
        ]);
    } else {
        echo json_encode([
            'status'  => 'error',
            'message' => 'Data tidak ditemukan'
        ]);
    }
}


break;
case 'update':
$error = array();
$data_post = [
    'id'   => 'ID Pembayaran',
    'nisn'             => 'NISN',
    'user_id'         => 'Siswa',
    'jenis_pembayaran'=> 'Jenis Pembayaran',
    'jumlah_pembayaran'=> 'Jumlah Pembayaran',
    'metode_pembayaran'=> 'Metode Pembayaran',
];

// Validasi input
$error = [];
foreach ($data_post as $key => $label) {
    if (!isset($_POST[$key]) || ($_POST[$key] === '' && $_POST[$key] !== '0')) {
        $error[] = "$label tidak boleh kosong";
    } else {
        $$key = htmlentities(strip_tags($_POST[$key]));
    }
}

$id = htmlentities(convert('decrypt', $_POST['id']));
$bayar_sekarang = (int) format_hapus_titik($jumlah_pembayaran);

if (empty($error)) {

    $query_bayar = mysqli_query($connection, "
        SELECT SUM(nominal) AS total_bayar
        FROM pembayaran
        WHERE user_id='$user_id'
        AND jenis_pembayaran='$jenis_pembayaran'
        AND status='berhasil'
        AND pembayaran_id != '$id'");
    $data_bayar = mysqli_fetch_assoc($query_bayar);
    $total_bayar = (int) ($data_bayar['total_bayar'] ?? 0);

    // Total tagihan
    $hasil = hitung_total_bayar($connection, $jenis_pembayaran, $nisn);
    $total_tagihan = $hasil['total_tagihan'] ?? 0;

    if (($total_bayar + $bayar_sekarang) > $total_tagihan) {
        die('Pembayaran gagal! Total pembayaran melebihi total tagihan.');
    }

    // CEK SALDO JIKA METODE SALDO
    if ($metode_pembayaran == 'saldo') {
        $query_saldo = mysqli_query($connection, "
            SELECT saldo FROM saldo_siswa WHERE user_id='$user_id'
        ");

        $saldo = 0;
        if ($query_saldo && mysqli_num_rows($query_saldo) > 0) {
            $data_saldo = mysqli_fetch_assoc($query_saldo);
            $saldo = (int) $data_saldo['saldo'];
        }

        if ($saldo < $bayar_sekarang) {
            die('Saldo tidak mencukupi. Saldo saat ini: Rp ' . format_angka($saldo));
        }else{
            
        }
    }

    $update = "UPDATE pembayaran SET
            user_id='$user_id',
            jenis_pembayaran='$jenis_pembayaran',
            nominal = '$bayar_sekarang',
            metode_pembayaran = '$metode_pembayaran',
            tanggal='$date' WHERE pembayaran_id = '$id'";
    if ($connection->query($update) === TRUE) {
        echo "success";
    } else {
        echo "Error: " . $connection->error;
    }
} else {
    foreach ($error as $values) {
        echo "$values\n";
    }
}

break;
case 'delete':
  if(isset($_POST['id'])){
    $id = htmlentities(convert('decrypt', $_POST['id']));
    $deleted = "DELETE FROM pembayaran WHERE pembayaran_id='$id'";
    if($connection->query($deleted) === true) {
      echo'success';
    } else { 
      echo'Data tidak berhasil dihapus.!';
      die($connection->error.__LINE__);
    }
  }


break;
case 'status':
$id = !empty($_POST['id']) ? htmlentities($_POST['id']) : null;
$status = !empty($_POST['status']) ? htmlentities($_POST['status']) : null;
$update="UPDATE pembayaran SET status='$status' WHERE pembayaran_id='$id'";
if($connection->query($update) === false) { 
  echo 'error';
  die($connection->error.__LINE__); 
}else{
  echo'success';
}


break;
case 'delete':
  $id = !empty($_POST['id']) ? htmlentities(convert('decrypt', $_POST['id'])) : null;
  $deleted = "DELETE FROM pembayaran WHERE pembayaran_id='$id'";
  if($connection->query($deleted) === true) {
    echo'success';
  } else { 
    //tidak berhasil
    echo'Data tidak berhasil dihapus.!';
    die($connection->error.__LINE__);
  }

break;
}}