<?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';

switch (@$_GET['action']){
case 'add':
$error = array();
$id       = htmlentities(convert('decrypt', $_POST['id']?? 0));

$fields = [
  'tahun_ajaran'    => 'Tahun Ajaran',
  'nominal'         => 'Nominal',
];

foreach ($fields as $key => $label) {
  if (empty($_POST[$key])) {
    $error[] = "$label tidak boleh kosong";
  } else {
    $value = anti_injection($_POST[$key]);
    // khusus nominal
    if ($key === 'nominal') {
      $value = format_hapus_titik($value);
    }
    $$key = $value;
  }
}

if (empty($error)) {
  $query  = "SELECT master_spp_id FROM master_spp WHERE master_spp_id='$id'";
  $result = $connection->query($query);
  if (!$result->num_rows > 0) {
    // INSERT
    $add = "INSERT INTO master_spp 
      (tahun_ajaran, nominal, status)
      VALUES 
      ('$tahun_ajaran', '$nominal', 'Y')";
    if ($connection->query($add) === false) {
      die($connection->error . __LINE__);
    } else {
      echo 'success';
    }

  } else {
    // UPDATE
    $update = "UPDATE master_spp SET
      tahun_ajaran    = '$tahun_ajaran',
      nominal         = '$nominal' WHERE master_spp_id = '$id'";
    if ($connection->query($update) === false) {
      die($connection->error . __LINE__);
    } else {
      echo 'success';
    }
  }

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

break;
case 'get-data-update':
if (isset($_POST['id'])) {
  $id = htmlentities(convert('decrypt', $_POST['id'] ?? '-'));
  $query  = "SELECT * FROM master_spp WHERE master_spp_id='$id'";
  $result = $connection->query($query);
  if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    
    $data['id']              = htmlentities(convert('encrypt', $row['master_spp_id']));
    $data['tahun_ajaran']    = $row['tahun_ajaran'] ?? '-';
    $data['nominal']         = format_angka($row['nominal'] ?? '-');
    $data['status']          = $row['status'] ?? 'Y';

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


break;
}
}?>