<?php
session_start();
require_once '../config/db.php';

// Optimize query to use existing supply_id
$sql = "SELECT 
            r.return_id, 
            r.supply_id, 
            r.quantity_returned, 
            r.return_date, 
            r.reason,
            d.drug_name as product_name, 
            s.supply_date, 
            sup.business_name,
            (SELECT COUNT(*) FROM returns WHERE supply_id = r.supply_id) as items_returned
        FROM returns r
        JOIN drugs d ON r.drug_id = d.id
        JOIN supplies s ON r.supply_id = s.id
        JOIN suppliers sup ON s.supplier_id = sup.id
        ORDER BY r.supply_id DESC, r.return_date DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute();
$returns = $stmt->fetchAll();

// More efficient grouping using supply_id
$groupedReturns = [];
foreach ($returns as $return) {
    if (!isset($groupedReturns[$return['supply_id']])) {
        $groupedReturns[$return['supply_id']] = [
            'supply_info' => [
                'supply_id' => $return['supply_id'],
                'business_name' => $return['business_name'],
                'supply_date' => $return['supply_date'],
                'items_returned' => $return['items_returned']
            ],
            'returns' => []
        ];
    }
    $groupedReturns[$return['supply_id']]['returns'][] = $return;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Returns - Admin Dashboard</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <style>
        :root {
            --primary-bg: #f4f6f9;
            --primary-color: #4e73df;
            --success-color: #1cc88a;
            --danger-color: #e74a3b;
        }

        body {
            background-color: var(--primary-bg);
            font-family: 'Segoe UI', sans-serif;
        }

        .page-header {
            background: white;
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem rgba(58, 59, 69, 0.15);
            margin-bottom: 1.5rem;
        }

        .card {
            border: none;
            border-radius: 0.5rem;
            box-shadow: 0 0.15rem 1.75rem rgba(58, 59, 69, 0.15);
        }

        .card-header {
            background: white;
            border-bottom: 1px solid #e3e6f0;
            padding: 1rem 1.25rem;
        }

        .table th {
            background: #f8f9fc;
            border-top: none;
            font-weight: 600;
            white-space: nowrap;
        }

        .table td {
            vertical-align: middle;
        }

        .badge-return {
            background: var(--danger-color);
            color: white;
            padding: 0.5em 0.75em;
            border-radius: 0.25rem;
            font-size: 0.75em;
        }

        .stats-card {
            background: linear-gradient(135deg, var(--primary-color), #224abe);
            color: white;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .stats-card h6 {
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.8rem;
            margin-bottom: 0.5rem;
        }

        .stats-card p {
            font-size: 1.25rem;
            margin: 0;
            font-weight: 600;
        }

        /* Add these new styles */
        .supply-header {
            background: #f8f9fc;
            padding: 1rem;
            margin: -1rem -1rem 1rem -1rem;
            border-bottom: 1px solid #e3e6f0;
        }

        .supply-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .supply-detail {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .supply-detail i {
            color: var(--primary-color);
        }

        .return-group {
            margin-bottom: 2rem;
        }

        .return-group:last-child {
            margin-bottom: 0;
        }

        .search-highlight {
            background-color: #fff3cd;
            padding: 0.2em;
            border-radius: 0.2em;
        }

        .hidden {
            display: none !important;
        }

        .input-group-text {
            background-color: var(--primary-color);
            border: none;
            color: white;
        }

        .input-group .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Page Header -->
        <div class="page-header">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h1 class="h3 mb-0">Product Returns History</h1>
                <a href="view_supply.php" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back to Supplies
                </a>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="input-group">
                        <input type="text" 
                               id="searchInput" 
                               class="form-control" 
                               placeholder="Search returns..."
                               aria-label="Search returns">
                        <div class="input-group-append">
                            <span class="input-group-text">
                                <i class="fas fa-search"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="row">
            <div class="col-xl-3 col-md-6">
                <div class="stats-card">
                    <h6><i class="fas fa-box-open mr-2"></i>Total Supplies with Returns</h6>
                    <p><?php echo count($groupedReturns); ?></p>
                </div>
            </div>
            <div class="col-xl-3 col-md-6">
                <div class="stats-card">
                    <h6><i class="fas fa-undo mr-2"></i>Total Items Returned</h6>
                    <p><?php echo count($returns); ?></p>
                </div>
            </div>
        </div>

        <!-- Grouped Returns -->
        <?php if (!empty($groupedReturns)): ?>
            <?php foreach ($groupedReturns as $supplyId => $supplyData): ?>
                <div class="card return-group">
                    <div class="card-body">
                        <div class="supply-header">
                            <div class="supply-info">
                                <div class="supply-detail">
                                    <i class="fas fa-truck"></i>
                                    <strong>Supply #<?php echo $supplyData['supply_info']['supply_id']; ?></strong>
                                </div>
                                <div class="supply-detail">
                                    <i class="fas fa-building"></i>
                                    <span><?php echo htmlspecialchars($supplyData['supply_info']['business_name']); ?></span>
                                </div>
                                <div class="supply-detail">
                                    <i class="fas fa-calendar"></i>
                                    <span>Supply Date: <?php echo date('d M Y', strtotime($supplyData['supply_info']['supply_date'])); ?></span>
                                </div>
                                <div class="supply-detail">
                                    <i class="fas fa-undo"></i>
                                    <span><?php echo $supplyData['supply_info']['items_returned']; ?> items returned</span>
                                </div>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Return ID</th>
                                        <th>Product Name</th>
                                        <th>Quantity</th>
                                        <th>Return Date</th>
                                        <th>Reason</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($supplyData['returns'] as $return): ?>
                                        <tr>
                                            <td>
                                                <span class="badge badge-return">
                                                    #<?php echo htmlspecialchars($return['return_id']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo htmlspecialchars($return['product_name']); ?></td>
                                            <td><?php echo htmlspecialchars($return['quantity_returned']); ?></td>
                                            <td><?php echo date('d M Y', strtotime($return['return_date'])); ?></td>
                                            <td>
                                                <?php echo !empty($return['reason']) ? 
                                                    htmlspecialchars($return['reason']) : 
                                                    '<span class="text-muted">No reason provided</span>'; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="card">
                <div class="card-body text-center text-muted py-4">
                    <i class="fas fa-box-open fa-3x mb-3"></i>
                    <p>No return records found</p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('searchInput');
        
        function performSearch() {
            const searchTerm = searchInput.value.toLowerCase().trim();
            const returnGroups = document.querySelectorAll('.return-group');
            let totalVisibleItems = 0;
            let visibleGroups = 0;

            returnGroups.forEach(group => {
                let found = false;
                const searchableElements = group.querySelectorAll('td, .supply-detail span');
                
                // Reset previous highlights
                group.querySelectorAll('.search-highlight').forEach(el => {
                    el.outerHTML = el.innerHTML;
                });

                if (searchTerm === '') {
                    group.classList.remove('hidden');
                    visibleGroups++;
                    totalVisibleItems += group.querySelectorAll('tbody tr').length;
                    return;
                }

                searchableElements.forEach(element => {
                    const text = element.textContent.toLowerCase();
                    if (text.includes(searchTerm)) {
                        found = true;
                        // Highlight matching text
                        const regex = new RegExp(`(${searchTerm})`, 'gi');
                        element.innerHTML = element.textContent.replace(
                            regex, 
                            '<span class="search-highlight">$1</span>'
                        );
                    }
                });

                group.classList.toggle('hidden', !found);
                if (!group.classList.contains('hidden')) {
                    visibleGroups++;
                    totalVisibleItems += group.querySelectorAll('tbody tr').length;
                }
            });

            // Update statistics
            const totalSuppliesCard = document.querySelector('.stats-card:first-child p');
            const totalItemsCard = document.querySelector('.stats-card:last-child p');
            
            if (totalSuppliesCard) totalSuppliesCard.textContent = visibleGroups;
            if (totalItemsCard) totalItemsCard.textContent = totalVisibleItems;
        }

        // Add search input event listener
        searchInput.addEventListener('input', performSearch);

        // Add clear button functionality
        const searchContainer = searchInput.parentElement;
        const clearButton = document.createElement('div');
        clearButton.className = 'input-group-append';
        clearButton.innerHTML = `
            <button class="btn btn-outline-secondary" type="button" id="clearSearch">
                <i class="fas fa-times"></i>
            </button>
        `;
        searchContainer.appendChild(clearButton);

        document.getElementById('clearSearch').addEventListener('click', function() {
            searchInput.value = '';
            performSearch();
            searchInput.focus();
        });

        // Initialize search on page load
        performSearch();
    });
    </script>
</body>
</html>
