<?php
require 'auth.php';
include 'koneksi.php';


// Pastikan koneksi database
if ($conn->connect_error) {
    error_log("Koneksi gagal: " . $conn->connect_error);
    echo json_encode(['status' => 'error', 'message' => 'Gagal terhubung ke database']);
    exit();
}

// Ambil data dari database
$sql = "SELECT * FROM inventaris";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Inventaris Barang</title>

    <!-- AdminLTE 3.2.0 -->
    <link rel="stylesheet" href="adminlte/plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="adminlte/dist/css/adminlte.min.css">
    <link rel="stylesheet" href="adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="adminlte/plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
    <link rel="stylesheet" href="adminlte/plugins/datatables-buttons/css/buttons.bootstrap4.min.css">

    <!-- jQuery -->
    <script src="adminlte/plugins/jquery/jquery.min.js"></script>
    <!-- Bootstrap 4 -->
    <script src="adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- AdminLTE -->
    <script src="adminlte/dist/js/adminlte.min.js"></script>

    <!-- Custom CSS -->
    <style>
        /* Styling for Global Netz in Navbar */
        .company-name {
            font-size: 1.5rem;
            font-weight: bold;
            color: #ffffff;
            padding: 10px 15px;
            background: linear-gradient(to right, #4e54c8, #8f94fb);
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease-in-out;
        }

        .company-name:hover {
            transform: scale(1.05);
        }

        /* Styling for Halaman Kelola Barang Header */
        .content-header {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .content-header h1 {
            color: #ffffff;
            font-size: 2rem;
            font-weight: bold;
        }

        .content-header h2 {
            color: #ffffff;
            font-size: 1.2rem;
            margin-top: 10px;
        }

        /* Card Styling for Daftar Barang */
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border: none;
        }

        .card-header {
            background: linear-gradient(to right, #ff9966, #ff5e62);
            color: #ffffff;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
        }

        .table th, .table td {
            text-align: center;
            vertical-align: middle;
        }

        .table img {
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }
    </style>

    <!-- Konfirmasi Logout -->
    <script>
        function confirmLogout(event) {
            event.preventDefault();
            var confirmAction = confirm("Apakah Anda yakin ingin logout?");
            if (confirmAction) {
                window.location.href = event.target.href;
            }
        }

        function openEditModal(rfid_barang) {
            $.ajax({
                url: 'edit_barang.php',
                type: 'GET',
                data: { rfid_barang: rfid_barang },
                success: function(data) {
                    $('#editModalBody').html(data);
                    $('#editModal').modal('show');
                },
                error: function() {
                    alert('Terjadi kesalahan saat memuat data.');
                }
            });
        }

        $(document).ready(function() {
    // Fokus otomatis pada elemen input RFID saat halaman dimuat
    $('#rfidInput').focus();

    // Variabel untuk mencegah pemrosesan ganda
    let isProcessing = false;

    // Fungsi debounce untuk menangani pemanggilan fungsi yang berulang
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }

    // Event listener untuk input RFID menggunakan debounce
    $('#rfidInput').on('keyup', debounce(function(event) {
        handleRFIDInput(event);
    }, 300));

    // Fungsi untuk menangani input RFID
    function handleRFIDInput(event) {
        var rfid_code = event.target.value.trim();
        if (rfid_code.length > 0 && !isProcessing) {
            isProcessing = true; // Menandakan pemrosesan sedang berlangsung
            $.ajax({
                url: 'proses_scan_rfid.php',
                type: 'POST',
                data: { rfid_code: rfid_code },
                success: function(response) {
                    try {
                        var data = JSON.parse(response);
                        if (data.status === 'success') {
                            Swal.fire({
                                icon: 'success',
                                title: 'Scan Berhasil!',
                                text: data.message,
                            }).then(() => {
                                $('#rfidInput').val('');
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Kesalahan',
                                text: data.message,
                            }).then(() => {
                                $('#rfidInput').val('');
                                $('#rfidInput').focus();
                            });
                        }
                    } catch (e) {
                        console.error("Parsing error:", e, response);
                        Swal.fire({
                            icon: 'error',
                            title: 'Kesalahan',
                            text: 'Terjadi kesalahan pada server. Cek log console untuk detail.',
                        }).then(() => {
                            $('#rfidInput').val('');
                            $('#rfidInput').focus();
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Request error:", status, error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Kesalahan',
                        text: 'Tidak dapat menghubungi server.',
                    }).then(() => {
                        $('#rfidInput').val('');
                        $('#rfidInput').focus();
                    });
                },
                complete: function() {
                    isProcessing = false; // Reset status pemrosesan
                }
            });
        }
    }

    // Fokus kembali ke elemen input RFID jika jendela browser kembali aktif
    $(window).on('focus', function() {
        $('#rfidInput').focus();
    });
});

    </script>
</head>
<body class="hold-transition sidebar-mini">
<input type="text" id="rfidInput" style="position:absolute; top:-1000px;" autofocus>
<div class="wrapper">

    <!-- Navbar -->
    <nav class="main-header navbar navbar-expand navbar-white navbar-light">
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
            </li>
        </ul>

        <span class="navbar-right company-name">
            Global Netz
        </span>
    </nav>

    <!-- Main Sidebar Container -->
    <aside class="main-sidebar sidebar-dark-primary elevation-4">
        <div class="sidebar">
            <nav class="mt-2">
                <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
                    <li class="nav-item">
                        <a href="#" class="nav-link">
                            <i class="nav-icon fas fa-user"></i>
                            <p>Dashboard</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="tambah_barang.php" class="nav-link">
                            <i class="nav-icon fas fa-plus"></i>
                            <p>Tambah Barang</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="laporan_barang.php" class="nav-link">
                            <i class="nav-icon fas fa-clipboard-list"></i>
                            <p>Laporan Barang</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="riwayat_barang.php" class="nav-link">
                            <i class="nav-icon fas fa-history"></i>
                            <p>Riwayat Barang</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="logout.php" class="nav-link" onclick="confirmLogout(event)">
                            <i class="nav-icon fas fa-sign-out-alt"></i>
                            <p>Logout</p>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </aside>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <section class="content">
            <div class="container-fluid">
                <div class="content-header">
                    <h1>Halaman Kelola Barang</h1>
                    <h2>Selamat Datang <?php echo htmlspecialchars($_SESSION['username']); ?>!</h2>
                </div>
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Daftar Barang</h3>
                    </div>
                    <div class="card-body">
                        <table id="example1" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>RFID Barang</th>
                                    <th>Nama Barang</th>
                                    <th>Jumlah Barang</th>
                                    <th>Status Barang</th>
                                    <th>Tanggal</th>
                                    <th>Foto</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if (isset($result) && $result->num_rows > 0) {
                                    while ($row = $result->fetch_assoc()) {
                                        echo "<tr>
                                                <td>".htmlspecialchars($row['rfid_barang'])."</td>
                                                <td>".htmlspecialchars($row['nama_barang'])."</td>
                                                <td>".htmlspecialchars($row['jumlah_barang'])."</td>
                                                <td>".htmlspecialchars($row['status_barang'])."</td>
                                                <td>".htmlspecialchars($row['date'])."</td>
                                                <td><img src='".htmlspecialchars($row['foto'])."' width='100'></td>
                                                <td>
                                                    <button class='btn btn-sm btn-warning' onclick=\"openEditModal('".htmlspecialchars($row['rfid_barang'])."')\">Edit</button>
                                                    <a href='proses_hapus.php?rfid_barang=".urlencode($row['rfid_barang'])."' class='btn btn-sm btn-danger' onclick=\"return confirm('Apakah Anda yakin ingin menghapus barang ini?')\">Hapus</a>
                                                </td>
                                              </tr>";
                                    }
                                } else {
                                    echo "<tr><td colspan='8'>Tidak ada barang yang terdaftar.</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- Footer -->
    <footer class="main-footer">
        <strong>Copyright &copy; 2023 <a href="#">Global Netz</a>.</strong> All rights reserved.
    </footer>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editModalLabel">Edit 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" id="editModalBody">
                <!-- Form edit akan dimuat di sini oleh AJAX -->
            </div>
        </div>
    </div>
</div>

<!-- DataTables -->
<script src="adminlte/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="adminlte/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="adminlte/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="adminlte/plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
</body>
</html>
