<?php
/**
 * ADMIN COMMISSIONS MANAGEMENT PAGE
 * File: admin/commissions.php
 * Manage platform commissions, vendor payouts, and commission analytics
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

$page_title = "Commissions Management";
$active_menu = "commissions";

// Initialize models
$db = Database::getInstance();

// Get filter parameters
$status = $_GET['status'] ?? 'all';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$vendor_filter = $_GET['vendor'] ?? '';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;

// Build WHERE clause
$where_conditions = [];
$params = [];

if ($status !== 'all') {
    $where_conditions[] = "c.status = ?";
    $params[] = $status;
}

if (!empty($search)) {
    $where_conditions[] = "(v.business_name LIKE ? OR o.order_number LIKE ? OR c.id LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

if (!empty($vendor_filter)) {
    $where_conditions[] = "c.vendor_id = ?";
    $params[] = $vendor_filter;
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(c.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(c.created_at) <= ?";
    $params[] = $date_to;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$count_sql = "SELECT COUNT(*) as total 
              FROM commissions c
              LEFT JOIN vendors v ON c.vendor_id = v.id
              LEFT JOIN orders o ON c.order_id = o.id
              $where_clause";
$count_result = $db->fetch($count_sql, $params);
$total_commissions = $count_result['total'];
$total_pages = ceil($total_commissions / $per_page);
$offset = ($page - 1) * $per_page;

// Get commissions with vendor and order details
$commissions_sql = "SELECT c.*, v.business_name as vendor_name, v.phone as vendor_phone, v.email as vendor_email,
                   o.order_number, o.total_amount as order_amount, o.created_at as order_date,
                   CONCAT(cust.first_name, ' ', cust.last_name) as customer_name
                   FROM commissions c
                   LEFT JOIN vendors v ON c.vendor_id = v.id
                   LEFT JOIN orders o ON c.order_id = o.id
                   LEFT JOIN customers cust ON o.customer_id = cust.id
                   $where_clause
                   ORDER BY c.created_at DESC
                   LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;
$commissions = $db->fetchAll($commissions_sql, $params);

// Get commission statistics
$stats_sql = "SELECT 
              COUNT(*) as total_commissions,
              COALESCE(SUM(CASE WHEN status = 'paid' THEN commission_amount ELSE 0 END), 0) as total_paid,
              COALESCE(SUM(CASE WHEN status = 'pending' THEN commission_amount ELSE 0 END), 0) as total_pending,
              COALESCE(SUM(CASE WHEN status = 'refunded' THEN commission_amount ELSE 0 END), 0) as total_refunded,
              COALESCE(AVG(commission_percentage), 0) as avg_commission_rate,
              COALESCE(SUM(order_amount), 0) as total_order_value
              FROM commissions c
              LEFT JOIN vendors v ON c.vendor_id = v.id
              LEFT JOIN orders o ON c.order_id = o.id
              $where_clause";
$stats = $db->fetch($stats_sql, array_slice($params, 0, -2)); // Remove LIMIT and OFFSET

// Get vendor-wise commission summary
$vendor_commissions_sql = "SELECT 
                          v.id,
                          v.business_name,
                          COUNT(c.id) as total_commissions,
                          COALESCE(SUM(CASE WHEN c.status = 'paid' THEN c.commission_amount ELSE 0 END), 0) as paid_commission,
                          COALESCE(SUM(CASE WHEN c.status = 'pending' THEN c.commission_amount ELSE 0 END), 0) as pending_commission,
                          COALESCE(SUM(c.order_amount), 0) as total_sales,
                          ROUND(COALESCE(AVG(c.commission_percentage), 0), 2) as avg_rate
                          FROM vendors v
                          LEFT JOIN commissions c ON v.id = c.vendor_id
                          LEFT JOIN orders o ON c.order_id = o.id
                          $where_clause
                          GROUP BY v.id, v.business_name
                          ORDER BY paid_commission DESC
                          LIMIT 10";
$vendor_commissions = $db->fetchAll($vendor_commissions_sql, array_slice($params, 0, -2));

// Get monthly commission chart data (last 12 months)
$monthly_sql = "SELECT 
                DATE_FORMAT(c.created_at, '%Y-%m') as month,
                COUNT(*) as commissions_count,
                SUM(CASE WHEN c.status = 'paid' THEN c.commission_amount ELSE 0 END) as paid_amount,
                SUM(CASE WHEN c.status = 'pending' THEN c.commission_amount ELSE 0 END) as pending_amount
                FROM commissions c
                WHERE DATE(c.created_at) >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
                GROUP BY DATE_FORMAT(c.created_at, '%Y-%m')
                ORDER BY month ASC";
$monthly_data = $db->fetchAll($monthly_sql);

// Get all vendors for filter dropdown
$vendors_sql = "SELECT id, business_name FROM vendors ORDER BY business_name";
$all_vendors = $db->fetchAll($vendors_sql);

// Handle commission actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    switch ($action) {
        case 'mark_paid':
            $commission_id = (int)$_POST['commission_id'];
            
            try {
                $update_sql = "UPDATE commissions 
                              SET status = 'paid', 
                                  paid_at = NOW()
                              WHERE id = ?";
                $db->execute($update_sql, [$commission_id]);
                
                flash('message', ['type' => 'success', 'message' => 'Commission marked as paid successfully']);
                header('Location: commissions.php');
                exit;
            } catch (Exception $e) {
                flash('message', ['type' => 'danger', 'message' => 'Error updating commission: ' . $e->getMessage()]);
            }
            break;
            
        case 'bulk_payout':
            $selected_commissions = $_POST['selected_commissions'] ?? [];
            $vendor_id = (int)$_POST['vendor_id'];
            
            if (!empty($selected_commissions) && $vendor_id) {
                try {
                    $placeholders = str_repeat('?,', count($selected_commissions) - 1) . '?';
                    $update_sql = "UPDATE commissions 
                                  SET status = 'paid', 
                                      paid_at = NOW()
                                  WHERE id IN ($placeholders) 
                                  AND vendor_id = ? 
                                  AND status = 'pending'";
                    $params = array_merge($selected_commissions, [$vendor_id]);
                    $db->execute($update_sql, $params);
                    
                    flash('message', ['type' => 'success', 'message' => 'Bulk payout completed successfully']);
                    header('Location: commissions.php');
                    exit;
                } catch (Exception $e) {
                    flash('message', ['type' => 'danger', 'message' => 'Error processing bulk payout: ' . $e->getMessage()]);
                }
            }
            break;
            
        case 'export_commissions':
            // Redirect to export functionality
            $export_params = http_build_query($_GET);
            header("Location: commissions-export.php?$export_params");
            exit;
            break;
    }
}

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">

<?php include '../templates/layouts/admin/header.php'; ?>
    
    <!-- Page Header -->
    <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">
                    <i class="fas fa-percentage"></i> Commissions Management
                </h1>
                <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
                    <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
                    <span>/</span>
                    <span>Commissions</span>
                </div>
            </div>
            
            <div>
                <button onclick="exportCommissions()" class="btn btn-success">
                    <i class="fas fa-download"></i> Export Data
                </button>
            </div>
        </div>
    </div>
    
    <!-- Content -->
    <div style="padding: 30px;">
        
        <!-- Flash Messages -->
        <?php if ($flash_message): ?>
            <div class="alert alert-<?= $flash_message['type'] ?>">
                <?= Security::escapeOutput($flash_message['message']) ?>
            </div>
        <?php endif; ?>
        
        <!-- Commission Statistics -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px;">
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--primary); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-receipt"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= number_format($stats['total_commissions'] ?? 0) ?></div>
                        <div style="font-size: 14px; color: #666;">Total Commissions</div>
                    </div>
                </div>
            </div>
            
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--success); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= format_money($stats['total_paid'] ?? 0) ?></div>
                        <div style="font-size: 14px; color: #666;">Total Paid</div>
                    </div>
                </div>
            </div>
            
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--warning); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= format_money($stats['total_pending'] ?? 0) ?></div>
                        <div style="font-size: 14px; color: #666;">Pending Payment</div>
                    </div>
                </div>
            </div>
            
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--info); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= number_format($stats['avg_commission_rate'] ?? 0, 1) ?>%</div>
                        <div style="font-size: 14px; color: #666;">Avg Commission Rate</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Filters -->
        <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px;">
            <form method="GET">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end;">
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Status</label>
                        <select name="status" class="form-control">
                            <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All Status</option>
                            <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="paid" <?= $status === 'paid' ? 'selected' : '' ?>>Paid</option>
                            <option value="refunded" <?= $status === 'refunded' ? 'selected' : '' ?>>Refunded</option>
                        </select>
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Vendor</label>
                        <select name="vendor" class="form-control">
                            <option value="">All Vendors</option>
                            <?php foreach ($all_vendors as $vendor): ?>
                                <option value="<?= $vendor['id'] ?>" <?= $vendor_filter == $vendor['id'] ? 'selected' : '' ?>>
                                    <?= Security::escapeOutput($vendor['business_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Date From</label>
                        <input type="date" name="date_from" class="form-control" value="<?= $date_from ?>">
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Date To</label>
                        <input type="date" name="date_to" class="form-control" value="<?= $date_to ?>">
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Order #, vendor, ID..." 
                               value="<?= Security::escapeOutput($search) ?>">
                    </div>
                    
                    <div>
                        <button type="submit" class="btn btn-primary" style="width: 100%;">
                            <i class="fas fa-search"></i> Filter
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 30px; margin-bottom: 30px;">
            <!-- Monthly Commission Chart -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                    <i class="fas fa-chart-area"></i> Commission Trends (Last 12 Months)
                </h3>
                <canvas id="commissionChart" height="80"></canvas>
            </div>
            
            <!-- Top Vendors by Commission -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                    <i class="fas fa-trophy"></i> Top Vendors
                </h3>
                
                <?php if (empty($vendor_commissions)): ?>
                    <p style="color: #999; text-align: center; padding: 20px;">No vendor data available</p>
                <?php else: ?>
                    <div style="max-height: 300px; overflow-y: auto;">
                        <?php foreach ($vendor_commissions as $index => $vendor): ?>
                            <div style="border-bottom: 1px solid #f0f0f0; padding: 15px 0;">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div>
                                        <div style="font-weight: 600; margin-bottom: 5px;">
                                            <span style="background: var(--primary); color: white; padding: 2px 6px; border-radius: 10px; font-size: 10px; margin-right: 8px;">
                                                #<?= $index + 1 ?>
                                            </span>
                                            <?= Security::escapeOutput($vendor['business_name']) ?>
                                        </div>
                                        <div style="font-size: 12px; color: #666;">
                                            <?= number_format($vendor['total_commissions']) ?> commissions
                                        </div>
                                    </div>
                                    <div style="text-align: right;">
                                        <div style="font-weight: 600; color: var(--success);">
                                            <?= format_money($vendor['paid_commission']) ?>
                                        </div>
                                        <div style="font-size: 12px; color: #666;">
                                            Pending: <?= format_money($vendor['pending_commission']) ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Commissions Table -->
        <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="font-size: 18px; font-weight: 600; color: var(--dark); margin: 0;">
                    <i class="fas fa-list"></i> Commission Records
                </h3>
                
                <div style="display: flex; gap: 10px; align-items: center;">
                    <div style="color: #666; font-size: 14px;">
                        Total: <?= number_format($total_commissions) ?> commissions
                    </div>
                    
                    <?php if ($status === 'pending' && !empty($commissions)): ?>
                        <button onclick="showBulkPayoutModal()" class="btn btn-success">
                            <i class="fas fa-money-bill-wave"></i> Bulk Payout
                        </button>
                    <?php endif; ?>
                </div>
            </div>
            
            <form method="POST" id="bulkForm">
                <input type="hidden" name="action" value="bulk_payout">
                
                <div style="overflow-x: auto;">
                    <table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="background: #f8f9fa;">
                                <?php if ($status === 'pending'): ?>
                                    <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">
                                        <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                    </th>
                                <?php endif; ?>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Commission ID</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Order #</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Vendor</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Customer</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Order Amount</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Commission %</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Commission</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Status</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Date</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($commissions)): ?>
                                <tr>
                                    <td colspan="<?= $status === 'pending' ? '11' : '10' ?>" style="padding: 30px; text-align: center; color: #999;">
                                        <i class="fas fa-percentage fa-3x mb-3"></i>
                                        <p>No commissions found</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($commissions as $commission): ?>
                                    <tr style="border-bottom: 1px solid #f0f0f0;">
                                        <?php if ($status === 'pending'): ?>
                                            <td style="padding: 15px;">
                                                <input type="checkbox" name="selected_commissions[]" value="<?= $commission['id'] ?>" class="commission-checkbox">
                                            </td>
                                        <?php endif; ?>
                                        
                                        <td style="padding: 15px;">
                                            <strong>#<?= $commission['id'] ?></strong>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <strong><?= Security::escapeOutput($commission['order_number']) ?></strong>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <div>
                                                <strong><?= Security::escapeOutput($commission['vendor_name']) ?></strong><br>
                                                <small style="color: #666;"><?= format_phone($commission['vendor_phone']) ?></small>
                                            </div>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <?= Security::escapeOutput($commission['customer_name']) ?>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <strong><?= format_money($commission['order_amount']) ?></strong>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <span style="background: var(--info); color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 600;">
                                                <?= number_format($commission['commission_percentage'], 1) ?>%
                                            </span>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <strong style="color: var(--success);"><?= format_money($commission['commission_amount']) ?></strong><br>
                                            <small style="color: #666;">Vendor: <?= format_money($commission['vendor_amount']) ?></small>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <?php
                                            $status_class = '';
                                            switch($commission['status']) {
                                                case 'pending':
                                                    $status_class = 'status-pending';
                                                    break;
                                                case 'paid':
                                                    $status_class = 'status-success';
                                                    break;
                                                case 'refunded':
                                                    $status_class = 'status-rejected';
                                                    break;
                                            }
                                            ?>
                                            <span class="status-badge <?= $status_class ?>">
                                                <?= ucfirst($commission['status']) ?>
                                            </span>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <small><?= format_date($commission['created_at'], 'M d, Y') ?></small><br>
                                            <?php if ($commission['paid_at']): ?>
                                                <small style="color: var(--success);">Paid: <?= format_date($commission['paid_at'], 'M d, Y') ?></small>
                                            <?php endif; ?>
                                        </td>
                                        
                                        <td style="padding: 15px;">
                                            <div class="action-buttons">
                                                <?php if ($commission['status'] === 'pending'): ?>
                                                    <button onclick="markAsPaid(<?= $commission['id'] ?>)" 
                                                            class="btn-action btn-success" 
                                                            title="Mark as Paid">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <button onclick="viewCommissionDetails(<?= $commission['id'] ?>)" 
                                                        class="btn-action btn-info" 
                                                        title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if ($status === 'pending' && !empty($commissions)): ?>
                    <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #eee;">
                        <div style="display: flex; justify-content: between; align-items: center;">
                            <div style="color: #666; font-size: 14px;">
                                Selected: <span id="selectedCount">0</span> commissions
                            </div>
                            <button type="submit" class="btn btn-success" onclick="return confirm('Process payout for selected commissions?')">
                                <i class="fas fa-money-bill-wave"></i> Process Selected Payouts
                            </button>
                        </div>
                    </div>
                <?php endif; ?>
            </form>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div style="margin-top: 20px; text-align: center;">
                    <ul class="pagination">
                        <?php if ($page > 1): ?>
                            <li><a href="?page=<?= $page - 1 ?>&status=<?= $status ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&vendor=<?= $vendor_filter ?>&search=<?= urlencode($search) ?>">&laquo; Previous</a></li>
                        <?php endif; ?>
                        
                        <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                            <li class="<?= $i == $page ? 'active' : '' ?>">
                                <a href="?page=<?= $i ?>&status=<?= $status ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&vendor=<?= $vendor_filter ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): ?>
                            <li><a href="?page=<?= $page + 1 ?>&status=<?= $status ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&vendor=<?= $vendor_filter ?>&search=<?= urlencode($search) ?>">Next &raquo;</a></li>
                        <?php endif; ?>
                    </ul>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Bulk Payout Modal -->
<div id="bulkPayoutModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 100px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 400px;">
        <h3 style="margin-bottom: 20px; font-size: 20px; font-weight: 600;">Bulk Payout</h3>
        
        <form method="POST" id="bulkPayoutForm">
            <input type="hidden" name="action" value="bulk_payout">
            <input type="hidden" name="vendor_id" id="bulkVendorId">
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600;">Select Vendor</label>
                <select name="vendor_id" class="form-control" required>
                    <option value="">Choose Vendor</option>
                    <?php 
                    $vendors_with_pending = [];
                    foreach ($commissions as $commission) {
                        if ($commission['status'] === 'pending') {
                            $vendors_with_pending[$commission['vendor_id']] = $commission['vendor_name'];
                        }
                    }
                    foreach ($vendors_with_pending as $vendor_id => $vendor_name): ?>
                        <option value="<?= $vendor_id ?>"><?= Security::escapeOutput($vendor_name) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <p style="margin-bottom: 25px; line-height: 1.6;">
                This will mark all pending commissions for the selected vendor as paid.
            </p>
            
            <div style="display: flex; gap: 15px; justify-content: flex-end;">
                <button type="button" onclick="closeBulkPayoutModal()" class="btn btn-secondary">Cancel</button>
                <button type="submit" class="btn btn-success">Process Payout</button>
            </div>
        </form>
    </div>
</div>

<!-- Commission Details Modal -->
<div id="detailsModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 50px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
            <h3 style="margin: 0; font-size: 20px; font-weight: 600;">Commission Details</h3>
            <button onclick="closeDetailsModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
        </div>
        
        <div id="commissionDetails">
            <!-- Details will be loaded via AJAX -->
        </div>
    </div>
</div>

<style>
.modal {
    animation: fadeIn 0.3s;
}

.modal-content {
    animation: slideIn 0.3s;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideIn {
    from { transform: translateY(-50px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.status-pending {
    background: var(--warning);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-success {
    background: var(--success);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-rejected {
    background: var(--danger);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.action-buttons {
    display: flex;
    gap: 5px;
}

.btn-action {
    background: none;
    border: 1px solid #ddd;
    padding: 8px;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s;
    color: #666;
    font-size: 14px;
}

.btn-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.btn-success:hover {
    border-color: var(--success);
    color: var(--success);
}

.btn-info:hover {
    border-color: var(--info);
    color: var(--info);
}

.form-control {
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 10px 12px;
    font-size: 14px;
    transition: border-color 0.3s;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.btn {
    border: none;
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
}

.btn-primary {
    background: var(--primary);
    color: white;
}

.btn-primary:hover {
    background: #0056b3;
    transform: translateY(-2px);
}

.btn-success {
    background: var(--success);
    color: white;
}

.btn-success:hover {
    background: #1e7e34;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.pagination {
    list-style: none;
    padding: 0;
    margin: 20px 0;
    display: flex;
    justify-content: center;
    gap: 5px;
}

.pagination li {
    display: inline;
}

.pagination a,
.pagination span {
    display: inline-block;
    padding: 8px 12px;
    border: 1px solid #ddd;
    color: var(--dark);
    text-decoration: none;
    border-radius: 4px;
    transition: all 0.3s;
}

.pagination a:hover {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.pagination .active span {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Menu Toggle
document.getElementById('menuToggle')?.addEventListener('click', function() {
    document.getElementById('sidebar').classList.toggle('active');
});

// Commission Chart
const monthlyData = <?= json_encode($monthly_data) ?>;
const ctx = document.getElementById('commissionChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: monthlyData.map(d => d.month),
        datasets: [{
            label: 'Paid Commission',
            data: monthlyData.map(d => d.paid_amount),
            borderColor: '#28a745',
            backgroundColor: 'rgba(40, 167, 69, 0.1)',
            tension: 0.4,
            fill: true
        }, {
            label: 'Pending Commission',
            data: monthlyData.map(d => d.pending_amount),
            borderColor: '#ffc107',
            backgroundColor: 'rgba(255, 193, 7, 0.1)',
            tension: 0.4,
            fill: true
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            legend: {
                position: 'top'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '₦' + value.toLocaleString();
                    }
                }
            }
        }
    }
});

// Toggle select all checkboxes
function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.commission-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
    });
    
    updateSelectedCount();
}

// Update selected count
function updateSelectedCount() {
    const checkboxes = document.querySelectorAll('.commission-checkbox:checked');
    document.getElementById('selectedCount').textContent = checkboxes.length;
}

// Add event listeners to checkboxes
document.addEventListener('change', function(e) {
    if (e.target.classList.contains('commission-checkbox')) {
        updateSelectedCount();
    }
});

// Mark individual commission as paid
function markAsPaid(commissionId) {
    if (confirm('Mark this commission as paid?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="mark_paid">
            <input type="hidden" name="commission_id" value="${commissionId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Show bulk payout modal
function showBulkPayoutModal() {
    document.getElementById('bulkPayoutModal').style.display = 'block';
}

function closeBulkPayoutModal() {
    document.getElementById('bulkPayoutModal').style.display = 'none';
    document.getElementById('bulkPayoutForm').reset();
}

// View commission details
function viewCommissionDetails(commissionId) {
    document.getElementById('detailsModal').style.display = 'block';
    document.getElementById('commissionDetails').innerHTML = '<p>Loading commission details...</p>';
    
    // AJAX call to get commission details
    fetch('commission-details.php?id=' + commissionId)
        .then(response => response.text())
        .then(data => {
            document.getElementById('commissionDetails').innerHTML = data;
        })
        .catch(error => {
            document.getElementById('commissionDetails').innerHTML = '<p>Error loading commission details</p>';
        });
}

function closeDetailsModal() {
    document.getElementById('detailsModal').style.display = 'none';
}

// Export commissions
function exportCommissions() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    window.location.href = 'commissions-export.php?' + params.toString();
}

// Close modals when clicking outside
window.onclick = function(event) {
    const bulkPayoutModal = document.getElementById('bulkPayoutModal');
    const detailsModal = document.getElementById('detailsModal');
    
    if (event.target === bulkPayoutModal) {
        closeBulkPayoutModal();
    }
    if (event.target === detailsModal) {
        closeDetailsModal();
    }
}

// Auto-hide success messages
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 3000);
</script>

<?php include '../templates/layouts/admin/footer.php'; ?>