<?php
session_start();
include 'koneksi.php';

if (!isset($_SESSION['username'])) {
    header("Location: index.php");
    exit();
}

// Fungsi untuk mendapatkan awal dan akhir minggu dari bulan tertentu
function getStartAndEndDate($year, $month, $week) {
    $firstDayOfMonth = new DateTime("$year-$month-01");
    $dto = clone $firstDayOfMonth;
    $dto->modify('+' . ($week - 1) . ' weeks');
    $start = $dto->format('Y-m-d');
    $dto->modify('+6 days');
    $end = $dto->format('Y-m-d');
    return ['start' => max($start, $firstDayOfMonth->format('Y-m-d')), 'end' => min($end, $firstDayOfMonth->format('Y-m-t'))];
}

// Set nilai default untuk tahun, bulan, dan minggu
$year = isset($_GET['year']) ? $_GET['year'] : date('Y');
$month = isset($_GET['month']) ? $_GET['month'] : date('m');
$week = isset($_GET['week']) ? $_GET['week'] : 1;

// Dapatkan tanggal awal dan akhir untuk minggu yang dipilih dalam bulan tersebut
$dateRange = getStartAndEndDate($year, $month, $week);
$startDate = $dateRange['start'];
$endDate = $dateRange['end'];

// Mengambil data riwayat barang berdasarkan minggu, bulan, dan tahun yang dipilih
$sql = "SELECT r.*, i.nama_barang FROM riwayat_barang r 
        LEFT JOIN inventaris i ON r.rfid_barang = i.rfid_barang
        WHERE r.waktu_scan BETWEEN '$startDate' AND '$endDate'";
$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>Riwayat Barang</title>
    <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">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <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>
    </nav>

    <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="index.php" 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>
                </ul>
            </nav>
        </div>
    </aside>

    <div class="content-wrapper">
        <div class="container">
            <h2 class="text-center mt-4">Riwayat Barang</h2>

            <!-- Form filter berdasarkan tahun, bulan, dan minggu -->
            <form action="" method="GET" class="mt-4">
                <label for="year">Pilih Tahun:</label>
                <input type="number" name="year" id="year" min="2000" max="2100" value="<?php echo $year; ?>">
                
                <label for="month">Pilih Bulan:</label>
                <select name="month" id="month">
                    <?php
                    for ($m = 1; $m <= 12; $m++) {
                        $monthName = date('F', mktime(0, 0, 0, $m, 10));
                        echo "<option value='$m'".($m == $month ? ' selected' : '').">$monthName</option>";
                    }
                    ?>
                </select>

                <label for="week">Pilih Minggu:</label>
                <input type="number" name="week" id="week" min="1" max="5" value="<?php echo $week; ?>">
                <button type="submit" class="btn btn-primary">Filter</button>
            </form>

            <div class="card mt-4">
                <div class="card-header">
                    <h3 class="card-title">Riwayat Barang (Minggu ke-<?php echo $week; ?>, Bulan <?php echo $month; ?>, Tahun <?php echo $year; ?>)</h3>
                    <button id="generatePDF" class="btn btn-primary float-right">Download PDF</button>
                </div>
                <div class="card-body">
                    <table id="riwayatTable" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Nama Barang</th>
                                <th>RFID Barang</th>
                                <th>Status Awal</th>
                                <th>Status Baru</th>
                                <th>Waktu Scan</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    echo "<tr>
                                            <td>".$row['nama_barang']."</td>
                                            <td>".$row['rfid_barang']."</td>
                                            <td>".$row['status_awal']."</td>
                                            <td>".$row['status_baru']."</td>
                                            <td>".$row['waktu_scan']."</td>
                                            <td>
                                                <a href='hapus_riwayat.php?id=".$row['id']."' onclick='return confirm(\"Apakah Anda yakin ingin menghapus riwayat ini?\")' class='btn btn-danger btn-sm'>Hapus</a>
                                            </td>
                                          </tr>";
                                }
                            } else {
                                echo "<tr><td colspan='6'>Tidak ada riwayat perubahan status barang.</td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

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

<script src="adminlte/plugins/jquery/jquery.min.js"></script>
<script src="adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<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="adminlte/dist/js/adminlte.min.js"></script>

<script>
    $(function () {
        $('#riwayatTable').DataTable({
            "responsive": true,
            "lengthChange": true,
            "pageLength": 50,
            "language": {
                "lengthMenu": "Tampilkan _MENU_ entri",
                "info": "Menampilkan _START_ hingga _END_ dari _TOTAL_ entri",
                "infoEmpty": "Tidak ada entri yang tersedia",
                "infoFiltered": "(difilter dari _MAX_ total entri)",
                "zeroRecords": "Tidak ada entri yang ditemukan"
            }
        });
    });

    document.getElementById('generatePDF').addEventListener('click', function () {
    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF();

    // Draw the background rectangle first
    pdf.setFillColor(220, 220, 220); // Light gray background
    pdf.rect(75, 10, 60, 10, 'F'); // Adjust position and size as needed

    // Set styling for "Global Netz" title and add the text
    pdf.setFontSize(18);
    pdf.setTextColor(44, 62, 80); // Dark color for the text
    pdf.setFont("helvetica", "bold");
    pdf.text("Global Netz", 105, 17, { align: "center" }); // Adjust the Y-position to ensure it appears within the rectangle

    // Document title
    pdf.setFontSize(16);
    pdf.setTextColor(0, 0, 0); // Black color for text
    pdf.setFont("helvetica", "normal");
    pdf.text("Rekapan Mingguan Barang", 14, 30);

    // Week, month, and year information
    pdf.setFontSize(12);
    pdf.text("Minggu: <?php echo $week; ?>, Bulan: <?php echo $month; ?>, Tahun: <?php echo $year; ?>", 14, 40);

    // Add the table with the data
    pdf.autoTable({
        head: [['Nama Barang', 'RFID Barang', 'Status Awal', 'Status Baru', 'Waktu Scan']],
        body: Array.from(document.querySelectorAll('#riwayatTable tbody tr')).map(row => 
            Array.from(row.querySelectorAll('td')).map(cell => cell.innerText)
        ),
        startY: 50,
        theme: 'grid'
    });

    // Save the generated PDF with a dynamic filename
    pdf.save('Riwayat_Barang_Minggu_<?php echo $week; ?>_Bulan_<?php echo $month; ?>_Tahun_<?php echo $year; ?>.pdf');
});
</script>
</body>
</html>
