<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Set page title
$page_title = "Report Reservasi";

// Log activity
create_audit_log($conn, 'Report Reservasi Access', $it_id, 'it', 'IT user accessed reservasi report');

// Handle Excel Export
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    $export_type = isset($_GET['export_type']) ? $_GET['export_type'] : 'filtered';
    $filename_suffix = $export_type == 'full' ? 'Full_Report' : 'Filtered_Report';
    
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="Report_Reservasi_' . $filename_suffix . '_' . date('Y-m-d_H-i-s') . '.xls"');
    header('Cache-Control: max-age=0');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>No Reservasi</th>';
    echo '<th>Kode Barang</th>';
    echo '<th>Color Code</th>';
    echo '<th>Component</th>';
    echo '<th>Buyer</th>';
    echo '<th>collection_surabaya</th>';
    echo '<th>Peminjam</th>';
    echo '<th>Lokasi Asal</th>';
    echo '<th>Lokasi Tujuan</th>';
    echo '<th>Tanggal Transaksi</th>';
    echo '<th>Tanggal Pengembalian</th>';
    echo '<th>Tanggal Kembali</th>';
    echo '<th>Kondisi Kembali</th>';
    echo '<th>Status Waktu</th>';
    echo '</tr>';
    
    // Build export query based on type
    if ($export_type == 'full') {
        // Full report - no filters
        $export_query = "SELECT st.reservation_number, csi.kode_barang, mcp.code_color, cc.component_name,
                                b.nama_buyer, col.nama_collection_surabaya, bu.username as peminjam, 
                                ti.lokasi_asal, ti.lokasi_tujuan, st.tanggal_transaksi, 
                                st.tanggal_pengembalian, ti.tanggal_kembali, ti.kondisi_kembali, ti.status_waktu
                         FROM stock_transactions_surabaya st
                         JOIN transaction_items_surabaya ti ON st.id = ti.transaction_id
                         JOIN color_stock_items_surabaya csi ON ti.stock_item_id = csi.id
                         JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
                         JOIN color_components_surabaya cc ON csi.component_id = cc.id
                         JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
                         JOIN buyers_surabaya b ON mcp.buyer_id = b.id
                         JOIN collection_surabayas col ON mcp.collection_surabaya_id = col.id
                         WHERE st.status_peminjaman = 'Dikembalikan' AND ti.dikembalikan = 1
                         ORDER BY st.tanggal_transaksi DESC";
        $export_result = $conn->query($export_query);
    } else {
        // Filtered report - use same filters as display
        $date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
        $date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
        $peminjam_filter = isset($_GET['peminjam']) ? $_GET['peminjam'] : '';
        $color_filter = isset($_GET['color']) ? $_GET['color'] : '';
        $buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';
        
        $where_conditions = ["st.status_peminjaman = 'Dikembalikan'", "ti.dikembalikan = 1"];
        $export_params = [];
        $export_param_types = '';

        if (!empty($date_from)) {
            $where_conditions[] = "DATE(st.tanggal_transaksi) >= ?";
            $export_params[] = $date_from;
            $export_param_types .= 's';
        }

        if (!empty($date_to)) {
            $where_conditions[] = "DATE(st.tanggal_transaksi) <= ?";
            $export_params[] = $date_to;
            $export_param_types .= 's';
        }

        if (!empty($peminjam_filter)) {
            $where_conditions[] = "bu.username LIKE ?";
            $export_params[] = '%' . $peminjam_filter . '%';
            $export_param_types .= 's';
        }

        if (!empty($color_filter)) {
            $where_conditions[] = "mcp.code_color LIKE ?";
            $export_params[] = '%' . $color_filter . '%';
            $export_param_types .= 's';
        }

        if (!empty($buyer_filter)) {
            $where_conditions[] = "b.id = ?";
            $export_params[] = $buyer_filter;
            $export_param_types .= 'i';
        }

        $export_where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

        $export_query = "SELECT st.reservation_number, csi.kode_barang, mcp.code_color, cc.component_name,
                                b.nama_buyer, col.nama_collection_surabaya, bu.username as peminjam, 
                                ti.lokasi_asal, ti.lokasi_tujuan, st.tanggal_transaksi, 
                                st.tanggal_pengembalian, ti.tanggal_kembali, ti.kondisi_kembali, ti.status_waktu
                         FROM stock_transactions_surabaya st
                         JOIN transaction_items_surabaya ti ON st.id = ti.transaction_id
                         JOIN color_stock_items_surabaya csi ON ti.stock_item_id = csi.id
                         JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
                         JOIN color_components_surabaya cc ON csi.component_id = cc.id
                         JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
                         JOIN buyers_surabaya b ON mcp.buyer_id = b.id
                         JOIN collection_surabayas col ON mcp.collection_surabaya_id = col.id
                         $export_where_clause
                         ORDER BY st.tanggal_transaksi DESC";

        $export_stmt = $conn->prepare($export_query);
        if (!empty($export_params)) {
            $export_stmt->bind_param($export_param_types, ...$export_params);
        }
        $export_stmt->execute();
        $export_result = $export_stmt->get_result();
    }
    
    while ($row = $export_result->fetch_assoc()) {
        echo '<tr>';
        echo '<td>' . htmlspecialchars($row['reservation_number']) . '</td>';
        echo '<td>' . htmlspecialchars($row['kode_barang']) . '</td>';
        echo '<td>' . htmlspecialchars($row['code_color']) . '</td>';
        echo '<td>' . htmlspecialchars($row['component_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['nama_buyer']) . '</td>';
        echo '<td>' . htmlspecialchars($row['nama_collection_surabaya']) . '</td>';
        echo '<td>' . htmlspecialchars($row['peminjam']) . '</td>';
        echo '<td>' . htmlspecialchars($row['lokasi_asal']) . '</td>';
        echo '<td>' . htmlspecialchars($row['lokasi_tujuan']) . '</td>';
        echo '<td>' . ($row['tanggal_transaksi'] ? date('d/m/Y H:i', strtotime($row['tanggal_transaksi'])) : '-') . '</td>';
        echo '<td>' . ($row['tanggal_pengembalian'] ? date('d/m/Y H:i', strtotime($row['tanggal_pengembalian'])) : '-') . '</td>';
        echo '<td>' . ($row['tanggal_kembali'] ? date('d/m/Y H:i', strtotime($row['tanggal_kembali'])) : '-') . '</td>';
        echo '<td>' . htmlspecialchars($row['kondisi_kembali']) . '</td>';
        echo '<td>' . htmlspecialchars($row['status_waktu']) . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    exit();
}

// Filter parameters
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$peminjam_filter = isset($_GET['peminjam']) ? $_GET['peminjam'] : '';
$color_filter = isset($_GET['color']) ? $_GET['color'] : '';
$buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';

// Build query with filters
$where_conditions = ["st.status_peminjaman = 'Dikembalikan'", "ti.dikembalikan = 1"];
$params = [];
$param_types = '';

if (!empty($date_from)) {
    $where_conditions[] = "DATE(st.tanggal_transaksi) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(st.tanggal_transaksi) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

if (!empty($peminjam_filter)) {
    $where_conditions[] = "bu.username LIKE ?";
    $params[] = '%' . $peminjam_filter . '%';
    $param_types .= 's';
}

if (!empty($color_filter)) {
    $where_conditions[] = "mcp.code_color LIKE ?";
    $params[] = '%' . $color_filter . '%';
    $param_types .= 's';
}

if (!empty($buyer_filter)) {
    $where_conditions[] = "b.id = ?";
    $params[] = $buyer_filter;
    $param_types .= 'i';
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

$query = "SELECT st.reservation_number, csi.kode_barang, mcp.code_color, cc.component_name,
                 bu.username as peminjam, ti.lokasi_asal, ti.lokasi_tujuan,
                 st.tanggal_transaksi, st.tanggal_pengembalian, ti.tanggal_kembali,
                 ti.kondisi_kembali, ti.status_waktu, b.nama_buyer, col.nama_collection_surabaya
          FROM stock_transactions_surabaya st
          JOIN transaction_items_surabaya ti ON st.id = ti.transaction_id
          JOIN color_stock_items_surabaya csi ON ti.stock_item_id = csi.id
          JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
          JOIN color_components_surabaya cc ON csi.component_id = cc.id
          JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
          JOIN buyers_surabaya b ON mcp.buyer_id = b.id
          JOIN collection_surabayas col ON mcp.collection_surabaya_id = col.id
          $where_clause
          ORDER BY st.tanggal_transaksi DESC";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// Include header
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center">
            <div>
                <h2 class="text-2xl font-bold text-gray-800 mb-2">Report Reservasi</h2>
                <p class="text-gray-600">Laporan reservasi yang sudah selesai dan dikembalikan</p>
            </div>
            <div class="flex space-x-2">
                <div class="relative">
                    <button type="button" id="exportBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg transition duration-200 flex items-center">
                        <i class="fas fa-file-excel mr-2"></i>Export Excel
                        <i class="fas fa-chevron-down ml-2"></i>
                    </button>
                    <div id="exportMenu" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg z-10 border">
                        <div class="py-1">
                            <a href="?export=excel&export_type=filtered<?php echo !empty($_SERVER['QUERY_STRING']) ? '&' . str_replace(['export=excel&', 'export_type=filtered&', 'export_type=full&'], '', $_SERVER['QUERY_STRING']) : ''; ?>" 
                               class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                <i class="fas fa-filter mr-2"></i>Export Data Terfilter
                            </a>
                            <a href="?export=excel&export_type=full" 
                               class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                <i class="fas fa-database mr-2"></i>Export Full Report
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter Data</h3>
        <form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Buyer</label>
                <select name="buyer" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">Semua Buyer</option>
                    <?php
                    $buyer_query = "SELECT id, nama_buyer FROM buyers_surabaya ORDER BY nama_buyer";
                    $buyer_result = $conn->query($buyer_query);
                    while ($buyer_row = $buyer_result->fetch_assoc()) {
                        $selected = $buyer_filter == $buyer_row['id'] ? 'selected' : '';
                        echo '<option value="' . $buyer_row['id'] . '" ' . $selected . '>' . htmlspecialchars($buyer_row['nama_buyer']) . '</option>';
                    }
                    ?>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Tanggal Dari</label>
                <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Tanggal Sampai</label>
                <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Peminjam</label>
                <input type="text" name="peminjam" value="<?php echo htmlspecialchars($peminjam_filter); ?>" 
                       placeholder="Cari nama peminjam..." 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Color Code</label>
                <input type="text" name="color" value="<?php echo htmlspecialchars($color_filter); ?>" 
                       placeholder="Cari color code..." 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div class="md:col-span-5 flex space-x-2">
                <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition duration-200">
                    <i class="fas fa-filter mr-2"></i>Filter
                </button>
                <a href="report_reservasi.php" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-lg transition duration-200">
                    <i class="fas fa-refresh mr-2"></i>Reset
                </a>
            </div>
        </form>
    </div>

    <!-- Data Table -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full table-auto">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No Reservasi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color Code</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Peminjam</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Transaksi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Kembali</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kondisi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status Waktu</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if ($result->num_rows > 0): ?>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                    <?php echo htmlspecialchars($row['reservation_number']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['kode_barang']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['code_color']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['component_name']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <div class="flex items-center">
                                        <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
                                            <?php echo htmlspecialchars($row['nama_buyer']); ?>
                                        </span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['peminjam']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo htmlspecialchars($row['lokasi_asal']) . ' → ' . htmlspecialchars($row['lokasi_tujuan']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['tanggal_transaksi'] ? date('d/m/Y H:i', strtotime($row['tanggal_transaksi'])) : '-'; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['tanggal_kembali'] ? date('d/m/Y H:i', strtotime($row['tanggal_kembali'])) : '-'; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <?php
                                    $kondisi_class = '';
                                    switch($row['kondisi_kembali']) {
                                        case 'Baik':
                                            $kondisi_class = 'bg-green-100 text-green-800';
                                            break;
                                        case 'Rusak':
                                            $kondisi_class = 'bg-red-100 text-red-800';
                                            break;
                                        case 'Hilang':
                                            $kondisi_class = 'bg-purple-100 text-purple-800';
                                            break;
                                        default:
                                            $kondisi_class = 'bg-gray-100 text-gray-800';
                                    }
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $kondisi_class; ?>">
                                        <?php echo htmlspecialchars($row['kondisi_kembali']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <?php
                                    $status_class = '';
                                    switch($row['status_waktu']) {
                                        case 'tepat':
                                            $status_class = 'bg-green-100 text-green-800';
                                            $status_text = 'Tepat Waktu';
                                            break;
                                        case 'overdue':
                                            $status_class = 'bg-red-100 text-red-800';
                                            $status_text = 'Terlambat';
                                            break;
                                        default:
                                            $status_class = 'bg-gray-100 text-gray-800';
                                            $status_text = 'Normal';
                                    }
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $status_class; ?>">
                                        <?php echo $status_text; ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="11" class="px-6 py-4 text-center text-sm text-gray-500">
                                Tidak ada data reservasi yang ditemukan
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const exportBtn = document.getElementById('exportBtn');
    const exportMenu = document.getElementById('exportMenu');
    
    exportBtn.addEventListener('click', function() {
        exportMenu.classList.toggle('hidden');
    });
    
    // Close menu when clicking outside
    document.addEventListener('click', function(event) {
        if (!exportBtn.contains(event.target) && !exportMenu.contains(event.target)) {
            exportMenu.classList.add('hidden');
        }
    });
});
</script>

<?php include '../template_it/footer.php'; ?>