<div class="page-header responsive-header">
    <div>
        <a href="<?= APP_URL ?>/reports" class="btn btn-ghost btn-sm mb-3" style="padding-left:0;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Reports
        </a>
        <h1><?= $data['title'] ?></h1>
        <div class="page-subtitle">Detailed analysis of purchased items with supplier insights and profit potential</div>
    </div>
    <div class="flex gap-2 flex-wrap">
        <a href="<?= APP_URL ?>/reports?report=purchase-items&format=csv<?= ($qs = http_build_query($data['filters'])) ? '&' . $qs : '' ?>" class="btn btn-outline btn-sm">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                <polyline points="7 10 12 15 17 10"></polyline>
                <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
            Export CSV
        </a>
        <a href="<?= APP_URL ?>/reports?report=purchase-items&format=print<?= ($qs = http_build_query($data['filters'])) ? '&' . $qs : '' ?>" class="btn btn-secondary btn-sm">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="6 9 6 15 18 15"></polyline>
                <path d="M6 4h12v16H6z"></path>
            </svg>
            Print
        </a>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-header">
        <h3 class="card-title">Filters</h3>
    </div>
    <form method="GET" class="p-3">
        <input type="hidden" name="report" value="purchase-items">
        <div class="responsive-grid gap-3">
            <div class="form-group">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?= e($data['filters']['date_from']) ?>">
            </div>
            <div class="form-group">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?= e($data['filters']['date_to']) ?>">
            </div>
            <div class="form-group">
                <label class="form-label">&nbsp;</label>
                <button type="submit" class="btn btn-primary w-full">Apply Filters</button>
            </div>
            <div class="form-group">
                <label class="form-label">&nbsp;</label>
                <a href="<?= APP_URL ?>/reports?report=purchase-items" class="btn btn-outline w-full">Clear Filters</a>
            </div>
        </div>
    </form>
</div>

<!-- Summary Cards -->
<div class="responsive-grid gap-3 mb-4 summary-cards">
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Total Items</div>
            <div class="text-xl font-bold"><?= number_format($data['summary']['total_items']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Total Quantity</div>
            <div class="text-xl font-bold text-blue-600"><?= number_format($data['summary']['total_quantity']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Total Cost</div>
            <div class="text-xl font-bold text-red-600"><?= money($data['summary']['total_cost']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Potential Profit</div>
            <div class="text-xl font-bold text-green-600"><?= money($data['summary']['total_potential_profit']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Avg Unit Cost</div>
            <div class="text-xl font-bold"><?= money($data['summary']['avg_unit_cost']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Potential Revenue</div>
            <div class="text-xl font-bold text-purple-600"><?= money($data['summary']['total_potential_revenue']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Unique Suppliers</div>
            <div class="text-xl font-bold text-orange-600"><?= number_format($data['summary']['unique_suppliers']) ?></div>
        </div>
    </div>
    <div class="card compact-card">
        <div class="p-3">
            <div class="text-xs text-muted">Unique Products</div>
            <div class="text-xl font-bold text-teal-600"><?= number_format($data['summary']['unique_products']) ?></div>
        </div>
    </div>
</div>

<!-- Tabs Navigation -->
<div class="card mb-4">
    <div class="card-header">
        <div class="tab-nav-scroll">
            <button class="tab-btn btn btn-primary" data-tab="suppliers-chart">Top Suppliers</button>
            <button class="tab-btn btn btn-secondary" data-tab="category-chart">Category</button>
            <button class="tab-btn btn btn-secondary" data-tab="suppliers-table">Suppliers</button>
            <button class="tab-btn btn btn-secondary" data-tab="category-table">Categories</button>
            <button class="tab-btn btn btn-secondary" data-tab="products">Products</button>
            <button class="tab-btn btn btn-secondary" data-tab="details">Details</button>
        </div>
    </div>
</div>

<!-- Tab Content -->
<div class="tab-content">
    <!-- Top Suppliers Chart Tab -->
    <div class="tab-pane active" id="suppliers-chart">
        <div class="card mb-4">
            <div class="card-header">
                <h3 class="card-title">Top Suppliers by Cost</h3>
                <div class="text-sm text-muted">Your biggest suppliers by purchase value</div>
                <div class="flex gap-2">
                    <button onclick="window.print()" class="btn btn-secondary btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="6 9 6 15 18 15"></polyline>
                            <path d="M6 4h12v16H6z"></path>
                        </svg>
                        Print Chart
                    </button>
                </div>
            </div>
            <div class="p-3 chart-container">
                <canvas id="supplierChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Category Chart Tab -->
    <div class="tab-pane" id="category-chart">
        <div class="card mb-4">
            <div class="card-header">
                <h3 class="card-title">Category Breakdown</h3>
                <div class="text-sm text-muted">Purchase distribution by category</div>
                <div class="flex gap-2">
                    <button onclick="window.print()" class="btn btn-secondary btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="6 9 6 15 18 15"></polyline>
                            <path d="M6 4h12v16H6z"></path>
                        </svg>
                        Print Chart
                    </button>
                </div>
            </div>
            <div class="p-3 chart-container">
                <canvas id="categoryChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Top Suppliers Table Tab -->
    <div class="tab-pane" id="suppliers-table">
        <div class="card mb-4">
            <div class="card-header">
                <h3 class="card-title">Top Suppliers Analysis</h3>
                <div class="flex gap-2">
                    <button onclick="exportTableToCSV('suppliers-table', 'suppliers-analysis.csv')" class="btn btn-outline btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                            <polyline points="7 10 12 15 17 10"></polyline>
                            <line x1="12" y1="15" x2="12" y2="3"></line>
                        </svg>
                        Export CSV
                    </button>
                    <button onclick="window.print()" class="btn btn-secondary btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="6 9 6 15 18 15"></polyline>
                            <path d="M6 4h12v16H6z"></path>
                        </svg>
                        Print
                    </button>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="data-table compact-table" id="suppliers-table-data">
                    <thead>
                        <tr>
                            <th class="text-left">Supplier</th>
                            <th class="text-center">Purchase Count</th>
                            <th class="text-center">Total Quantity</th>
                            <th class="text-center">Total Cost</th>
                            <th class="text-center">Avg Unit Cost</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($data['top_suppliers'] as $supplier): ?>
                        <tr>
                            <td class="text-left font-semibold"><?= e($supplier['supplier'] ?? 'Direct') ?></td>
                            <td class="text-center"><?= number_format($supplier['purchase_count']) ?></td>
                            <td class="text-center"><?= number_format($supplier['total_quantity']) ?></td>
                            <td class="text-center font-bold text-red-600"><?= money($supplier['total_cost']) ?></td>
                            <td class="text-center"><?= money($supplier['avg_unit_cost']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Category Breakdown Table Tab -->
    <div class="tab-pane" id="category-table">
        <div class="card mb-4">
            <div class="card-header">
                <h3 class="card-title">Category Breakdown</h3>
                <div class="flex gap-2">
                    <button onclick="exportTableToCSV('category-table', 'category-breakdown.csv')" class="btn btn-outline btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                            <polyline points="7 10 12 15 17 10"></polyline>
                            <line x1="12" y1="15" x2="12" y2="3"></line>
                        </svg>
                        Export CSV
                    </button>
                    <button onclick="window.print()" class="btn btn-secondary btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="6 9 6 15 18 15"></polyline>
                            <path d="M6 4h12v16H6z"></path>
                        </svg>
                        Print
                    </button>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="data-table compact-table" id="category-table-data">
                    <thead>
                        <tr>
                            <th class="text-left">Category</th>
                            <th class="text-center">Product Count</th>
                            <th class="text-center">Total Quantity</th>
                            <th class="text-center">Total Cost</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($data['category_breakdown'] as $category): ?>
                        <tr>
                            <td class="text-left font-semibold"><?= e($category['category'] ?? 'Uncategorized') ?></td>
                            <td class="text-center"><?= number_format($category['product_count']) ?></td>
                            <td class="text-center"><?= number_format($category['total_quantity']) ?></td>
                            <td class="text-center font-bold text-red-600"><?= money($category['total_cost']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Top Products Tab -->
    <div class="tab-pane" id="products">
        <div class="card mb-4">
            <div class="card-header">
                <h3 class="card-title">Most Purchased Products</h3>
                <div class="flex gap-2">
                    <button onclick="exportTableToCSV('products', 'top-products.csv')" class="btn btn-outline btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                            <polyline points="7 10 12 15 17 10"></polyline>
                            <line x1="12" y1="15" x2="12" y2="3"></line>
                        </svg>
                        Export CSV
                    </button>
                    <button onclick="window.print()" class="btn btn-secondary btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="6 9 6 15 18 15"></polyline>
                            <path d="M6 4h12v16H6z"></path>
                        </svg>
                        Print
                    </button>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="data-table compact-table" id="products-table-data">
                    <thead>
                        <tr>
                            <th class="text-left">Product</th>
                            <th class="text-left">SKU</th>
                            <th class="text-center">Total Quantity</th>
                            <th class="text-center">Total Cost</th>
                            <th class="text-center">Avg Unit Cost</th>
                            <th class="text-center">Purchase Count</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($data['top_products'] as $product): ?>
                        <tr>
                            <td class="text-left font-semibold"><?= e($product['product']) ?></td>
                            <td class="text-left"><?= e($product['sku']) ?></td>
                            <td class="text-center"><?= number_format($product['total_quantity']) ?></td>
                            <td class="text-center font-bold text-red-600"><?= money($product['total_cost']) ?></td>
                            <td class="text-center"><?= money($product['avg_unit_cost']) ?></td>
                            <td class="text-center"><?= number_format($product['purchase_count']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Purchase Items Detail Tab -->
    <div class="tab-pane" id="details">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Purchase Items Detail</h3>
                <div class="flex gap-2">
                    <button onclick="exportTableToCSV('details', 'purchase-items-detail.csv')" class="btn btn-outline btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                            <polyline points="7 10 12 15 17 10"></polyline>
                            <line x1="12" y1="15" x2="12" y2="3"></line>
                        </svg>
                        Export CSV
                    </button>
                    <button onclick="window.print()" class="btn btn-secondary btn-sm">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="6 9 6 15 18 15"></polyline>
                            <path d="M6 4h12v16H6z"></path>
                        </svg>
                        Print
                    </button>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="data-table compact-table" id="details-table-data">
                    <thead>
                        <tr>
                            <th class="text-left">Purchase No</th>
                            <th class="text-left">Date</th>
                            <th class="text-left">Product</th>
                            <th class="text-left">SKU</th>
                            <th class="text-left">Category</th>
                            <th class="text-center">Quantity</th>
                            <th class="text-center">Unit Cost</th>
                            <th class="text-center">Total Cost</th>
                            <th class="text-left">Supplier</th>
                            <th class="text-left">Location</th>
                            <th class="text-center">Potential Revenue</th>
                            <th class="text-center">Potential Profit</th>
                            <th class="text-center">Profit Margin</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($data['purchase_items'] as $item): ?>
                        <tr>
                            <td class="text-left">
                                <a href="<?= APP_URL ?>/purchases/<?= $item['purchase_id'] ?>" class="text-blue-600 hover:underline">
                                    <?= e($item['purchase_no']) ?>
                                </a>
                            </td>
                            <td class="text-left"><?= date('M j, Y', strtotime($item['purchase_date'])) ?></td>
                            <td class="text-left font-semibold"><?= e($item['product_name']) ?></td>
                            <td class="text-left"><?= e($item['sku']) ?></td>
                            <td class="text-left"><?= e($item['category'] ?? 'N/A') ?></td>
                            <td class="text-center"><?= number_format($item['quantity']) ?></td>
                            <td class="text-center"><?= money($item['unit_cost']) ?></td>
                            <td class="text-center font-bold text-red-600"><?= money($item['total']) ?></td>
                            <td class="text-left"><?= e($item['supplier'] ?? 'Direct') ?></td>
                            <td class="text-left"><?= e($item['location']) ?></td>
                            <td class="text-center text-purple-600"><?= money($item['potential_revenue']) ?></td>
                            <td class="text-center font-bold <?= $item['potential_profit'] >= 0 ? 'text-green-600' : 'text-red-600' ?>">
                                <?= money($item['potential_profit']) ?>
                            </td>
                            <td class="text-center">
                                <?php 
                                $margin = $item['unit_cost'] > 0 ? (($item['selling_price'] - $item['unit_cost']) / $item['unit_cost']) * 100 : 0;
                                ?>
                                <span class="badge <?= $margin >= 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                                    <?= number_format($margin, 1) ?>%
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="font-bold bg-blue-50 border-t-2 border-blue-200">
                            <td class="text-left" colspan="5">TOTALS</td>
                            <td class="text-center"><?= number_format($data['summary']['total_quantity']) ?></td>
                            <td class="text-center"><?= money($data['summary']['avg_unit_cost']) ?></td>
                            <td class="text-center text-red-600"><?= money($data['summary']['total_cost']) ?></td>
                            <td class="text-left" colspan="2"></td>
                            <td class="text-center text-purple-600"><?= money($data['summary']['total_potential_revenue']) ?></td>
                            <td class="text-center <?= $data['summary']['total_potential_profit'] >= 0 ? 'text-green-600' : 'text-red-600' ?>">
                                <?= money($data['summary']['total_potential_profit']) ?>
                            </td>
                            <td class="text-center"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            
            <?= paginationLinks($data['pagination'], APP_URL . '/reports?report=purchase-items', $data['filters']) ?>
        </div>
    </div>
</div>

<style>
.tab-pane {
    display: none;
}
.tab-pane.active {
    display: block;
}
.tab-btn {
    cursor: pointer;
}

/* Responsive Grid Layout */
.responsive-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
}

/* Compact Card */
.compact-card {
    padding: 0.75rem;
}

/* Compact Table */
.compact-table thead th {
    padding: 0.5rem 0.75rem;
    font-size: 0.7rem;
}
.compact-table tbody td {
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
}
.compact-table tfoot td {
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
}

/* Tab Navigation Scroll */
.tab-nav-scroll {
    display: flex;
    gap: 0.5rem;
    overflow-x: auto;
    padding-bottom: 0.5rem;
    scrollbar-width: thin;
}
.tab-nav-scroll::-webkit-scrollbar {
    height: 4px;
}
.tab-nav-scroll::-webkit-scrollbar-thumb {
    background: rgba(99,102,241,0.3);
    border-radius: 4px;
}
.tab-nav-scroll .tab-btn {
    white-space: nowrap;
    font-size: 0.8rem;
    padding: 0.5rem 1rem;
}

/* Chart Container */
.chart-container {
    position: relative;
    min-height: 250px;
}

/* Responsive Header */
.responsive-header {
    flex-direction: column;
    align-items: flex-start;
}
@media (min-width: 768px) {
    .responsive-header {
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
}

/* Mobile Responsive */
@media (max-width: 1024px) {
    .responsive-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 640px) {
    .responsive-grid {
        grid-template-columns: 1fr;
    }
    
    .page-header h1 {
        font-size: 1.1rem;
    }
    
    .page-subtitle {
        font-size: 0.75rem;
    }
    
    .card {
        padding: 1rem;
    }
    
    .compact-card {
        padding: 0.6rem;
    }
    
    .compact-table thead th,
    .compact-table tbody td,
    .compact-table tfoot td {
        padding: 0.4rem 0.5rem;
        font-size: 0.75rem;
    }
    
    .chart-container {
        min-height: 200px;
    }
    
    .tab-nav-scroll .tab-btn {
        font-size: 0.75rem;
        padding: 0.4rem 0.75rem;
    }
    
    .btn-sm {
        padding: 0.4rem 0.75rem;
        font-size: 0.75rem;
    }
    
    .form-control {
        padding: 0.5rem 0.75rem;
        font-size: 0.85rem;
    }
}

@media (max-width: 480px) {
    .summary-cards .text-xl {
        font-size: 1.1rem;
    }
    
    .summary-cards .text-xs {
        font-size: 0.65rem;
    }
}
</style>

<!-- Chart Scripts -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Tab switching functionality
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabPanes = document.querySelectorAll('.tab-pane');

    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const targetTab = this.getAttribute('data-tab');

            // Remove active class from all buttons and panes
            tabButtons.forEach(btn => {
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-secondary');
            });
            tabPanes.forEach(pane => {
                pane.classList.remove('active');
            });

            // Add active class to clicked button and target pane
            this.classList.remove('btn-secondary');
            this.classList.add('btn-primary');
            document.getElementById(targetTab).classList.add('active');
        });
    });

    // CSV Export Function
    window.exportTableToCSV = function(tableId, filename) {
        const tableIdMap = {
            'suppliers-table': 'suppliers-table-data',
            'category-table': 'category-table-data',
            'products': 'products-table-data',
            'details': 'details-table-data'
        };
        
        const actualTableId = tableIdMap[tableId] || tableId + '-data';
        const table = document.getElementById(actualTableId);
        
        if (!table) {
            alert('Table not found');
            return;
        }

        const rows = table.querySelectorAll('tr');
        const csv = [];
        
        for (let i = 0; i < rows.length; i++) {
            const row = [];
            const cells = rows[i].querySelectorAll('th, td');
            
            for (let j = 0; j < cells.length; j++) {
                let text = cells[j].innerText;
                text = text.replace(/"/g, '""');
                row.push('"' + text + '"');
            }
            
            csv.push(row.join(','));
        }

        const csvString = csv.join('\n');
        const blob = new Blob([csvString], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.setAttribute('hidden', '');
        a.setAttribute('href', url);
        a.setAttribute('download', filename);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    };

    // Supplier Chart
    const supplierCtx = document.getElementById('supplierChart');
    if (supplierCtx) {
        try {
            const suppliers = <?= json_encode($data['top_suppliers'] ?? []) ?>;
            
            if (suppliers && suppliers.length > 0) {
                const supplierColors = [
                    'rgba(99, 102, 241, 0.8)',
                    'rgba(16, 185, 129, 0.8)',
                    'rgba(245, 158, 11, 0.8)',
                    'rgba(239, 68, 68, 0.8)',
                    'rgba(139, 92, 246, 0.8)',
                    'rgba(20, 184, 166, 0.8)',
                    'rgba(236, 72, 153, 0.8)',
                    'rgba(249, 115, 22, 0.8)',
                    'rgba(6, 182, 212, 0.8)',
                    'rgba(168, 85, 247, 0.8)'
                ];
                
                const supplierBorderColors = [
                    'rgb(99, 102, 241)',
                    'rgb(16, 185, 129)',
                    'rgb(245, 158, 11)',
                    'rgb(239, 68, 68)',
                    'rgb(139, 92, 246)',
                    'rgb(20, 184, 166)',
                    'rgb(236, 72, 153)',
                    'rgb(249, 115, 22)',
                    'rgb(6, 182, 212)',
                    'rgb(168, 85, 247)'
                ];

                new Chart(supplierCtx, {
                    type: 'bar',
                    data: {
                        labels: suppliers.map(s => s.supplier || 'Direct'),
                        datasets: [{
                            label: 'Total Cost',
                            data: suppliers.map(s => parseFloat(s.total_cost)),
                            backgroundColor: suppliers.map((_, i) => supplierColors[i % supplierColors.length]),
                            borderColor: suppliers.map((_, i) => supplierBorderColors[i % supplierBorderColors.length]),
                            borderWidth: 2
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return '$' + value.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                });
            } else {
                supplierCtx.parentElement.innerHTML = '<div class="text-center text-muted p-4">No supplier data available for chart</div>';
            }
        } catch (e) {
            console.error('Error loading supplier chart:', e);
            supplierCtx.parentElement.innerHTML = '<div class="text-center text-muted p-4">Error loading chart</div>';
        }
    }

    // Category Chart
    const categoryCtx = document.getElementById('categoryChart');
    if (categoryCtx) {
        try {
            const categories = <?= json_encode($data['category_breakdown'] ?? []) ?>;
            
            if (categories && categories.length > 0) {
                const categoryColors = [
                    'rgba(99, 102, 241, 0.8)',
                    'rgba(16, 185, 129, 0.8)',
                    'rgba(245, 158, 11, 0.8)',
                    'rgba(239, 68, 68, 0.8)',
                    'rgba(139, 92, 246, 0.8)',
                    'rgba(20, 184, 166, 0.8)',
                    'rgba(236, 72, 153, 0.8)',
                    'rgba(249, 115, 22, 0.8)',
                    'rgba(6, 182, 212, 0.8)',
                    'rgba(168, 85, 247, 0.8)',
                    'rgba(34, 197, 94, 0.8)',
                    'rgba(234, 179, 8, 0.8)'
                ];
                
                new Chart(categoryCtx, {
                    type: 'doughnut',
                    data: {
                        labels: categories.map(c => c.category || 'Uncategorized'),
                        datasets: [{
                            data: categories.map(c => parseFloat(c.total_cost)),
                            backgroundColor: categories.map((_, i) => categoryColors[i % categoryColors.length]),
                            borderWidth: 2,
                            borderColor: '#ffffff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'right'
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        let label = context.label || '';
                                        if (label) {
                                            label += ': ';
                                        }
                                        label += '$' + context.raw.toLocaleString();
                                        return label;
                                    }
                                }
                            }
                        }
                    }
                });
            } else {
                categoryCtx.parentElement.innerHTML = '<div class="text-center text-muted p-4">No category data available for chart</div>';
            }
        } catch (e) {
            console.error('Error loading category chart:', e);
            categoryCtx.parentElement.innerHTML = '<div class="text-center text-muted p-4">Error loading chart</div>';
        }
    }
});
</script>
