<?php
/**
 * Affiliate Program Page
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';

require_login();

$page_title = 'Affiliate Program';

$user_id = get_current_user_id();
$user = get_current_user_data($pdo);

// Check if user has affiliate account
$affiliate = get_affiliate_by_user_id($user_id);

// Handle affiliate signup
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['signup'])) {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        set_flash_message('Invalid request.', 'error');
    } else {
        if (create_affiliate($user_id)) {
            set_flash_message('Your affiliate application has been submitted!', 'success');
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            set_flash_message('Failed to submit application. Please try again.', 'error');
        }
    }
}

// Get affiliate stats if active
$stats = [];
if ($affiliate && $affiliate['status'] === 'active') {
    $stats = get_affiliate_stats($affiliate['id']);
    
    // Get referrals
    $stmt = $pdo->prepare("SELECT ar.*, o.order_number, o.total as order_total, o.created_at as order_date
                          FROM affiliate_referrals ar
                          JOIN orders o ON ar.order_id = o.id
                          WHERE ar.affiliate_id = ?
                          ORDER BY ar.created_at DESC LIMIT 10");
    $stmt->execute([$affiliate['id']]);
    $referrals = $stmt->fetchAll();
}

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

<section class="section">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4" data-aos="fade-up">
            <h1><i class="fas fa-handshake me-2"></i>Affiliate Program</h1>
            <a href="<?php echo BASE_URL; ?>/account/index.php" class="btn btn-outline-light">
                <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
            </a>
        </div>
        
        <?php if (!$affiliate): ?>
            <!-- Affiliate Signup -->
            <div class="row justify-content-center">
                <div class="col-lg-8" data-aos="fade-up">
                    <div class="card text-center">
                        <div class="card-body py-5">
                            <i class="fas fa-handshake fa-4x text-primary mb-4"></i>
                            <h2>Join Our Affiliate Program</h2>
                            <p class="lead text-muted mb-4">
                                Earn commissions by promoting our digital products. 
                                Share your unique referral link and earn <?php echo get_setting('affiliate_commission_rate', '10'); ?>% on every sale!
                            </p>
                            
                            <div class="row g-4 mb-5">
                                <div class="col-md-4">
                                    <div class="p-4 border border-secondary rounded">
                                        <i class="fas fa-link fa-2x text-primary mb-3"></i>
                                        <h5>Get Your Link</h5>
                                        <p class="text-muted small mb-0">Receive a unique referral link</p>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="p-4 border border-secondary rounded">
                                        <i class="fas fa-share-alt fa-2x text-primary mb-3"></i>
                                        <h5>Share & Promote</h5>
                                        <p class="text-muted small mb-0">Share on social media, blogs, etc.</p>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="p-4 border border-secondary rounded">
                                        <i class="fas fa-dollar-sign fa-2x text-primary mb-3"></i>
                                        <h5>Earn Commissions</h5>
                                        <p class="text-muted small mb-0">Get paid for every sale</p>
                                    </div>
                                </div>
                            </div>
                            
                            <form method="POST">
                                <?php echo csrf_field(); ?>
                                <button type="submit" name="signup" class="btn btn-primary btn-lg">
                                    <i class="fas fa-user-plus me-2"></i>Apply Now
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        <?php elseif ($affiliate['status'] === 'pending'): ?>
            <!-- Pending Approval -->
            <div class="row justify-content-center">
                <div class="col-lg-8" data-aos="fade-up">
                    <div class="card text-center">
                        <div class="card-body py-5">
                            <i class="fas fa-clock fa-4x text-warning mb-4"></i>
                            <h2>Application Pending</h2>
                            <p class="text-muted">
                                Your affiliate application is currently under review. 
                                We'll notify you once it's approved.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        <?php elseif ($affiliate['status'] === 'rejected'): ?>
            <!-- Rejected -->
            <div class="row justify-content-center">
                <div class="col-lg-8" data-aos="fade-up">
                    <div class="card text-center">
                        <div class="card-body py-5">
                            <i class="fas fa-times-circle fa-4x text-danger mb-4"></i>
                            <h2>Application Not Approved</h2>
                            <p class="text-muted">
                                Unfortunately, your affiliate application was not approved at this time.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <!-- Active Affiliate Dashboard -->
            <div class="row g-4 mb-5">
                <div class="col-md-6 col-lg-3" data-aos="fade-up" data-aos-delay="0">
                    <div class="stat-card">
                        <div class="stat-icon bg-primary">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-info">
                            <h3><?php echo number_format($stats['total_referrals'] ?? 0); ?></h3>
                            <p>Total Referrals</p>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6 col-lg-3" data-aos="fade-up" data-aos-delay="100">
                    <div class="stat-card">
                        <div class="stat-icon bg-success">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <div class="stat-info">
                            <h3><?php echo format_price($stats['total_earnings'] ?? 0); ?></h3>
                            <p>Total Earnings</p>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6 col-lg-3" data-aos="fade-up" data-aos-delay="200">
                    <div class="stat-card">
                        <div class="stat-icon bg-warning">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="stat-info">
                            <h3><?php echo format_price($stats['pending_earnings'] ?? 0); ?></h3>
                            <p>Pending</p>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6 col-lg-3" data-aos="fade-up" data-aos-delay="300">
                    <div class="stat-card">
                        <div class="stat-icon bg-info">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stat-info">
                            <h3><?php echo format_price($stats['paid_earnings'] ?? 0); ?></h3>
                            <p>Paid Out</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Referral Link -->
            <div class="card mb-4" data-aos="fade-up">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-link me-2"></i>Your Referral Link</h5>
                </div>
                <div class="card-body">
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" id="referralLink" 
                               value="<?php echo BASE_URL; ?>/register.php?ref=<?php echo $affiliate['affiliate_code']; ?>" 
                               readonly>
                        <button class="btn btn-primary" type="button" onclick="copyReferralLink()">
                            <i class="fas fa-copy me-2"></i>Copy
                        </button>
                    </div>
                    <p class="text-muted mb-0">
                        <i class="fas fa-info-circle me-1"></i>
                        Share this link with your audience. When someone registers through your link and makes a purchase, you'll earn a commission!
                    </p>
                </div>
            </div>
            
            <!-- Recent Referrals -->
            <div class="card" data-aos="fade-up">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-history me-2"></i>Recent Referrals</h5>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($referrals)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No referrals yet. Start sharing your link!</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-dark table-hover mb-0">
                                <thead>
                                    <tr>
                                        <th>Order</th>
                                        <th>Date</th>
                                        <th>Order Total</th>
                                        <th>Commission</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($referrals as $referral): ?>
                                    <tr>
                                        <td><?php echo $referral['order_number']; ?></td>
                                        <td><?php echo format_date($referral['order_date']); ?></td>
                                        <td><?php echo format_price($referral['order_total']); ?></td>
                                        <td class="text-success"><?php echo format_price($referral['commission_amount']); ?></td>
                                        <td>
                                            <span class="badge bg-<?php 
                                                echo match($referral['status']) {
                                                    'approved' => 'success',
                                                    'pending' => 'warning',
                                                    'paid' => 'info',
                                                    default => 'secondary'
                                                };
                                            ?>">
                                                <?php echo ucfirst($referral['status']); ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<script>
function copyReferralLink() {
    const linkInput = document.getElementById('referralLink');
    linkInput.select();
    document.execCommand('copy');
    
    // Show toast notification
    showToast('Referral link copied to clipboard!', 'success');
}
</script>

<style>
.stat-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1.5rem;
    background: var(--gradient-card);
    border: 1px solid var(--dark-lighter);
    border-radius: var(--radius);
}

.stat-icon {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: var(--radius);
    font-size: 1.5rem;
    color: var(--white);
}

.stat-info h3 {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
    color: var(--white);
}

.stat-info p {
    margin: 0;
    color: var(--gray-500);
    font-size: 0.875rem;
}
</style>

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