<?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['reject'])) {
        $cKode = isset($_POST['cKode']) ? $_POST['cKode'] : '';  
        $cNama = isset($_POST['cNama']) ? $_POST['cNama'] : '';  
        $cFoto = isset($_POST['cFoto']) ? $_POST['cFoto'] : '';  
    
        if (empty($cKode) || empty($cNama)) {
            echo json_encode(["message" => "Error: Kode Barang atau Nama Barang tidak boleh kosong!"]);
            exit;
        }
    
        $sql_foto = "SELECT cFileImage, cbarcode FROM tbbarang 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()) {
            $foto_lama = $row['cFileImage']; 
            $cbarcode = $row['cbarcode']; 
            $cbarcode = str_replace(' ', '', $cbarcode); 
        }
        $stmt_foto->close();
    
        if (!empty($_FILES['cfoto']['name'])) {
            $target_dir = "uploads/";
    
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
    
            $ext = pathinfo($_FILES["cfoto"]["name"], PATHINFO_EXTENSION);
            $file_name = $cbarcode . "." . strtolower($ext);   
            $new_filename = $target_dir . $file_name;
    
            if (move_uploaded_file($_FILES["cfoto"]["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) && file_exists($foto_lama)) {
                unlink($foto_lama);
            }
        } else {
            $target_file = $foto_lama;  
        }
    
        $query = "UPDATE tbbarang SET cFileImage = ? WHERE cKode = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ss", $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'];  
    
        $sql_foto = "SELECT cFileImage FROM tbbarang 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()) {
            $foto_lama = $row['cFileImage'];
        }
        $stmt_foto->close();
    
        // Update data menjadi kosong (null atau string kosong sesuai kebutuhan)
        $query = "UPDATE tbbarang SET cFileImage = '' WHERE cKode = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $cKode);

    
        if ($stmt->execute()) {
            echo "deleted"; 
            exit;
        } else {
            echo "Error: Gagal menghapus data!";  
            exit;
        }
    
        $stmt->close();  
    }
    
    
}

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

$query_barang = "SELECT cFileImage, t.* FROM tbbarang t
                WHERE t.cFileImage IS NULL OR t.cFileImage = ''";  // Updated query

if (!empty($search_barang)) {
    $query_barang .= " AND (LOWER(t.cNama) LIKE ? OR LOWER(t.cKode) LIKE ?)";
    $params_barang = ["%".strtolower($search_barang)."%", "%".strtolower($search_barang)."%"];
    $types_barang = "ss";
    $query_barang .= " LIMIT 25";
} else {
    $params_barang = [];
    $types_barang = "";
    $query_barang .= " LIMIT 50";
}

$stmt_barang = $conn->prepare($query_barang);
if (!empty($params_barang)) {
    $stmt_barang->bind_param($types_barang, ...$params_barang);
}
$stmt_barang->execute();
$result_barang = $stmt_barang->get_result();

$barangku = [];
if ($result_barang->num_rows > 0) {
    while ($row = $result_barang->fetch_assoc()) {
        $barangku[] = $row;
    }
}

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

$query = "SELECT cFileImage, t.* FROM tbbarang t WHERE 1=1 AND t.cFileImage IS NOT NULL AND t.cFileImage != ''";
$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";  

$query .= !empty($search_all) ? " LIMIT 25" : " LIMIT 50";  

$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 Upload Barang</title>
    <meta content="width=device-width, initial-scale=1.0, shrink-to-fit=no" name="viewport" />
    <link rel="icon" href="../assets/img/sekolah/favicon56.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 = "halamanuploadbarang"; 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 Upload Barang</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 Halaman" 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 Barang</th>
                                    <th>Nama Barang</th>
                                    <th>URL Foto</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-id="<?= $row['cKode'] ?>"
                                        data-nama="<?= $row['cNama'] ?>"
                                        data-cfileimage="<?= $row['cFileImage'] ?>">
                                        <td><?= $no++ ?></td>
                                        <td><?= htmlspecialchars($row['cKode']) ?></td>
                                        <td><?= htmlspecialchars($row['cNama']) ?></td>
                                        <td>
                                            <?php if (!empty($row['cFileImage'])): ?>
                                                <a href="<?= htmlspecialchars($row['cFileImage']) ?>" target="_blank">Lihat Foto</a>
                                            <?php else: ?>
                                                No Foto
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center">Data tidak ditemukan</td> <!-- Update colspan for the new columns -->
                                </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="cgroup" class="col-sm-3 col-form-label">Pilih Barang</label>
                                        <div class="col-sm-9">
                                            <button type="button" class="btn btn-secondary" id="toggleBtn">Buka Barang</button>
                                        </div>
                                    </div>

                                    <div class="modal fade" id="dialogModal" tabindex="-1" role="dialog" aria-labelledby="dialogModalLabel" aria-hidden="true">
                                        <div class="modal-dialog" role="document">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="dialogModalLabel">Pilihan Barang</h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="form-group">
                                                        <label for="searchText">Cari Barang</label>
                                                        <input type="text" class="form-control" id="searchText" placeholder="Masukkan nama barang">
                                                        <button type="button" class="btn btn-primary mt-2" id="searchBtn">Cari</button>
                                                    </div>

                                                    <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
                                                        <table class="table table-bordered mt-4" id="tableBarang">
                                                            <thead>
                                                                <tr>
                                                                    <th>No</th>
                                                                    <th>Nama Barang</th>
                                                                    <th>Harga</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody id="barangBody">
                                                                <?php if (!empty($barangku)): ?>
                                                                    <?php foreach ($barangku as $index => $item): ?>
                                                                        <tr class="clickable-row2" data-id="<?= $item['cKode'] ?>" data-nama="<?= $item['cNama'] ?>" data-harga="<?= $item['nHrgBeli'] ?>" data-cFileImage="<?= $item['cFileImage'] ?>">
                                                                            <td><?= $index + 1 ?></td>
                                                                            <td class="clickable-column" data-column="cNama"><?= $item['cNama'] ?></td>
                                                                            <td class="clickable-column" data-column="cFileImage" style="display:none;"><?= $item['cFileImage'] ?></td> <!-- Hide this column -->
                                                                            <td class="clickable-column" data-column="cKode"><?= $item['nHrgBeli'] ?></td>
                                                                        </tr>
                                                                    <?php endforeach; ?>
                                                                <?php else: ?>
                                                                    <tr>
                                                                        <td colspan="3" class="text-center">Data tidak ditemukan</td>
                                                                    </tr>
                                                                <?php endif; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                                
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="cKode" class="col-sm-3 col-form-label">Kode Barang</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" id="cKode" name="cKode" placeholder="Masukkan Kode Barang" required readonly>
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="cNama" class="col-sm-3 col-form-label">Nama Barang</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" id="cNama" name="cNama" placeholder="Masukkan Nama Barang" required readonly>
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="cfoto" class="col-sm-3 col-form-label">Foto</label>
                                        <div class="col-sm-9">
                                            <input type="file" class="form-control" id="cfoto" name="cfoto" 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 src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        $(document).ready(function () {
            $("#toggleBtn").click(function () {
                $("#dialogModal").modal('show');
            });

            $(".clickable-column").click(function () {
                var column = $(this).data('column');
                var itemRow = $(this).closest('tr');
                var cKode = itemRow.data('id');   
                var cNama = itemRow.data('nama'); 
                var cHarga = itemRow.data('harga'); 
                var cFileImage = itemRow.data('cfileimage');

                $("#dialogModal").modal('hide');
                $("#cKode").val(cKode);
                $("#cNama").val(cNama);
                $("#cFoto").val(cFileImage);
            });

            $("#searchBtn").click(function () {
                var searchText = $("#searchText").val().toLowerCase();

                $("#barangBody .clickable-row2").each(function () {
                    var itemName = $(this).find("td:eq(1)").text().toLowerCase(); 
                    if (itemName.includes(searchText)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });

            $("#searchText").keypress(function (e) {
                if (e.which == 13) {
                    e.preventDefault();
                    $("#searchBtn").click();
                }
            });
        });
    </script>


    <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 currentCnomer = null;
            $("#btn-edit").hide();
            $("#btn-delete").hide();
            $("#btn-cancel").show();

            $("#btn-cancel").on("click", function () {
                $("#cKode").val(""); 
                $("#cNama").val(""); 
                $("#cFoto").val(""); 
                $("#cketerangan1").val("");
                $("#cketerangan2").val("");
                $("#cketerangan3").val("");

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

                $("#formAlat")[0].reset();
                $(".form-group").has("button#toggleBtn").show();

            });
 
            $(document).on("click", ".clickable-row", function () {
                var cKode = $(this).data("id");
                var cNama = $(this).data("nama");
                var cFileImage = $(this).data("cfileimage");
                var cKeterangan1 = $(this).data("keterangan1");
                var cKeterangan2 = $(this).data("keterangan2");
                var cKeterangan3 = $(this).data("keterangan3");

                $("#cKode").val(cKode);
                $("#cNama").val(cNama);
                $("#cFoto").val(cFileImage);
                $("#cketerangan1").val(cKeterangan1);
                $("#cketerangan2").val(cKeterangan2);
                $("#cketerangan3").val(cKeterangan3);

                currentCnomer = cKode;

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

                $(".form-group").has("button#toggleBtn").hide();
            });


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

                var cKode = $("#cKode").val();
                var cNama = $("#cNama").val();
                var cFoto = $("#cfoto")[0].files[0];

                if (!cKode || !cNama || !cFoto) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Semua kolom wajib diisi!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }


                var formData = new FormData();
                formData.append("reject", true);
                formData.append("cKode", cKode);
                formData.append("cNama", cNama);

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

                    if (cFoto.size > 2 * 1024 * 1024) {
                        Swal.fire({
                            icon: 'warning',
                            title: 'Peringatan!',
                            text: 'Ukuran gambar terlalu besar! Akan dikompresi...',
                        });
                        compressImage(cFoto, 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("cfoto", compressedFile);
                            sendDataedit(formData);
                        });
                    } else {
                        formData.append("cfoto", cFoto);
                        sendDataedit(formData);
                    }
                } else {
                    sendDataedit(formData);
                }
            });

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

                var cKode = $("#cKode").val();
                var cNama = $("#cNama").val();
                var cFoto = $("#cfoto")[0].files[0];

                if (!cKode || !cNama || !cFoto) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Semua kolom wajib diisi!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }

                var formData = new FormData();
                formData.append("reject", true);
                formData.append("cKode", cKode);
                formData.append("cNama", cNama);

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

                    if (cFoto.size > 2 * 1024 * 1024) {
                        Swal.fire({
                            icon: 'warning',
                            title: 'Peringatan!',
                            text: 'Ukuran gambar terlalu besar! Akan dikompresi...',
                        });
                        compressImage(cFoto, 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("cfoto", compressedFile);
                            sendDataedit(formData);
                        });
                    } else {
                        formData.append("cfoto", cFoto);
                        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 {
                                    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>
