<?php
session_start();

if (!isset($_SESSION['user']) || $_SESSION['level'] != 'A') {
    header("Location: ../index.php");
    exit;
}

require '../config.php';

ini_set('display_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['create'])) {
        $ckode = $_POST['ckode'];
        $cnama = $_POST['cnama'];
        $npoin = $_POST['npoin'];

        $sql_check_ckode = "SELECT ckode FROM tbreward WHERE ckode = ?";
        $stmt_check_ckode = $conn->prepare($sql_check_ckode);
        $stmt_check_ckode->bind_param("s", $ckode);
        $stmt_check_ckode->execute();
        $result_check_ckode = $stmt_check_ckode->get_result();
    
        if ($result_check_ckode->num_rows > 0) {
            echo json_encode(["message" => "Kode sudah ada, gunakan kode lain!"]);
            exit;
        }
    
        if (!empty($_FILES['cfileimage']['name'])) {
            $target_dir = "uploads/";
    
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
    
            $ext = pathinfo($_FILES["cfileimage"]["name"], PATHINFO_EXTENSION);
            $file_name = "Foto" . time() . "." . strtolower($ext); 
            $new_filename = $target_dir . $file_name;
    
            if (move_uploaded_file($_FILES["cfileimage"]["tmp_name"], $new_filename)) {
                $target_file = url("/admin/" . $new_filename);
            } else {
                echo json_encode(["message" => "Error: Gagal mengunggah foto baru!"]);
                exit;
            }
        } else {
            $target_file = ''; 
        }
    
        $query = "INSERT INTO tbreward (ckode, cnama, npoin, cfileimage) VALUES (?, ?, ?, ?)";
    
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssis", $ckode, $cnama, $npoin, $target_file);
    
        if ($stmt->execute()) {
            echo "created";  
            exit;
        } else {
            echo json_encode(["message" => "Error: Gagal menambah data!"]);
            exit;
        }
    
        $stmt->close();
    }
    
    if (isset($_POST['reject'])) {
        $ckode = $_POST['ckode'];
        $cnama = $_POST['cnama'];
        $npoin = $_POST['npoin'];
    
        $sql_foto = "SELECT cnama, cfileimage FROM tbreward WHERE ckode = ?";
        $stmt_foto = $conn->prepare($sql_foto);
        $stmt_foto->bind_param("s", $ckode);
        $stmt_foto->execute();
        $result_foto = $stmt_foto->get_result();
        $foto_lama = '';
    
        if ($row = $result_foto->fetch_assoc()) {
            $old_cnama = $row['cnama'];
            $foto_lama = $row['cfileimage'];
        } else {
            echo json_encode(["message" => "Data tidak ditemukan untuk kode tersebut!"]);
            exit;
        }
        $stmt_foto->close();
    
        if ($cnama != $old_cnama) {
            $sql_check_cnama = "SELECT cnama FROM tbreward WHERE cnama = ? AND ckode != ?";
            $stmt_check_cnama = $conn->prepare($sql_check_cnama);
            $stmt_check_cnama->bind_param("ss", $cnama, $ckode);
            $stmt_check_cnama->execute();
            $result_check_cnama = $stmt_check_cnama->get_result();
    
            if ($result_check_cnama->num_rows > 0) {
                echo json_encode(["message" => "Nama sudah digunakan, silakan pilih nama lain!"]);
                exit;
            }
    
            $stmt_check_cnama->close();
        }
    
        if (!empty($_FILES['cfileimage']['name'])) {
            $target_dir = "uploads/";
    
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
    
            $ext = pathinfo($_FILES["cfileimage"]["name"], PATHINFO_EXTENSION);
            $file_name = "Foto" . $ckode . "." . strtolower($ext);
            $new_filename = $target_dir . $file_name;
    
            if (move_uploaded_file($_FILES["cfileimage"]["tmp_name"], $new_filename)) {
                $target_file = url("/admin/" . $new_filename);
            } else {
                echo json_encode(["message" => "Error: Gagal mengunggah foto baru!"]);
                exit;
            }
    
            if (!empty($foto_lama)) {
                $old_file_path = str_replace(url("/admin/"), "", $foto_lama);
                if (file_exists($old_file_path)) {
                    unlink($old_file_path);
                }
            }
        } else {
            $target_file = $foto_lama;
        }
    
        $query = "UPDATE tbreward SET cnama = ?, npoin = ?, cfileimage = ? WHERE ckode = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("siss", $cnama, $npoin, $target_file, $ckode);
    
        if ($stmt->execute()) {
            echo "delete";
            exit;
        } else {
            echo json_encode(["message" => "Error: Gagal memperbarui data!"]);
            exit;
        }
    
        $stmt->close();
    }

    
    
    if (isset($_POST['delete'])) {
        $ckode = $_POST['ckode'];  
    
        $query = "SELECT cfileimage FROM tbreward WHERE ckode = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $ckode);
        $stmt->execute();
        $result = $stmt->get_result();
    
        if ($row = $result->fetch_assoc()) {
            $foto_lama = $row['cfileimage'];
        }
        $stmt->close();
    
        if (!empty($foto_lama) && file_exists($foto_lama)) {
            unlink($foto_lama); 
        }
    
        $query = "DELETE FROM tbreward WHERE ckode = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $ckode);
    
        if ($stmt->execute()) {
            echo "deleted";  
            exit;

        } else {
            echo "Error: Gagal menghapus data!";
            exit;

        }
    
        $stmt->close();  
    }
    
}



$search_all = isset($_POST['search_all']) ? trim(mysqli_real_escape_string($conn, $_POST['search_all'])) : '';

$query = "SELECT * FROM tbreward WHERE 1=1";
$params = [];
$types = "";

if (!empty($search_all)) {
    $query .= " AND (ckode LIKE ? OR cnama LIKE ?) ";
    $params[] = "%{$search_all}%";
    $params[] = "%{$search_all}%";
    $types .= "ss";
}

$query .= " ORDER BY ckode DESC";


$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();


$conn->close();
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Halaman Reward</title>
    <meta content="width=device-width, initial-scale=1.0, shrink-to-fit=no" name="viewport" />
    <link rel="icon" href="../assets/img/sekolah/favicon6.ico" type="image/x-icon" />
    <script src="../assets/js/plugin/webfont/webfont.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        WebFont.load({
            google: { families: ["Public Sans:300,400,500,600,700"] },
            custom: {
                families: [
                    "Font Awesome 5 Solid",
                    "Font Awesome 5 Regular",
                    "Font Awesome 5 Brands",
                    "simple-line-icons",
                ],
                urls: ["../assets/css/fonts.min.css"],
            },
            active: function () {
                sessionStorage.fonts = true;
            },
        });
    </script>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css" />
    <link rel="stylesheet" href="../assets/css/plugins.min.css" />
    <link rel="stylesheet" href="../assets/css/kaiadmin.min.css" />
    <link rel="stylesheet" href="../assets/css/demo.css" />

</head>
<body>
    <div class="wrapper">
        <?php $menu = "infopromokoperasi"; require 'menu.php'; ?>
        <div class="main-panel">
            <?php require 'header.php'; ?>

            <div class="container">
                <div class="page-inner">
                    <div class="d-flex align-items-left align-items-md-center flex-column flex-md-row pt-2 pb-4">
                        <div class="page-header">
                            <h3 class="fw-bold mb-3">Halaman Reward</h3>
                            <ul class="breadcrumbs mb-3">
                                <li class="nav-home">
                                    <a href="<?= url("/admin"); ?>">
                                        <i class="icon-home"></i>
                                    </a>
                                </li>
                                <li class="separator">
                                    <i class="icon-arrow-right"></i>
                                </li>
                            </ul>
                        </div>
                    </div>

                    
                    <form method="POST" class="d-flex align-items-center w-100 justify-content-between">
                        <div class="form-group mr-2 flex-grow-1">
                            <input type="text" class="form-control" id="search_all" name="search_all" 
                                placeholder="Cari Kode / Nama " style="min-width: 200px;" 
                                value="<?= htmlspecialchars($search_all ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary" style="padding: 7px 20px; width: auto;">Cari</button>
                        </div>
                    </form>
                    <style>
                        .table thead th {
                            position: sticky;
                            top: 0;
                            background-color: #fff;
                            z-index: 1;
                            white-space: nowrap;
                        }
                        .table {
                            table-layout: auto;
                            width: 100%;
                            overflow-x: auto;
                        }
                        .table td, .table th {
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            overflow: hidden;
                        }
                        .table-responsive {
                            overflow-x: auto;
                            max-height: 400px;
                        }
                    </style>
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>no</th>
                                    <th>Kode</th>
                                    <th>Nama</th>
                                    <th>Point</th>
                                    <th>Image</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (mysqli_num_rows($result) > 0): ?>
                                    <?php $no = 1; while ($row = mysqli_fetch_assoc($result)): ?>
                                        <tr class="clickable-row"
                                            data-ckode="<?= $row['ckode'] ?>"
                                            data-cnama="<?= $row['cnama'] ?>"
                                            data-foto="<?= htmlspecialchars($row['cfileimage']) ?>"
                                            data-npoin="<?= $row['npoin'] ?>">
                                            <td><?= $no++ ?></td>
                                            <td><?= htmlspecialchars($row['ckode']) ?></td> 
                                            <td><?= htmlspecialchars($row['cnama']) ?></td> 
                                            <td><?= number_format($row['npoin'], 0, ',', '.') ?></td>
                                            <td><?php if (!empty($row['cfileimage'])): ?><a href="<?= htmlspecialchars($row['cfileimage']) ?>" target="_blank">Lihat Foto</a><?php endif; ?></td>
    
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center">Data tidak ditemukan</td> <!-- Update colspan untuk menyesuaikan dengan jumlah kolom -->
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>




                    <div class="form-container">
                        <form id="formAlat" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-12">
                                    
                                    <div class="form-group row">
                                        <label for="ckode" class="col-sm-3 col-form-label">Kode</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" id="ckode" name="ckode" placeholder="Masukkan kode">
                                        </div>
                                    </div>
                                    
                                    <div class="form-group row">
                                        <label for="cnama" class="col-sm-3 col-form-label">Nama</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" id="cnama" name="cnama" placeholder="Masukkan nama">
                                        </div>
                                    </div>
                                    
                                    <div class="form-group row">
                                        <label for="npoin" class="col-sm-3 col-form-label">Poin</label>
                                        <div class="col-sm-9">
                                            <input type="number" class="form-control" id="npoin" name="npoin" placeholder="Masukkan poin">
                                        </div>
                                    </div>
                                    

                                    <div class="form-group row">
                                        <label for="cfileimage" class="col-sm-3 col-form-label">Foto</label>
                                        <div class="col-sm-9">
                                            <input type="file" class="form-control" id="cfileimage" name="cfileimage" accept="image/*">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row mt-3">
                                <div class="col-12 text-center">
                                    <button type="submit" name="create" id="btn-create" class="btn btn-success" style="margin-right: 20px;">Buat</button>
                                    <button type="submit" name="edit" id="btn-edit" class="btn btn-warning" style="margin-right: 20px;">Edit</button>
                                    <button type="submit" name="delete" id="btn-delete" class="btn btn-danger" style="margin-right: 20px;">Hapus</button>
                                    <button type="reset" name="cancel" id="btn-cancel" class="btn btn-secondary">Batal</button>
                                </div>
                            </div>
                        </form>
                    </div>

                </div>
            </div>
        </div>
    </div>
    <script src="../assets/js/core/jquery-3.7.1.min.js"></script>
    <script src="../assets/js/core/popper.min.js"></script>
    <script src="../assets/js/core/bootstrap.min.js"></script>
    <script src="../assets/js/plugin/jquery-scrollbar/jquery.scrollbar.min.js"></script>
    <script src="../assets/js/plugin/chart.js/chart.min.js"></script>
    <script src="../assets/js/plugin/jquery.sparkline/jquery.sparkline.min.js"></script>
    <script src="../assets/js/plugin/chart-circle/circles.min.js"></script>
    <script src="../assets/js/plugin/datatables/datatables.min.js"></script>
    <script src="../assets/js/plugin/bootstrap-notify/bootstrap-notify.min.js"></script>
    <script src="../assets/js/plugin/jsvectormap/jsvectormap.min.js"></script>
    <script src="../assets/js/plugin/jsvectormap/world.js"></script>
    <script src="../assets/js/plugin/sweetalert/sweetalert.min.js"></script>
    <script src="../assets/js/main.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">



    <script>
    document.addEventListener("DOMContentLoaded", function () {
        const closeMenuLinks = document.querySelectorAll(".close-menu");

        closeMenuLinks.forEach(link => {
        link.addEventListener("click", function () {
            const collapseElement = document.getElementById("dataMaster");
            if (collapseElement) {
            const bsCollapse = new bootstrap.Collapse(collapseElement, {
                toggle: true 
            });
            }
        });
        });
    });
    </script>

    <script>
        
        $(document).ready(function () {

            var currentckode = null;
            $("#btn-edit").hide();
            $("#btn-delete").hide();
            $("#btn-cancel").show();

            $(document).on("click", ".clickable-row", function () {
                var ckode = $(this).data("ckode");
                var cnama = $(this).data("cnama");
                var cfileimage = $(this).data("foto");
                var npoin = $(this).data("npoin");
            
                $("#ckode").val(ckode); 
                $("#cnama").val(cnama);
                $("#npoin").val(npoin);
            
                if (cfileimage) {
                    $("#cfileimage").next(".file-name").text(cfileimage); 
                }
                
                $("#ckode").prop("disabled", true); 
                 
                $("#btn-create").hide();
                $("#btn-edit").show();
                $("#btn-delete").show();
                $("#btn-cancel").show();
            });
            
            $("#btn-cancel").on("click", function () {
                $("#ckode").val("");
                $("#cnama").val("");
                $("#npoin").val("");
                $("#cfileimage").val("");
                
                $("#ckode").prop("disabled", false);
    

                $("#btn-create").show();
                $("#btn-edit").hide();
                $("#btn-delete").hide();

                $("#formAlat")[0].reset();
            });

 

            $("#btn-edit").click(function (e) {
                e.preventDefault();

                var ckode = $("#ckode").val();
                var cnama = $("#cnama").val();
                var npoin = $("#npoin").val();
                var cfileimage = $("#cfileimage")[0].files[0];
            
                if (!ckode || !cnama || !npoin) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Semua kolom wajib diisi!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                if (isNaN(npoin)) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Poin harus berupa angka!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                if (npoin % 1 !== 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Poin harus berupa angka bulat!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                var formData = new FormData();
                formData.append("reject", true);
                formData.append("ckode", ckode);
                formData.append("cnama", cnama);
                formData.append("npoin", npoin);
 
                
                if (cfileimage) {
                    var allowedTypes = ["image/png", "image/jpg", "image/jpeg"];
                    
                    if (!allowedTypes.includes(cfileimage.type)) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal! ',
                            text: 'Hanya file PNG, JPG, atau JPEG yang diperbolehkan!',
                        });
                        return;
                    }

                    if (cfileimage.size > 2 * 1024 * 1024) {
                        Swal.fire({
                            icon: 'warning',
                            title: 'Peringatan!',
                            text: 'Ukuran gambar terlalu besar! Akan dikompresi...',
                        });
                        compressImage(cfileimage, function (compressedFile) {
                            if (compressedFile.size > 2 * 1024 * 1024) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Gagal! ',
                                    text: 'Gambar masih terlalu besar setelah kompresi. Pilih gambar lain!',
                                });
                                return;
                            }
                            formData.append("cfileimage", compressedFile);
                            sendDataedit(formData);
                        });
                    } else {
                        formData.append("cfileimage", cfileimage);
                        sendDataedit(formData);
                    }
                } else {
                    sendDataedit(formData);
                }
            });

            function compressImage(file, callback) {
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function (event) {
                    var img = new Image();
                    img.src = event.target.result;
                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        var ctx = canvas.getContext("2d");

                        var maxWidth = 800;
                        var maxHeight = 800;
                        var width = img.width;
                        var height = img.height;

                        if (width > maxWidth || height > maxHeight) {
                            if (width > height) {
                                height *= maxWidth / width;
                                width = maxWidth;
                            } else {
                                width *= maxHeight / height;
                                height = maxHeight;
                            }
                        }

                        canvas.width = width;
                        canvas.height = height;
                        ctx.drawImage(img, 0, 0, width, height);

                        canvas.toBlob(function (blob) {
                            callback(new File([blob], file.name, { type: "image/jpeg", lastModified: Date.now() }));
                        }, "image/jpeg", 0.6);
                    };
                };
            }

            function sendDataedit(formData) {
                Swal.fire({
                    title: "Konfirmasi",
                    text: "Apakah Anda yakin dengan data yang Anda inputkan?",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya, Simpan!",
                    cancelButtonText: "Batal"
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: '',
                            type: 'POST',
                            data: formData,
                            contentType: false,
                            processData: false,
                            success: function (response) {
                                if (response.trim() === 'delete') {
                                    Swal.fire({
                                        icon: 'success',
                                        title: 'Berhasil!',
                                        text: 'Data berhasil diperbarui!',
                                        timer: 3000,
                                        showConfirmButton: false,
                                    }).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    var message = response.message || response; // Mengambil pesan error
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal!',
                            text: message,  // Menampilkan pesan error tanpa format JSON
                        });
                                    console.log("Terjadi kesalahan, response:", response);
                                }
                            },
                            error: function (xhr, status, error) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error!',
                                    text: 'Terjadi kesalahan saat memproses data. Silakan coba lagi.',
                                });
                                console.log("AJAX Error:", error);
                            }
                        });
                    }
                });
            }


            $("#btn-create").click(function (e) {
                e.preventDefault();

                var ckode = $("#ckode").val();
                var cnama = $("#cnama").val();
                var npoin = $("#npoin").val();
                var cfileimage = $("#cfileimage")[0].files[0];
            
                if (!ckode || !cnama || !npoin) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Semua kolom wajib diisi!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                if (isNaN(npoin)) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Poin harus berupa angka!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                if (npoin % 1 !== 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Poin harus berupa angka bulat!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                var formData = new FormData();
                formData.append("create", true);
                formData.append("ckode", ckode);
                formData.append("cnama", cnama);
                formData.append("npoin", npoin);

                if (cfileimage) {
                    var allowedTypes = ["image/png", "image/jpg", "image/jpeg"];
                    
                    if (!allowedTypes.includes(cfileimage.type)) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal! ',
                            text: 'Hanya file PNG, JPG, atau JPEG yang diperbolehkan!',
                        });
                        return;
                    }

                    if (cfileimage.size > 2 * 1024 * 1024) {
                        Swal.fire({
                            icon: 'warning',
                            title: 'Peringatan!',
                            text: 'Ukuran gambar terlalu besar! Akan dikompresi...',
                        });
                        compressImage(cfileimage, function (compressedFile) {
                            if (compressedFile.size > 2 * 1024 * 1024) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Gagal! ',
                                    text: 'Gambar masih terlalu besar setelah kompresi. Pilih gambar lain!',
                                });
                                return;
                            }
                            formData.append("cfileimage", compressedFile);
                            sendData(formData);
                        });
                    } else {
                        formData.append("cfileimage", cfileimage);
                        sendData(formData);
                    }
                } else {
                    sendData(formData);
                }
            });


            function sendData(formData) {
                Swal.fire({
                    title: "Konfirmasi",
                    text: "Apakah Anda yakin dengan data yang Anda inputkan?",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya, Simpan!",
                    cancelButtonText: "Batal"
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: '',
                            type: 'POST',
                            data: formData,
                            contentType: false,
                            processData: false,
                            success: function (response) {
                                if (response.trim() === 'created') {
                                    Swal.fire({
                                        icon: 'success',
                                        title: 'Berhasil!',
                                        text: 'Data berhasil diperbarui!',
                                        timer: 3000,
                                        showConfirmButton: false,
                                    }).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Gagal!',
                                        text: 'Terjadi kesalahan, response: ' + response,
                                    });
                                    console.log("Terjadi kesalahan, response:", response);
                                }
                            },
                            error: function (xhr, status, error) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error!',
                                    text: 'Terjadi kesalahan saat memproses data. Silakan coba lagi.',
                                });
                                console.log("AJAX Error:", error);
                            }
                        });
                    }
                });
            }

        

        $("#btn-delete").click(function (e) {
            e.preventDefault();

            var ckode = $("#ckode").val();

            if (!ckode) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Peringatan!',
                    text: 'Pilih data yang ingin dihapus!',
                    timer: 3000,
                    showConfirmButton: false,
                });
                return;
            }

            Swal.fire({
                icon: 'warning',
                title: 'Apakah Anda yakin?',
                text: 'Data ini akan dihapus!',
                showCancelButton: true,
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '',
                        type: 'POST',
                        data: { delete: true, ckode: ckode },
                        success: function (response) {
                            response = response.trim();
                            if (response === "deleted") {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Berhasil!',
                                    text: 'Data berhasil dihapus!',
                                    timer: 3000,
                                    showConfirmButton: false,
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Gagal!',
                                    text: 'Terjadi kesalahan, response: ' + response,
                                });
                                console.log("Error Response:", response);
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error!',
                                text: 'Terjadi kesalahan saat memproses data. Silakan coba lagi.',
                            });
                            console.log("AJAX Error:", status, error, xhr.responseText);
                        }
                    });
                }
            });
        });

    });
    </script>



</body>
</html>
