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

// Log activity
create_audit_log($conn, 'Report Renew Access', $it_id, 'it', 'IT user accessed renew 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_Renew_' . $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 Renew</th>';
    echo '<th>Tanggal Pembuatan Awal</th>';
    echo '<th>Tanggal Kedaluwarsa Awal</th>';
    echo '<th>Terakhir Renew</th>';
    echo '<th>Status Saat Ini</th>';
    echo '<th>Keterangan</th>';
    echo '</tr>';
    
    // Build export query based on type
    if ($export_type == 'full') {
        // Full report - no filters, no limit
        $export_query = "SELECT rch.kode_barang, mcp.code_color, cc.component_name,
                                b.nama_buyer, col.nama_collection, COUNT(rch.id) as total_renew,
                                MIN(rch.tanggal_pembuatan) as first_created,
                                MIN(rch.tanggal_kedaluwarsa) as first_expired,
                                MAX(rch.renewed_date) as last_renewed,
                                COALESCE(csi.status, 'Data Tidak Ditemukan') as current_status,
                                GROUP_CONCAT(DISTINCT rch.keterangan ORDER BY rch.renewed_date DESC SEPARATOR ' | ') as all_keterangan
                         FROM renew_code_history rch
                         JOIN master_color_panel mcp ON rch.color_id = mcp.id
                         JOIN color_components cc ON rch.component_id = cc.id
                         JOIN buyers b ON mcp.buyer_id = b.id
                         JOIN collections col ON mcp.collection_id = col.id
                         LEFT JOIN color_stock_items csi ON rch.original_id = csi.id
                         GROUP BY rch.kode_barang, mcp.code_color, cc.component_name, b.nama_buyer, col.nama_collection, csi.status
                         ORDER BY total_renew DESC, last_renewed DESC";
        $export_result = $conn->query($export_query);
    } else {
        // Filtered report - use same filters as display
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
        $color_filter = isset($_GET['color']) ? $_GET['color'] : '';
        $component_filter = isset($_GET['component']) ? $_GET['component'] : '';
        $date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
        $date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
        $buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';
        
        $where_conditions = [];
        $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($date_from)) {
            $where_conditions[] = "DATE(rch.renewed_date) >= ?";
            $export_params[] = $date_from;
            $export_param_types .= 's';
        }

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

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

        $export_where_clause = '';
        if (!empty($where_conditions)) {
            $export_where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
        }

        $export_query = "SELECT rch.kode_barang, mcp.code_color, cc.component_name,
                                b.nama_buyer, col.nama_collection, COUNT(rch.id) as total_renew,
                                MIN(rch.tanggal_pembuatan) as first_created,
                                MIN(rch.tanggal_kedaluwarsa) as first_expired,
                                MAX(rch.renewed_date) as last_renewed,
                                COALESCE(csi.status, 'Data Tidak Ditemukan') as current_status,
                                GROUP_CONCAT(DISTINCT rch.keterangan ORDER BY rch.renewed_date DESC SEPARATOR ' | ') as all_keterangan
                         FROM renew_code_history rch
                         JOIN master_color_panel mcp ON rch.color_id = mcp.id
                         JOIN color_components cc ON rch.component_id = cc.id
                         JOIN buyers b ON mcp.buyer_id = b.id
                         JOIN collections col ON mcp.collection_id = col.id
                         LEFT JOIN color_stock_items csi ON rch.original_id = csi.id
                         $export_where_clause
                         GROUP BY rch.kode_barang, mcp.code_color, cc.component_name, b.nama_buyer, col.nama_collection, csi.status
                         ORDER BY total_renew DESC, last_renewed 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_renew']) . '</td>';
        echo '<td>' . ($row['first_created'] ? date('d/m/Y', strtotime($row['first_created'])) : '-') . '</td>';
        echo '<td>' . ($row['first_expired'] ? date('d/m/Y', strtotime($row['first_expired'])) : '-') . '</td>';
        echo '<td>' . ($row['last_renewed'] ? date('d/m/Y H:i', strtotime($row['last_renewed'])) : '-') . '</td>';
        echo '<td>' . htmlspecialchars($row['current_status']) . '</td>';
        echo '<td>' . htmlspecialchars($row['all_keterangan']) . '</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'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$buyer_filter = isset($_GET['buyer']) ? $_GET['buyer'] : '';

// Build query with filters
$where_conditions = [];
$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($date_from)) {
    $where_conditions[] = "DATE(rch.renewed_date) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

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

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

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

$query = "SELECT rch.kode_barang, mcp.code_color, cc.component_name,
                 b.nama_buyer, col.nama_collection, COUNT(rch.id) as total_renew,
                 MIN(rch.tanggal_pembuatan) as first_created,
                 MIN(rch.tanggal_kedaluwarsa) as first_expired,
                 MAX(rch.renewed_date) as last_renewed,
                 COALESCE(csi.status, 'Data Tidak Ditemukan') as current_status,
                 GROUP_CONCAT(DISTINCT rch.keterangan ORDER BY rch.renewed_date DESC SEPARATOR ' | ') as all_keterangan
          FROM renew_code_history rch
          JOIN master_color_panel mcp ON rch.color_id = mcp.id
          JOIN color_components cc ON rch.component_id = cc.id
          JOIN buyers b ON mcp.buyer_id = b.id
          JOIN collections col ON mcp.collection_id = col.id
          LEFT JOIN color_stock_items csi ON rch.original_id = csi.id
          $where_clause
          GROUP BY rch.kode_barang, mcp.code_color, cc.component_name, b.nama_buyer, col.nama_collection, csi.status
          ORDER BY total_renew DESC, last_renewed 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 Renew Code Barang</h2>
                <p class="text-gray-600">Laporan code barang yang sering di-renew (diperbaharui)</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 rch.kode_barang) as total_items_renewed,
                COUNT(rch.id) as total_renew_count,
                AVG(renew_count.count) as avg_renew_per_item,
                MAX(renew_count.count) as max_renew_count
            FROM renew_code_history rch
            JOIN (
                SELECT kode_barang, COUNT(id) as count
                FROM renew_code_history
                GROUP BY kode_barang
            ) as renew_count ON rch.kode_barang = renew_count.kode_barang
        ";
        $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-sync-alt text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Total Item Di-renew</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['total_items_renewed'] ?? 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-redo text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Total Renew</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['total_renew_count'] ?? 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-bar text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Rata-rata Renew</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['avg_renew_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-exclamation-triangle text-2xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Tertinggi Di-renew</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo number_format($stats['max_renew_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-6 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>
                <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 class="md:col-span-6 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_renew.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 Renew</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tgl Pembuatan Awal</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tgl Expired Awal</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Terakhir Renew</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status Saat Ini</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Keterangan</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-orange-100 text-orange-800">
                                        <?php echo number_format($row['total_renew']); ?>x
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['first_created'] ? date('d/m/Y', strtotime($row['first_created'])) : '-'; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['first_expired'] ? date('d/m/Y', strtotime($row['first_expired'])) : '-'; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <?php echo $row['last_renewed'] ? date('d/m/Y H:i', strtotime($row['last_renewed'])) : '-'; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <?php
                                    $status_class = '';
                                    switch($row['current_status']) {
                                        case 'Tersedia':
                                            $status_class = 'bg-green-100 text-green-800';
                                            break;
                                        case 'Dipinjam':
                                            $status_class = 'bg-yellow-100 text-yellow-800';
                                            break;
                                        case 'Rusak':
                                            $status_class = 'bg-red-100 text-red-800';
                                            break;
                                        case 'Expired':
                                            $status_class = 'bg-gray-100 text-gray-800';
                                            break;
                                        case 'Renew':
                                            $status_class = 'bg-blue-100 text-blue-800';
                                            break;
                                        case 'Hilang':
                                            $status_class = 'bg-purple-100 text-purple-800';
                                            break;
                                        default:
                                            $status_class = 'bg-gray-100 text-gray-800';
                                    }
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $status_class; ?>">
                                        <?php echo htmlspecialchars($row['current_status']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-900 max-w-xs">
                                    <div class="truncate" title="<?php echo htmlspecialchars($row['all_keterangan']); ?>">
                                        <?php 
                                        $keterangan = $row['all_keterangan'];
                                        if (strlen($keterangan) > 50) {
                                            echo htmlspecialchars(substr($keterangan, 0, 50)) . '...';
                                        } else {
                                            echo htmlspecialchars($keterangan);
                                        }
                                        ?>
                                    </div>
                                </td>
                            </tr>
                        <?php 
                        $ranking++;
                        endwhile; 
                        ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="11" class="px-6 py-4 text-center text-sm text-gray-500">
                                Tidak ada data renew yang ditemukan
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Info Section -->
    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-6">
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fas fa-info-circle text-blue-400 text-xl"></i>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-medium text-blue-800">Informasi Report Renew</h3>
                <div class="mt-2 text-sm text-blue-700">
                    <p>• Data ini menampilkan code barang yang pernah di-renew berdasarkan tabel <code>renew_code_history</code></p>
                    <p>• Total renew menunjukkan berapa kali code barang tersebut telah diperbaharui</p>
                    <p>• Status saat ini menunjukkan kondisi terkini dari code barang di tabel <code>color_stock_items</code></p>
                    <p>• Code barang yang sering di-renew mungkin memerlukan perhatian khusus untuk kualitas atau penanganan</p>
                </div>
            </div>
        </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'; ?>