<?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 Dipinjam";

// Log activity
create_audit_log($conn, 'Report Dipinjam Access', $it_id, 'it', 'IT user accessed dipinjam 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_Dipinjam_' . $filename_suffix . '_' . date('Y-m-d_H-i-s') . '.xls"');
    header('Cache-Control: max-age=0');
    
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>Kode Barang</th>';
    echo '<th>Color Code</th>';
    echo '<th>Component</th>';
    echo '<th>Buyer</th>';
    echo '<th>Collection</th>';
    echo '<th>Total Dipinjam</th>';
    echo '<th>Sering Dipinjam Oleh</th>';
    echo '<th>Terakhir Dipinjam</th>';
    echo '</tr>';
    
    // Build export query based on type
    if ($export_type == 'full') {
        // Full report - no filters, no limit
        $export_query = "SELECT csi.kode_barang, mcp.code_color, cc.component_name,
                                b.nama_buyer, col.nama_collection, COUNT(ti.id) as total_borrowed,
                                GROUP_CONCAT(DISTINCT bu.username ORDER BY bu.username SEPARATOR ', ') as borrowers,
                                MAX(st.tanggal_transaksi) as last_borrowed
                         FROM color_stock_items csi
                         JOIN master_color_panel mcp ON csi.color_id = mcp.id
                         JOIN color_components cc ON csi.component_id = cc.id
                         JOIN buyers b ON mcp.buyer_id = b.id
                         JOIN collections col ON mcp.collection_id = col.id
                         JOIN transaction_items ti ON csi.id = ti.stock_item_id
                         JOIN stock_transactions st ON ti.transaction_id = st.id
                         JOIN borrower_users bu ON st.borrower_id = bu.id
                         WHERE st.status IN ('Disetujui', 'OnProccesing') OR st.status_peminjaman = 'Dikembalikan'
                         GROUP BY csi.id, csi.kode_barang, mcp.code_color, cc.component_name, b.nama_buyer, col.nama_collection
                         ORDER BY total_borrowed DESC, last_borrowed DESC";
        $export_result = $conn->query($export_query);
    } else {
        // Filtered report - use same filters as display
        $buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';
        $where_conditions = ["(st.status IN ('Disetujui', 'OnProccesing') OR st.status_peminjaman = 'Dikembalikan')"];
        $export_params = [];
        $export_param_types = '';

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

        if (!empty($component_filter)) {
            $where_conditions[] = "cc.component_name LIKE ?";
            $export_params[] = '%' . $component_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 csi.kode_barang, mcp.code_color, cc.component_name,
                                b.nama_buyer, col.nama_collection, COUNT(ti.id) as total_borrowed,
                                GROUP_CONCAT(DISTINCT bu.username ORDER BY bu.username SEPARATOR ', ') as borrowers,
                                MAX(st.tanggal_transaksi) as last_borrowed
                         FROM color_stock_items csi
                         JOIN master_color_panel mcp ON csi.color_id = mcp.id
                         JOIN color_components cc ON csi.component_id = cc.id
                         JOIN buyers b ON mcp.buyer_id = b.id
                         JOIN collections col ON mcp.collection_id = col.id
                         JOIN transaction_items ti ON csi.id = ti.stock_item_id
                         JOIN stock_transactions st ON ti.transaction_id = st.id
                         JOIN borrower_users bu ON st.borrower_id = bu.id
                         $export_where_clause
                         GROUP BY csi.id, csi.kode_barang, mcp.code_color, cc.component_name, b.nama_buyer, col.nama_collection
                         ORDER BY total_borrowed DESC, last_borrowed DESC
                         LIMIT ?";

        $export_stmt = $conn->prepare($export_query);
        if (!empty($export_params)) {
            $export_params[] = $limit;
            $export_param_types .= 'i';
            $export_stmt->bind_param($export_param_types, ...$export_params);
        } else {
            $export_stmt->bind_param('i', $limit);
        }
        $export_stmt->execute();
        $export_result = $export_stmt->get_result();
    }
    
    while ($row = $export_result->fetch_assoc()) {
        echo '<tr>';
        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']) . '</td>';
        echo '<td>' . htmlspecialchars($row['total_borrowed']) . '</td>';
        echo '<td>' . htmlspecialchars($row['borrowers']) . '</td>';
        echo '<td>' . ($row['last_borrowed'] ? date('d/m/Y H:i', strtotime($row['last_borrowed'])) : '-') . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    exit();
}

// Filter parameters
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
$color_filter = isset($_GET['color']) ? $_GET['color'] : '';
$component_filter = isset($_GET['component']) ? $_GET['component'] : '';
$buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';

// Build query with filters
$where_conditions = ["(st.status IN ('Disetujui', 'OnProccesing') OR st.status_peminjaman = 'Dikembalikan')"];
$params = [];
$param_types = '';

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

if (!empty($component_filter)) {
    $where_conditions[] = "cc.component_name LIKE ?";
    $params[] = '%' . $component_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 csi.kode_barang, mcp.code_color, cc.component_name,
                 b.nama_buyer, col.nama_collection, COUNT(ti.id) as total_borrowed,
                 GROUP_CONCAT(DISTINCT bu.username ORDER BY bu.username SEPARATOR ', ') as borrowers,
                 MAX(st.tanggal_transaksi) as last_borrowed
          FROM color_stock_items csi
          JOIN master_color_panel mcp ON csi.color_id = mcp.id
          JOIN color_components cc ON csi.component_id = cc.id
          JOIN buyers b ON mcp.buyer_id = b.id
          JOIN collections col ON mcp.collection_id = col.id
          JOIN transaction_items ti ON csi.id = ti.stock_item_id
          JOIN stock_transactions st ON ti.transaction_id = st.id
          JOIN borrower_users bu ON st.borrower_id = bu.id
          $where_clause
          GROUP BY csi.id, csi.kode_barang, mcp.code_color, cc.component_name, b.nama_buyer, col.nama_collection
          ORDER BY total_borrowed DESC, last_borrowed DESC
          LIMIT ?";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $params[] = $limit;
    $param_types .= 'i';
    $stmt->bind_param($param_types, ...$params);
} else {
    $stmt->bind_param('i', $limit);
}
$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 Code Barang Sering Dipinjam</h2>
                <p class="text-gray-600">Laporan code barang yang paling sering dipinjam</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>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <?php
        // Get statistics
        $stats_query = "
            SELECT 
                COUNT(DISTINCT csi.id) as total_items_borrowed,
                COUNT(ti.id) as total_transactions,
                AVG(borrow_count.count) as avg_borrow_per_item,
                MAX(borrow_count.count) as max_borrow_count
            FROM (
                SELECT csi.id, COUNT(ti.id) as count
                FROM color_stock_items csi
                JOIN transaction_items ti ON csi.id = ti.stock_item_id
                JOIN stock_transactions st ON ti.transaction_id = st.id
                WHERE st.status IN ('Disetujui', 'OnProccesing') OR st.status_peminjaman = 'Dikembalikan'
                GROUP BY csi.id
            ) as borrow_count
            JOIN color_stock_items csi ON borrow_count.id = csi.id
            JOIN transaction_items ti ON csi.id = ti.stock_item_id
        ";
        $stats_result = $conn->query($stats_query);
        $stats = $stats_result->fetch_assoc();
        ?>
        
        <div class="bg-white p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-500 mr-4">
                    <i class="fas fa-box text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Total Item Dipinjam</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['total_items_borrowed'] ?? 0); ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-500 mr-4">
                    <i class="fas fa-exchange-alt text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Total Transaksi</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['total_transactions'] ?? 0); ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-yellow-100 text-yellow-500 mr-4">
                    <i class="fas fa-chart-line text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Rata-rata Peminjaman</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['avg_borrow_per_item'] ?? 0, 1); ?></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-red-100 text-red-500 mr-4">
                    <i class="fas fa-crown text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Tertinggi Dipinjam</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['max_borrow_count'] ?? 0); ?>x</p>
                </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-4 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 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">Limit Data</label>
                <select name="limit" 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="25" <?php echo $limit == 25 ? 'selected' : ''; ?>>25 Teratas</option>
                    <option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>50 Teratas</option>
                    <option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>100 Teratas</option>
                    <option value="200" <?php echo $limit == 200 ? 'selected' : ''; ?>>200 Teratas</option>
                </select>
            </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>
                <label class="block text-sm font-medium text-gray-700 mb-2">Component</label>
                <input type="text" name="component" value="<?php echo htmlspecialchars($component_filter); ?>" 
                       placeholder="Cari component..." 
                       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-4 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_dipinjam.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">Ranking</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-center text-xs font-medium text-gray-500 uppercase tracking-wider">Total Dipinjam</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sering Dipinjam Oleh</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Terakhir Dipinjam</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if ($result->num_rows > 0): ?>
                        <?php 
                        $ranking = 1;
                        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
                                    $rank_class = '';
                                    if ($ranking == 1) $rank_class = 'bg-yellow-100 text-yellow-800';
                                    elseif ($ranking == 2) $rank_class = 'bg-gray-100 text-gray-800';
                                    elseif ($ranking == 3) $rank_class = 'bg-orange-100 text-orange-800';
                                    else $rank_class = 'bg-blue-100 text-blue-800';
                                    ?>
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full <?php echo $rank_class; ?>">
                                        #<?php echo $ranking; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium 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-center">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                        <?php echo number_format($row['total_borrowed']); ?>x
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-900">
                                    <?php 
                                    $borrowers = explode(', ', $row['borrowers']);
                                    if (count($borrowers) <= 3) {
                                        echo htmlspecialchars($row['borrowers']);
                                    } else {
                                        echo htmlspecialchars(implode(', ', array_slice($borrowers, 0, 3))) . ' <span class="text-gray-500">+' . (count($borrowers) - 3) . ' lainnya</span>';
                                    }
                                    ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['last_borrowed'] ? date('d/m/Y H:i', strtotime($row['last_borrowed'])) : '-'; ?>
                                </td>
                            </tr>
                        <?php 
                        $ranking++;
                        endwhile; 
                        ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="px-6 py-4 text-center text-sm text-gray-500">
                                Tidak ada data peminjaman 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'; ?>