<?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['editbos'])) {
        $TanggalStart = isset($_POST['TanggalStart']) ? $_POST['TanggalStart'] : '';
        $TanggalEnd = isset($_POST['TanggalEnd']) ? $_POST['TanggalEnd'] : '';
        $status = isset($_POST['status']) ? $_POST['status'] : '';
    
    
        $query = "UPDATE tbbarangdiskonheader SET TanggalStart = ?, TanggalEnd = ?, status = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssi", $TanggalStart, $TanggalEnd, $status); 
    
        if ($stmt->execute()) {
            echo "editiki";
            exit;
        } else {
            echo json_encode(["message" => "Error: Gagal menyimpan data!"]);
            exit;
        }
    
        $stmt->close();
    }

    
    
    
   
    
    
}

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

$query_barang = "
    SELECT t.*
    FROM tbbarang t
    WHERE t.cKode NOT IN (SELECT cKode FROM tbbarangdiskon)
";

if (!empty($search_barang)) {
    $query_barang .= " AND (t.cKode LIKE '%$search_barang%' OR t.cNama LIKE '%$search_barang%')";
}

$query_barang .= " ORDER BY t.cKode ASC";
$query_barang .= !empty($search_barang) ? " LIMIT 25" : " LIMIT 50";

$stmt_barang = $conn->prepare($query_barang);
if (!$stmt_barang) {
    die("Prepare failed: " . $conn->error);
}

$stmt_barang->execute();
$result_barang = $stmt_barang->get_result();

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


$query = "
    SELECT TanggalStart, TanggalEnd, status
    FROM tbbarangdiskonheader t
    WHERE 1=1
";

$params = [];
$types = "";

$query .= " ORDER BY t.TanggalStart DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();





$conn->close();
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Jadwal Diskon</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 = "jadwaldiskon"; 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">Jadwal Diskon</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>

                    
                    
                    <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>TanggalStart</th>
                                    <th>TanggalEnd</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if (mysqli_num_rows($result) > 0): ?>
                                <?php while ($row = mysqli_fetch_assoc($result)): ?>
                                    <tr class="clickable-row"
                                        data-TanggalStart="<?= $row['TanggalStart'] ?>"
                                        data-TanggalEnd="<?= $row['TanggalEnd'] ?>"
                                        data-status="<?= $row['status'] ?>">
                                        <td><?= $row['TanggalStart'] ?></td>
                                        <td><?= $row['TanggalEnd'] ?></td>
                                        <td>
                                            <?= $row['status'] == '0.00' ? 'Privat' : ($row['status'] == '1.00' ? 'Publish' : ''); ?>
                                        </td>

                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3" class="text-center">Data tidak ditemukan</td> <!-- Update colspan to 3 -->
                                </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="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 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>
                            </div>

                            <div class="row mt-3">
                                <div class="col-12 text-center">
                                    
                                    <button type="submit" name="edit" id="btn-edit" class="btn btn-warning" style="margin-right: 20px;">Edit</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 () {

            var currentCnomer = null;
            $("#btn-edit").hide();
            $("#btn-cancel").hide();

            $("#btn-cancel").on("click", function () {
                $("#TanggalStart").val(""); 
                $("#TanggalEnd").val("");
            
                $("#status").val("0");

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

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

            });
 
            $(document).on("click", ".clickable-row", function () {
                var TanggalStart = $(this).data("tanggalstart");
                var TanggalEnd = $(this).data("tanggalend");
                var status = $(this).data("status");
                
                var statusInt = parseInt(status);
                
                if (statusInt === 0) {
                    $("#privat").prop("checked", true); 
                } else if (statusInt === 1) {
                    $("#publish").prop("checked", true);
                }

                
                $("#TanggalStart").val(TanggalStart); 
                $("#TanggalEnd").val(TanggalEnd);
                $("#status").val(statusInt);  
            
                $("#btn-create").hide();
                $("#btn-edit").show();
                $("#btn-delete").show();
                $("#btn-cancel").show();
            
                $(".form-group").has("button#toggleBtn").hide();
            });



            $("#btn-edit").click(function (e) {
                e.preventDefault();
            
                var TanggalStart = $("#TanggalStart").val();  
                var TanggalEnd = $("#TanggalEnd").val();      
                
                var status = $('input[name="cgroup"]:checked').val(); 
                
                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;
                }
            
                if (!status) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan!',
                        text: 'Status harus dipilih!',
                        timer: 3000,
                        showConfirmButton: false,
                    });
                    return;
                }

            
                var formData = new FormData();
                formData.append("editbos", true);
                formData.append("TanggalStart", TanggalStart); 
                formData.append("TanggalEnd", TanggalEnd);     
                formData.append("status", status);   
            
                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) {
                                response = response.trim();
                                if (response === 'editiki') {
                                    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("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>
