<?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'])) {
        $cGroup = $_POST['cgroup'];
        $cKeterangan1 = $_POST['cketerangan1'];
        $cKeterangan2 = $_POST['cketerangan2'];
        $cKeterangan3 = $_POST['cketerangan3'];
        $cnoid = $_POST['cnoid']; 
    
        $TanggalStart = isset($_POST['TanggalStart']) ? $_POST['TanggalStart'] : '';
        $TanggalEnd = isset($_POST['TanggalEnd']) ? $_POST['TanggalEnd'] : '';

        $sql_check_cnoid = "SELECT cnoid FROM tbfotohalutama WHERE cnoid = ?";
        $stmt_check_cnoid = $conn->prepare($sql_check_cnoid);
        $stmt_check_cnoid->bind_param("i", $cnoid);
        $stmt_check_cnoid->execute();
        $result_check_cnoid = $stmt_check_cnoid->get_result();
    
        if ($result_check_cnoid->num_rows > 0) {
            echo "Nomor urut yang Anda gunakan sudah ada";
            exit;
        }
    
        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 = "Foto" . time() . "." . 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;
            }
        } else {
            $target_file = ''; 
        }
    
        $query = "INSERT INTO tbfotohalutama (cgroup, cfoto, cketerangan1, cketerangan2, cketerangan3, cnoid, TanggalStart , TanggalEnd) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssssssss", $cGroup, $target_file, $cKeterangan1, $cKeterangan2, $cKeterangan3, $cnoid, $TanggalStart, $TanggalEnd);
    
        if ($stmt->execute()) {
            echo "created";  
            exit;
        } else {
            echo json_encode(["message" => "Error: Gagal menambah data!"]);
            exit;
        }
    
        $stmt->close();
    }
    
    if (isset($_POST['reject'])) {
        $cNomer = $_POST['cnomer'];
        $cGroup = $_POST['cgroup'];
        $cKeterangan1 = $_POST['cketerangan1'];
        $cKeterangan2 = $_POST['cketerangan2'];
        $cKeterangan3 = $_POST['cketerangan3'];
        $cnoid = $_POST['cnoid']; 
        $TanggalStart = isset($_POST['TanggalStart']) ? $_POST['TanggalStart'] : '';
        $TanggalEnd = isset($_POST['TanggalEnd']) ? $_POST['TanggalEnd'] : '';
        
        $sql_foto = "SELECT cnoid, cfoto FROM tbfotohalutama WHERE cnomer = ?";
        $stmt_foto = $conn->prepare($sql_foto);
        $stmt_foto->bind_param("i", $cNomer);
        $stmt_foto->execute();
        $result_foto = $stmt_foto->get_result();
        $foto_lama = '';
    
        if ($row = $result_foto->fetch_assoc()) {
            $old_cnoid = $row['cnoid'];
            $foto_lama = $row['cfoto'];
        }
        $stmt_foto->close();

        if ($cnoid != $old_cnoid) {
            $sql_check_cnoid = "SELECT cnoid FROM tbfotohalutama WHERE cnoid = ?";
            $stmt_check_cnoid = $conn->prepare($sql_check_cnoid);
            $stmt_check_cnoid->bind_param("i", $cnoid);
            $stmt_check_cnoid->execute();
            $result_check_cnoid = $stmt_check_cnoid->get_result();
    
            if ($result_check_cnoid->num_rows > 0) {
                echo "Nomor urut yang Anda gunakan sudah ada";
                exit;
            }
    
            $stmt_check_cnoid->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 = "Foto" . $cNomer . "." . 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 tbfotohalutama SET 
                    cgroup = ?, 
                    cfoto = ?, 
                    cketerangan1 = ?, 
                    cketerangan2 = ?, 
                    cketerangan3 = ?,
                    cnoid = ?, TanggalStart = ?, TanggalEnd = ?
                WHERE cnomer = ?";
    
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssssssssi", $cGroup, $target_file, $cKeterangan1, $cKeterangan2, $cKeterangan3, $cnoid, $TanggalStart, $TanggalEnd, $cNomer);
    
        if ($stmt->execute()) {
            echo "delete";  
            exit;
        } else {
            echo json_encode(["message" => "Error: Gagal memperbarui data!"]);
            exit;
        }
    
        $stmt->close();
    }
    
    
    if (isset($_POST['delete'])) {
        $cNomer = $_POST['cnomer'];  
    
        $query = "SELECT cfoto FROM tbfotohalutama WHERE cnomer = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $cNomer);
        $stmt->execute();
        $result = $stmt->get_result();
    
        if ($row = $result->fetch_assoc()) {
            $foto_lama = $row['cfoto'];
        }
        $stmt->close();
    
        if (!empty($foto_lama) && file_exists($foto_lama)) {
            unlink($foto_lama); 
        }
    
        $query = "DELETE FROM tbfotohalutama WHERE cnomer = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $cNomer);
    
        if ($stmt->execute()) {
            echo "deleted";  
            exit;

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

        }
    
        $stmt->close();  
    }
    
}

$sql = "SELECT cnoid FROM tbfotohalutama";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();

$cnoid_used = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $cnoid_used[] = $row['cnoid'];
    }
}


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

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

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

$query .= " ORDER BY cnomer 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 Utama</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 Utama</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 " 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>Status</th>
                                    <th>Foto</th>
                                    <th>Judul</th>
                                    <th>Keterangan 2</th>
                                    <th>Keterangan 3</th>
                                    <th>No Urut</th> 
                                    <th>Mulai Tanggal</th>
                                    <th>Selesai Tanggal</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-cnomer="<?= $row['cnomer'] ?>"
                                        data-cnoid="<?= $row['cnoid'] ?>"
                                        data-group="<?= htmlspecialchars($row['cgroup']) ?>"
                                        data-foto="<?= htmlspecialchars($row['cfoto']) ?>"
                                        data-keterangan1="<?= htmlspecialchars($row['cketerangan1']) ?>"
                                        data-keterangan2="<?= htmlspecialchars($row['cketerangan2']) ?>"
                                        data-keterangan3="<?= htmlspecialchars($row['cketerangan3']) ?>"
                                        data-TanggalStart="<?= $row['TanggalStart'] ?>"
                                        data-TanggalEnd="<?= $row['TanggalEnd'] ?>">
                                        <td><?= $no++ ?></td>
                                        <td>
                                            <?= htmlspecialchars($row['cgroup']) == '1' ? 'Publish' : 'Privat'; ?>
                                        </td>

                                        <td><?php if (!empty($row['cfoto'])): ?><a href="<?= htmlspecialchars($row['cfoto']) ?>" target="_blank">Lihat Foto</a><?php endif; ?></td>
                                        
                                        <td>
                                            <?php
                                            $cketerangan1 = htmlspecialchars($row['cketerangan1']);
                                            $words1 = explode(' ', $cketerangan1); 
                                            if (count($words1) > 20) {
                                                echo implode(' ', array_slice($words1, 0, 20)) . '...';
                                            } else {
                                                echo $cketerangan1;
                                            }
                                            ?>
                                        </td>

                                        <td>
                                            <?php
                                            $cketerangan2 = htmlspecialchars($row['cketerangan2']);
                                            $words2 = explode(' ', $cketerangan2); 
                                            if (count($words2) > 20) {
                                                echo implode(' ', array_slice($words2, 0, 20)) . '...';
                                            } else {
                                                echo $cketerangan2;
                                            }
                                            ?>
                                        </td>

                                        <td>
                                            <?php
                                            $cketerangan3 = htmlspecialchars($row['cketerangan3']);
                                            $words3 = explode(' ', $cketerangan3); 
                                            if (count($words3) > 20) {
                                                echo implode(' ', array_slice($words3, 0, 20)) . '...';
                                            } else {
                                                echo $cketerangan3;
                                            }
                                            ?>
                                        </td>

                                        <td><?= htmlspecialchars($row['cnoid']) ?></td> 
                                        <td><?= $row['TanggalStart'] ?></td>
                                        <td><?= $row['TanggalEnd'] ?></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="cgroup" class="col-sm-3 col-form-label">Group</label>
                                        <div class="col-sm-9">
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="radio" name="cgroup" id="privat" value="0" required>
                                                <label class="form-check-label" for="privat">Privat</label>
                                            </div>
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="radio" name="cgroup" id="publish" value="1" required>
                                                <label class="form-check-label" for="publish">Publish</label>
                                            </div>
                                        </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 class="form-group row">
                                        <label for="cketerangan1" class="col-sm-3 col-form-label">Judul</label>
                                        <div class="col-sm-9">
                                            <textarea class="form-control" id="cketerangan1" name="cketerangan1" rows="3"></textarea>
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="cketerangan2" class="col-sm-3 col-form-label">Keterangan 2</label>
                                        <div class="col-sm-9">
                                            <textarea class="form-control" id="cketerangan2" name="cketerangan2" rows="3"></textarea>
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="cketerangan3" class="col-sm-3 col-form-label">Keterangan 3</label>
                                        <div class="col-sm-9">
                                            <textarea class="form-control" id="cketerangan3" name="cketerangan3" rows="3"></textarea>
                                        </div>
                                    </div>

                                    
                                    <div class="form-group row">
                                        <label for="cnoid" class="col-sm-3 col-form-label">No Urut</label>
                                        <div class="col-sm-9">
                                            <input type="number" class="form-control" id="cnoid" name="cnoid" min="10" max="99" placeholder="Masukkan No.Urut" />
                                        </div>
                                    </div>
                                    
                                    <div class="form-group row">
                                        <label for="TanggalStart" class="col-sm-3 col-form-label">Tanggal Mulai</label>
                                        <div class="col-sm-9">
                                            <input type="datetime-local" class="form-control" id="TanggalStart" name="TanggalStart" required>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group row">
                                        <label for="TanggalEnd" class="col-sm-3 col-form-label">Tanggal Selesai</label>
                                        <div class="col-sm-9">
                                            <input type="datetime-local" class="form-control" id="TanggalEnd" name="TanggalEnd" required>
                                        </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 currentCnomer = null;
            $("#btn-edit").hide();
            $("#btn-delete").hide();
            $("#btn-cancel").show();

            $(document).on("click", ".clickable-row", function () {
                var cNomer = $(this).data("cnomer");
                var cGroup = $(this).data("group");
                var cFoto = $(this).data("foto");
                var cKeterangan1 = $(this).data("keterangan1");
                var cKeterangan2 = $(this).data("keterangan2");
                var cKeterangan3 = $(this).data("keterangan3");
                var cnoid = $(this).data("cnoid"); 
                var TanggalStart = $(this).data("tanggalstart");
                var TanggalEnd = $(this).data("tanggalend");

                if (cGroup == "0") {
                    $("#privat").prop("checked", true); 
                } else if (cGroup == "1") {
                    $("#publish").prop("checked", true);
                }

                $("#cketerangan1").val(cKeterangan1);
                $("#cketerangan2").val(cKeterangan2);
                $("#cketerangan3").val(cKeterangan3);
                $("#cnomer").val(cNomer); 
                $("#cnoid").val(cnoid);
                
                $("#TanggalStart").val(TanggalStart); 
                $("#TanggalEnd").val(TanggalEnd);
                
                currentCnomer = cNomer;

                if (cFoto) {
                    $("#cfoto").next(".file-name").text(cFoto); 
                }

                $("#btn-create").hide();
                $("#btn-edit").show();
                $("#btn-delete").show();
                $("#btn-cancel").show();
            });
            
            $("#btn-cancel").on("click", function () {
                $("#cgroup").val("0"); 
                $("#cfoto").val(""); 
                $("#cketerangan1").val("");
                $("#cketerangan2").val("");
                $("#cketerangan3").val("");

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

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

 

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

                var cGroup = $("input[name='cgroup']:checked").val();
                var cNomer = currentCnomer;
                var cFoto = $("#cfoto")[0].files[0];
                var cKeterangan1 = $("#cketerangan1").val();
                var cKeterangan2 = $("#cketerangan2").val();
                var cKeterangan3 = $("#cketerangan3").val();
                var cnoid = $("#cnoid").val();
                var TanggalStart = $("#TanggalStart").val();  
                var TanggalEnd = $("#TanggalEnd").val();      


                if (!cGroup || !cKeterangan1 || !cKeterangan2 || !cnoid || !cKeterangan3) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Semua kolom wajib diisi!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }
                
                if (isNaN(cnoid)) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Nomor urut harus berupa angka!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;  
                }
                
                if (cnoid % 1 !== 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Nomor urut harus berupa angka bulat!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }
                
                if (cnoid > 100) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Nomor urut tidak boleh lebih dari 100!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }

                if (!TanggalStart) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Tanggal Mulai tidak boleh kosong!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                if (!TanggalEnd) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Tanggal Selesai tidak boleh kosong!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }

                var formData = new FormData();
                formData.append("reject", true);
                formData.append("cgroup", cGroup);
                formData.append("cnomer", cNomer);
                formData.append("cketerangan1", cKeterangan1);
                formData.append("cketerangan2", cKeterangan2);
                formData.append("cketerangan3", cKeterangan3);
                formData.append("cnoid", cnoid);
                formData.append("TanggalStart", TanggalStart); 
                formData.append("TanggalEnd", TanggalEnd);    
                
                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 {
                                    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 cGroup = $("input[name='cgroup']:checked").val();
                var cNomer = currentCnomer;
                var cFoto = $("#cfoto")[0].files[0];
                var cKeterangan1 = $("#cketerangan1").val();
                var cKeterangan2 = $("#cketerangan2").val();
                var cKeterangan3 = $("#cketerangan3").val();
                var cnoid = $("#cnoid").val();
                var TanggalStart = $("#TanggalStart").val();  
                var TanggalEnd = $("#TanggalEnd").val();     
                
                if (!cGroup || !cKeterangan1 || !cKeterangan2 || !cnoid || !cKeterangan3) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Semua kolom wajib diisi!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }
                
                if (isNaN(cnoid)) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Nomor urut harus berupa angka!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;  
                }
                
                if (cnoid % 1 !== 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Nomor urut harus berupa angka bulat!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }
                
                if (cnoid > 100) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Nomor urut tidak boleh lebih dari 100!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return; 
                }

                if (!TanggalStart) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Tanggal Mulai tidak boleh kosong!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
            
                if (!TanggalEnd) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Tanggal Selesai tidak boleh kosong!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }
                
                var formData = new FormData();
                formData.append("create", true);
                formData.append("cgroup", cGroup);
                formData.append("cnomer", cNomer);
                formData.append("cketerangan1", cKeterangan1);
                formData.append("cketerangan2", cKeterangan2);
                formData.append("cketerangan3", cKeterangan3);
                formData.append("cnoid", cnoid);
                formData.append("TanggalStart", TanggalStart); 
                formData.append("TanggalEnd", TanggalEnd); 

                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);
                            sendData(formData);
                        });
                    } else {
                        formData.append("cfoto", cFoto);
                        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) {
                                console.log(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 cNomer = currentCnomer;

            if (!cNomer) {
                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, cnomer: cNomer },
                        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>
