<?php
/**
 * Product Purchases Management
 * XChange 2025 Registration System
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once 'product_helper.php';

// Get database connection
$conn = getDBConnection();

// Check authentication and permissions
$auth = new AdminAuth($conn);
$auth->requirePermission('registrations');

$productManager = new ProductManager($conn);

// Handle actions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$auth->hasPermission('payments')) {
        header('Location: access_denied.php');
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'update_stock_status') {
        try {
            $registration_product_id = $_POST['registration_product_id'];
            $new_status = $_POST['stock_status'];
            $reason = $_POST['reason'] ?? '';
            
            $productManager->updateStockStatus($registration_product_id, $new_status, 
                                             $_SESSION['admin_user_id'], $reason);
            
            $message = "Stock status updated successfully.";
            $messageType = "success";
            
            // Log admin activity
            $auth->logActivity('update_product_stock', "Updated stock status to {$new_status} for registration product ID {$registration_product_id}");
            
        } catch (Exception $e) {
            $message = "Error updating stock status: " . $e->getMessage();
            $messageType = "error";
        }
    }
}

// Get filters
$filters = [
    'product_id' => $_GET['product_id'] ?? '',
    'category_id' => $_GET['category_id'] ?? '',
    'stock_status' => $_GET['stock_status'] ?? '',
    'payment_status' => $_GET['payment_status'] ?? '',
    'search' => $_GET['search'] ?? ''
];

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 25;
$offset = ($page - 1) * $limit;

// Get data
$purchases = $productManager->getProductPurchases($filters, $limit, $offset);
$totalPurchases = $productManager->getProductPurchasesCount($filters);
$totalPages = ceil($totalPurchases / $limit);

$products = $productManager->getAllProducts();
$categories = $productManager->getProductCategories();
$summary = $productManager->getProductSummary();
$productSales = $productManager->getProductSales();

// Export functionality
if (isset($_GET['export']) && $_GET['export'] === 'csv' && $auth->hasPermission('export_data')) {
    $exportData = $productManager->getProductPurchases($filters, 10000, 0); // Get all for export
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="product_purchases_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // CSV Headers
    fputcsv($output, [
        'Registration Number', 'Contact Name', 'Contact Email', 'Product Name', 
        'Product Code', 'Category', 'Quantity', 'Unit Price', 'Total Price', 
        'Pricing Tier', 'Stock Status', 'Payment Status', 'Purchase Date'
    ]);
    
    foreach ($exportData as $purchase) {
        fputcsv($output, [
            $purchase['registration_number'],
            $purchase['contact_name'],
            $purchase['contact_email'],
            $purchase['product_name'],
            $purchase['product_code'],
            $purchase['category_name'],
            $purchase['quantity'],
            '$' . number_format($purchase['unit_price'], 2),
            '$' . number_format($purchase['total_price'], 2),
            $purchase['pricing_tier'],
            ucfirst($purchase['stock_status']),
            ucfirst($purchase['payment_status']),
            date('Y-m-d H:i', strtotime($purchase['created_at']))
        ]);
    }
    
    fclose($output);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Purchases - XChange 2025 Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <link rel="stylesheet" href="product-purchases.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>
    
    <div class="admin-content">
        <div class="page-header">
            <h1>Product Purchases Management</h1>
            <p>View and manage all product purchases across registrations</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card">
                <i class="help-icon" data-tooltip="total-purchases">?</i>
                <div class="summary-value"><?php echo number_format($summary['total_purchases']); ?></div>
                <div class="summary-label">Total Purchases</div>
            </div>
            <div class="summary-card">
                <i class="help-icon" data-tooltip="paid-revenue">?</i>
                <div class="summary-value">$<?php echo number_format($summary['total_revenue'], 2); ?></div>
                <div class="summary-label">Paid Revenue</div>
            </div>
            <div class="summary-card">
                <i class="help-icon" data-tooltip="unpaid-amount">?</i>
                <div class="summary-value">$<?php echo number_format($summary['unpaid_amount'], 2); ?></div>
                <div class="summary-label">Unpaid Amount</div>
            </div>
            <div class="summary-card">
                <i class="help-icon" data-tooltip="confirmed-purchases">?</i>
                <div class="summary-value"><?php echo number_format($summary['confirmed_purchases']); ?></div>
                <div class="summary-label">Confirmed</div>
            </div>
            <div class="summary-card">
                <i class="help-icon" data-tooltip="pending-purchases">?</i>
                <div class="summary-value"><?php echo number_format($summary['pending_purchases']); ?></div>
                <div class="summary-label">Pending</div>
            </div>
        </div>


        <!-- Filters -->
        <div class="product-filters">
            <div class="filter-header">
                <h3>Filter Purchases</h3>
                <div class="filter-actions">
                    <button type="button" id="toggleFilters" class="btn btn-outline">
                        <span id="filterToggleText">Show Filters</span>
                        <i id="filterToggleIcon">▼</i>
                    </button>
                    <a href="product-purchases.php" class="btn btn-secondary">Clear All</a>
                </div>
            </div>
            
            <div id="filterPanel" class="filter-panel" style="display: none;">
                <form method="GET" class="filter-form">
                    <!-- Quick Status Filters -->
                    <div class="quick-filters">
                        <div class="quick-filter-group">
                            <label class="quick-filter-label">Quick Filters:</label>
                            <div class="quick-filter-buttons">
                                <button type="button" class="quick-filter-btn <?php echo $filters['payment_status'] === 'paid' ? 'active' : ''; ?>" 
                                        data-filter="payment_status" data-value="paid">Paid Orders</button>
                                <button type="button" class="quick-filter-btn <?php echo $filters['payment_status'] === 'pending' ? 'active' : ''; ?>" 
                                        data-filter="payment_status" data-value="pending">Pending Payment</button>
                                <button type="button" class="quick-filter-btn <?php echo $filters['stock_status'] === 'confirmed' ? 'active' : ''; ?>" 
                                        data-filter="stock_status" data-value="confirmed">Confirmed Stock</button>
                                <button type="button" class="quick-filter-btn <?php echo $filters['stock_status'] === 'cancelled' ? 'active' : ''; ?>" 
                                        data-filter="stock_status" data-value="cancelled">Cancelled</button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Advanced Filters -->
                    <div class="advanced-filters">
                        <div class="filter-row">
                            <div class="filter-group">
                                <label class="filter-label">Search</label>
                                <input type="text" name="search" class="filter-input" 
                                       placeholder="Registration number, name, email..." 
                                       value="<?php echo htmlspecialchars($filters['search']); ?>">
                            </div>
                            
                            <div class="filter-group">
                                <label class="filter-label">Category</label>
                                <select name="category_id" class="filter-select">
                                    <option value="">All Categories</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>" 
                                                <?php echo $filters['category_id'] == $category['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($category['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <label class="filter-label">Product</label>
                                <select name="product_id" class="filter-select">
                                    <option value="">All Products</option>
                                    <?php foreach ($products as $product): ?>
                                        <option value="<?php echo $product['id']; ?>" 
                                                <?php echo $filters['product_id'] == $product['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($product['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="filter-row">
                            <div class="filter-group">
                                <label class="filter-label">Stock Status</label>
                                <select name="stock_status" class="filter-select">
                                    <option value="">All Status</option>
                                    <option value="reserved" <?php echo $filters['stock_status'] === 'reserved' ? 'selected' : ''; ?>>Reserved</option>
                                    <option value="confirmed" <?php echo $filters['stock_status'] === 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
                                    <option value="cancelled" <?php echo $filters['stock_status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                    <option value="refunded" <?php echo $filters['stock_status'] === 'refunded' ? 'selected' : ''; ?>>Refunded</option>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <label class="filter-label">Payment Status</label>
                                <select name="payment_status" class="filter-select">
                                    <option value="">All Payments</option>
                                    <option value="pending" <?php echo $filters['payment_status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="paid" <?php echo $filters['payment_status'] === 'paid' ? 'selected' : ''; ?>>Paid</option>
                                    <option value="failed" <?php echo $filters['payment_status'] === 'failed' ? 'selected' : ''; ?>>Failed</option>
                                    <option value="expired" <?php echo $filters['payment_status'] === 'expired' ? 'selected' : ''; ?>>Expired</option>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <button type="submit" class="btn btn-primary">Apply Filters</button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Hidden inputs for quick filters -->
                    <input type="hidden" name="quick_payment_status" id="quickPaymentStatus" value="<?php echo $filters['payment_status']; ?>">
                    <input type="hidden" name="quick_stock_status" id="quickStockStatus" value="<?php echo $filters['stock_status']; ?>">
                </form>
            </div>
        </div>

        <!-- Bulk Actions -->
        <div class="bulk-actions">
            <div class="bulk-actions-left">
                <span class="text-sm text-gray-600">
                    Showing <?php echo $offset + 1; ?>-<?php echo min($offset + $limit, $totalPurchases); ?> 
                    of <?php echo number_format($totalPurchases); ?> purchases
                </span>
            </div>
            <div class="bulk-actions-right">
                <?php if ($auth->hasPermission('registrations')): ?>
                    <a href="?<?php echo http_build_query(array_merge($filters, ['export' => 'csv'])); ?>" 
                       class="btn-export">
                        📊 Export CSV
                    </a>
                <?php endif; ?>
            </div>
        </div>

        <!-- Purchases Table -->
        <div class="purchase-table">
            <?php if (empty($purchases)): ?>
                <div class="empty-state">
                    <div class="empty-state-icon">📦</div>
                    <h3>No purchases found</h3>
                    <p>No product purchases match your current filters.</p>
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Registration</th>
                            <th>Quantity</th>
                            <th>Pricing</th>
                            <th>Stock Status</th>
                            <th>Payment</th>
                            <th>Date</th>
                            <?php if ($auth->hasPermission('payments')): ?>
                                <th>Actions</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($purchases as $purchase): ?>
                            <tr>
                                <td>
                                    <div class="product-info">
                                        <div class="product-name"><?php echo htmlspecialchars($purchase['product_name']); ?></div>
                                        <div class="product-code"><?php echo htmlspecialchars($purchase['product_code']); ?></div>
                                        <?php if ($purchase['category_name']): ?>
                                            <div class="product-category"><?php echo htmlspecialchars($purchase['category_name']); ?></div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td>
                                    <div class="registration-info">
                                        <div class="registration-number"><?php echo htmlspecialchars($purchase['registration_number']); ?></div>
                                        <div class="registration-contact"><?php echo htmlspecialchars($purchase['contact_name']); ?></div>
                                        <div class="registration-contact"><?php echo htmlspecialchars($purchase['contact_email']); ?></div>
                                    </div>
                                </td>
                                <td>
                                    <div class="quantity-info"><?php echo $purchase['quantity']; ?></div>
                                </td>
                                <td>
                                    <div class="price-info">
                                        <div class="total-price">$<?php echo number_format($purchase['total_price'], 2); ?></div>
                                        <div class="unit-price">$<?php echo number_format($purchase['unit_price'], 2); ?> each</div>
                                        <?php if ($purchase['pricing_tier']): ?>
                                            <div class="pricing-tier"><?php echo ucfirst(str_replace('_', ' ', $purchase['pricing_tier'])); ?></div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td>
                                    <span class="stock-status-badge stock-status-<?php echo $purchase['stock_status']; ?>">
                                        <?php echo ucfirst($purchase['stock_status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $purchase['payment_status']; ?>">
                                        <?php echo ucfirst($purchase['payment_status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="text-sm">
                                        <?php echo date('M j, Y', strtotime($purchase['created_at'])); ?><br>
                                        <span class="text-xs text-gray-500"><?php echo date('g:i A', strtotime($purchase['created_at'])); ?></span>
                                    </div>
                                </td>
                                <?php if ($auth->hasPermission('payments')): ?>
                                    <td>
                                        <div class="action-buttons">
                                            <a href="registration-details.php?id=<?php echo $purchase['registration_number']; ?>" 
                                               class="btn-action btn-view">View</a>
                                            <?php if ($purchase['stock_status'] !== 'cancelled' && $purchase['payment_status'] === 'paid'): ?>
                                                <button onclick="openStockStatusModal(<?php echo $purchase['id']; ?>, '<?php echo $purchase['stock_status']; ?>')" 
                                                        class="btn-action btn-edit" title="Cancel or refund this item">Update</button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?<?php echo http_build_query(array_merge($filters, ['page' => $page - 1])); ?>" 
                       class="pagination-btn">← Previous</a>
                <?php endif; ?>
                
                <span class="pagination-info">
                    Page <?php echo $page; ?> of <?php echo $totalPages; ?>
                </span>
                
                <?php if ($page < $totalPages): ?>
                    <a href="?<?php echo http_build_query(array_merge($filters, ['page' => $page + 1])); ?>" 
                       class="pagination-btn">Next →</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Stock Status Update Modal -->
    <?php if ($auth->hasPermission('payments')): ?>
        <div id="stockStatusModal" class="modal" style="display: none;">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>Update Stock Status</h3>
                    <button onclick="closeStockStatusModal()" class="modal-close">&times;</button>
                </div>
                <form method="POST" class="modal-body">
                    <input type="hidden" name="action" value="update_stock_status">
                    <input type="hidden" name="registration_product_id" id="modalRegistrationProductId">
                    
                    <div class="form-group">
                        <label class="form-label">Stock Status</label>
                        <select name="stock_status" id="modalStockStatus" class="form-control" required>
                            <option value="confirmed">Confirmed</option>
                            <option value="cancelled">Cancelled</option>
                            <option value="refunded">Refunded</option>
                        </select>
                        <div class="form-help">
                            <small class="text-muted">
                                ℹ️ Stock is automatically confirmed when payment is received. 
                                Use this only for cancellations, refunds, or corrections.
                            </small>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Reason (Optional)</label>
                        <textarea name="reason" class="form-control" rows="3" 
                                  placeholder="Enter reason for status change..."></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">Update Status</button>
                        <button type="button" onclick="closeStockStatusModal()" class="btn btn-secondary">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <script>
        function openStockStatusModal(registrationProductId, currentStatus) {
            document.getElementById('modalRegistrationProductId').value = registrationProductId;
            document.getElementById('modalStockStatus').value = currentStatus;
            document.getElementById('stockStatusModal').style.display = 'flex';
        }
        
        function closeStockStatusModal() {
            document.getElementById('stockStatusModal').style.display = 'none';
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('stockStatusModal');
            if (event.target === modal) {
                closeStockStatusModal();
            }
        }

        // Tooltip functionality
        document.addEventListener('DOMContentLoaded', function() {
            const tooltips = {
                'total-purchases': {
                    title: 'Total Purchases',
                    content: 'Total number of individual product purchases across all registrations. Each product item ordered counts as one purchase, regardless of payment status.'
                },
                'paid-revenue': {
                    title: 'Paid Revenue',
                    content: 'Total revenue from confirmed payments only. This represents actual income received from product sales where payment status is "paid".'
                },
                'unpaid-amount': {
                    title: 'Unpaid Amount',
                    content: 'Total value of product purchases with pending, failed, or expired payment status. This represents potential revenue that has not yet been collected.'
                },
                'confirmed-purchases': {
                    title: 'Confirmed Purchases',
                    content: 'Number of product purchases with confirmed stock status. These items have been paid for and stock has been allocated to the customer.'
                },
                'pending-purchases': {
                    title: 'Pending Purchases',
                    content: 'Number of product purchases with reserved stock status. These items are temporarily held pending payment confirmation.'
                }
            };

            // Create tooltip element
            const tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.style.display = 'none';
            document.body.appendChild(tooltip);

            // Add event listeners to help icons
            document.querySelectorAll('.help-icon').forEach(icon => {
                const tooltipKey = icon.getAttribute('data-tooltip');
                const tooltipData = tooltips[tooltipKey];

                if (tooltipData) {
                    icon.addEventListener('mouseenter', function(e) {
                        tooltip.innerHTML = `
                            <div class="tooltip-title">${tooltipData.title}</div>
                            <div class="tooltip-content">${tooltipData.content}</div>
                        `;
                        tooltip.style.display = 'block';
                        
                        // Position tooltip
                        const rect = icon.getBoundingClientRect();
                        const tooltipRect = tooltip.getBoundingClientRect();
                        
                        let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
                        let top = rect.top - tooltipRect.height - 10;
                        
                        // Adjust if tooltip goes off screen
                        if (left < 10) left = 10;
                        if (left + tooltipRect.width > window.innerWidth - 10) {
                            left = window.innerWidth - tooltipRect.width - 10;
                        }
                        if (top < 10) {
                            top = rect.bottom + 10;
                        }
                        
                        tooltip.style.left = left + 'px';
                        tooltip.style.top = top + 'px';
                    });

                    icon.addEventListener('mouseleave', function() {
                        tooltip.style.display = 'none';
                    });
                }
            });

            // Filter toggle functionality
            const toggleFilters = document.getElementById('toggleFilters');
            const filterPanel = document.getElementById('filterPanel');
            const filterToggleText = document.getElementById('filterToggleText');
            const filterToggleIcon = document.getElementById('filterToggleIcon');

            // Check if filters are active on page load
            const urlParams = new URLSearchParams(window.location.search);
            const hasActiveFilters = Array.from(urlParams.entries()).some(([key, value]) => 
                value && key !== 'page' && key !== 'limit'
            );

            if (hasActiveFilters) {
                filterPanel.style.display = 'block';
                filterToggleText.textContent = 'Hide Filters';
                filterToggleIcon.textContent = '▲';
            }

            toggleFilters.addEventListener('click', function() {
                const isVisible = filterPanel.style.display !== 'none';
                
                if (isVisible) {
                    filterPanel.style.display = 'none';
                    filterToggleText.textContent = 'Show Filters';
                    filterToggleIcon.textContent = '▼';
                } else {
                    filterPanel.style.display = 'block';
                    filterToggleText.textContent = 'Hide Filters';
                    filterToggleIcon.textContent = '▲';
                }
            });

            // Quick filter functionality
            document.querySelectorAll('.quick-filter-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const filterType = this.getAttribute('data-filter');
                    const filterValue = this.getAttribute('data-value');
                    
                    // Remove active class from all buttons of the same type
                    document.querySelectorAll(`[data-filter="${filterType}"]`).forEach(b => {
                        b.classList.remove('active');
                    });
                    
                    // Toggle current button
                    if (this.classList.contains('active')) {
                        this.classList.remove('active');
                        // Clear the filter
                        if (filterType === 'payment_status') {
                            document.querySelector('select[name="payment_status"]').value = '';
                        } else if (filterType === 'stock_status') {
                            document.querySelector('select[name="stock_status"]').value = '';
                        }
                    } else {
                        this.classList.add('active');
                        // Set the filter
                        if (filterType === 'payment_status') {
                            document.querySelector('select[name="payment_status"]').value = filterValue;
                        } else if (filterType === 'stock_status') {
                            document.querySelector('select[name="stock_status"]').value = filterValue;
                        }
                    }
                    
                    // Auto-submit the form
                    document.querySelector('.filter-form').submit();
                });
            });
        });
    </script>

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