<?php
/**
 * Admin Affiliates Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Affiliates';

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $affiliate_id = (int)$_POST['affiliate_id'];
    $status = sanitize($_POST['status']);
    
    try {
        $stmt = $pdo->prepare("UPDATE affiliates SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$status, $affiliate_id]);
        
        // Send email notification if approved
        if ($status === 'active') {
            send_affiliate_approved_email($affiliate_id);
        }
        
        set_flash_message('Affiliate status updated!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to update status.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle commission rate update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_commission'])) {
    $affiliate_id = (int)$_POST['affiliate_id'];
    $commission_rate = (float)$_POST['commission_rate'];
    
    try {
        $stmt = $pdo->prepare("UPDATE affiliates SET commission_rate = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$commission_rate, $affiliate_id]);
        set_flash_message('Commission rate updated!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to update commission rate.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filters
$status_filter = sanitize($_GET['status'] ?? '');

// Build query
$sql = "SELECT a.*, u.name as user_name, u.email as user_email,
        (SELECT COUNT(*) FROM affiliate_referrals WHERE affiliate_id = a.id) as referral_count,
        (SELECT COALESCE(SUM(commission_amount), 0) FROM affiliate_referrals WHERE affiliate_id = a.id AND status = 'approved') as total_earnings
        FROM affiliates a 
        JOIN users u ON a.user_id = u.id 
        WHERE 1=1";
$count_sql = "SELECT COUNT(*) FROM affiliates a WHERE 1=1";
$params = [];

if ($status_filter) {
    $sql .= " AND a.status = ?";
    $count_sql .= " AND a.status = ?";
    $params[] = $status_filter;
}

$sql .= " ORDER BY a.created_at DESC LIMIT ? OFFSET ?";

// Get total count
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_affiliates = $stmt->fetchColumn();
$total_pages = ceil($total_affiliates / $per_page);

// Get affiliates
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge($params, [$per_page, $offset]));
$affiliates = $stmt->fetchAll();

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-user-friends me-2"></i>Affiliate Program</h1>
    </div>
    
    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        <option value="suspended" <?php echo $status_filter === 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter me-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Affiliates Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Affiliate</th>
                            <th>Code</th>
                            <th>Commission</th>
                            <th>Referrals</th>
                            <th>Earnings</th>
                            <th>Status</th>
                            <th>Joined</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($affiliates as $affiliate): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="user-avatar me-2">
                                        <?php echo strtoupper(substr($affiliate['user_name'], 0, 1)); ?>
                                    </div>
                                    <div>
                                        <strong><?php echo sanitize($affiliate['user_name']); ?></strong>
                                        <small class="d-block text-muted"><?php echo sanitize($affiliate['user_email']); ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <code><?php echo $affiliate['affiliate_code']; ?></code>
                            </td>
                            <td><?php echo $affiliate['commission_rate']; ?>%</td>
                            <td><?php echo number_format($affiliate['referral_count']); ?></td>
                            <td><strong class="text-success"><?php echo format_price($affiliate['total_earnings']); ?></strong></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo match($affiliate['status']) {
                                        'active' => 'success',
                                        'pending' => 'warning',
                                        'rejected' => 'danger',
                                        'suspended' => 'secondary',
                                        default => 'secondary'
                                    };
                                ?>">
                                    <?php echo ucfirst($affiliate['status']); ?>
                                </span>
                            </td>
                            <td><?php echo format_date($affiliate['created_at']); ?></td>
                            <td>
                                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $affiliate['id']; ?>">
                                    <i class="fas fa-edit"></i>
                                </button>
                            </td>
                        </tr>
                        
                        <!-- Edit Modal -->
                        <div class="modal fade" id="editModal<?php echo $affiliate['id']; ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content bg-dark">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Edit Affiliate</h5>
                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <form method="POST" class="mb-4">
                                            <input type="hidden" name="affiliate_id" value="<?php echo $affiliate['id']; ?>">
                                            <div class="mb-3">
                                                <label class="form-label">Status</label>
                                                <select name="status" class="form-select">
                                                    <option value="pending" <?php echo $affiliate['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="active" <?php echo $affiliate['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                                    <option value="rejected" <?php echo $affiliate['status'] === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                                    <option value="suspended" <?php echo $affiliate['status'] === 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                                                </select>
                                            </div>
                                            <button type="submit" name="update_status" class="btn btn-primary">Update Status</button>
                                        </form>
                                        
                                        <form method="POST">
                                            <input type="hidden" name="affiliate_id" value="<?php echo $affiliate['id']; ?>">
                                            <div class="mb-3">
                                                <label class="form-label">Commission Rate (%)</label>
                                                <input type="number" name="commission_rate" class="form-control" 
                                                       value="<?php echo $affiliate['commission_rate']; ?>" 
                                                       min="1" max="100" step="0.01">
                                            </div>
                                            <button type="submit" name="update_commission" class="btn btn-primary">Update Commission</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="card-footer">
            <nav>
                <ul class="pagination justify-content-center mb-0">
                    <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

<style>
.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: var(--primary);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 600;
}
</style>

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