<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';

if (!isset($_SESSION['affiliate_id'])) {
    header('Location: login.php');
    exit;
}

$affiliate_id = (int)$_SESSION['affiliate_id'];
$affiliate = $conn->query("SELECT * FROM affiliates WHERE id = $affiliate_id")->fetch_assoc();

// Get stats
$total_referrals = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE affiliate_id = $affiliate_id")->fetch_assoc()['count'];
$pending_referrals = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE affiliate_id = $affiliate_id AND status = 'pending'")->fetch_assoc()['count'];
$approved_referrals = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE affiliate_id = $affiliate_id AND status = 'approved'")->fetch_assoc()['count'];
$paid_referrals = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE affiliate_id = $affiliate_id AND status = 'paid'")->fetch_assoc()['count'];
$total_commission = $conn->query("SELECT SUM(commission_amount) as total FROM affiliate_referrals WHERE affiliate_id = $affiliate_id AND status IN ('approved','paid')")->fetch_assoc()['total'] ?? 0;

// Product & Service clicks
$product_clicks = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE affiliate_id = $affiliate_id AND referral_type = 'product'")->fetch_assoc()['count'] ?? 0;
$service_clicks = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals WHERE affiliate_id = $affiliate_id AND referral_type = 'service'")->fetch_assoc()['count'] ?? 0;

// Get referrals list
$referrals = $conn->query("SELECT r.*, o.order_number, o.total_amount 
                            FROM affiliate_referrals r 
                            LEFT JOIN orders o ON r.order_id = o.id 
                            WHERE r.affiliate_id = $affiliate_id 
                            ORDER BY r.created_at DESC LIMIT 50");

// Get payouts
$payouts = $conn->query("SELECT * FROM affiliate_payouts WHERE affiliate_id = $affiliate_id ORDER BY requested_at DESC LIMIT 20");

$brand = getBrand();
$referral_link = "https://drmdferdous.com/?ref=" . $affiliate['referral_code'];
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Affiliate Dashboard | <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root{--p:#2d6a4f}
        body{background:#f0f2f5;font-family:'Segoe UI',sans-serif}
        .navbar{background:var(--p)!important}
        .stat-card{background:#fff;border-radius:15px;padding:20px;box-shadow:0 3px 15px rgba(0,0,0,.08);border-left:4px solid var(--p);transition:.3s}
        .stat-card:hover{transform:translateY(-5px);box-shadow:0 10px 25px rgba(0,0,0,.1)}
        .stat-number{font-size:2rem;font-weight:800;color:var(--p)}
        .card{border:none;border-radius:15px;box-shadow:0 3px 15px rgba(0,0,0,.08)}
        .card-header{background:var(--p);color:#fff;border-radius:15px 15px 0 0!important}
        .copy-btn{cursor:pointer;transition:.2s}
        .copy-btn:hover{transform:scale(1.1)}
        .badge-pending{background:#ffc107;color:#000}
        .badge-approved{background:#28a745;color:#fff}
        .badge-paid{background:#17a2b8;color:#fff}
        .badge-cancelled{background:#dc3545;color:#fff}
        .sidebar{background:linear-gradient(180deg,#1b4332,#2d6a4f);min-height:100vh;color:#fff;position:fixed;width:250px;z-index:1000;overflow-y:auto;transition:all .3s}
        .sidebar a{color:rgba(255,255,255,.85);text-decoration:none;padding:11px 18px;display:block;margin:2px 10px;border-radius:10px;transition:.3s}
        .sidebar a:hover,.sidebar a.active{background:rgba(255,255,255,.15);color:#fff;transform:translateX(5px)}
        .sidebar a i{width:22px;margin-right:10px}
        .main-content{margin-left:250px;padding:20px}
        .menu-toggle{display:none;position:fixed;top:15px;left:15px;z-index:1001;background:var(--p);color:#fff;border:none;width:40px;height:40px;border-radius:50%;cursor:pointer}
        .link-box{background:#f8f9fa;padding:12px;border-radius:10px;border:1px solid #dee2e6}
        .generated-link{background:#fff;padding:12px;border-radius:8px;border-left:3px solid var(--p);margin-bottom:10px}
        @media(max-width:992px){.menu-toggle{display:block}.sidebar{left:-250px}.sidebar.show{left:0}.main-content{margin-left:0;padding-top:60px}}
        @media(max-width:768px){.stat-number{font-size:1.5rem}}
        @keyframes slideInRight{from{transform:translateX(100%);opacity:0}to{transform:translateX(0);opacity:1}}
    </style>
</head>
<body>
<button class="menu-toggle" id="menuToggle" onclick="document.getElementById('sidebar').classList.toggle('show')"><i class="fas fa-bars"></i></button>

<div class="d-flex">
    <div class="sidebar" id="sidebar">
        <div class="p-3 text-center border-bottom"><h6><i class="fas fa-handshake"></i> Affiliate</h6><small><?= htmlspecialchars($affiliate['name']) ?></small></div>
        <div class="p-2">
            <a href="dashboard.php" class="active"><i class="fas fa-th-large"></i> Dashboard</a>
            <a href="#links"><i class="fas fa-link"></i> Referral Links</a>
            <a href="#products"><i class="fas fa-box"></i> Product Links</a>
            <a href="#services"><i class="fas fa-list-alt"></i> Service Links</a>
            <a href="#referrals"><i class="fas fa-users"></i> Referrals</a>
            <a href="#payouts"><i class="fas fa-money-bill-wave"></i> Payouts</a>
            <hr>
            <a href="../index.php"><i class="fas fa-globe"></i> View Site</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <div class="main-content flex-grow-1">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h4><i class="fas fa-handshake text-success"></i> Affiliate Dashboard</h4>
            <span><?= date('l, d M Y') ?></span>
        </div>

        <!-- Stats -->
        <div class="row g-3 mb-4">
            <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number"><?= $total_referrals ?></div><div class="text-muted">Total Referrals</div></div></div>
            <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number"><?= $pending_referrals ?></div><div class="text-muted">Pending</div></div></div>
            <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number"><?= $approved_referrals ?></div><div class="text-muted">Approved</div></div></div>
            <div class="col-md-3 col-6"><div class="stat-card"><div class="stat-number">৳<?= number_format($total_commission, 2) ?></div><div class="text-muted">Total Commission</div></div></div>
        </div>
        
        <!-- Product & Service Click Stats -->
        <div class="row g-3 mb-4">
            <div class="col-md-3 col-6">
                <div class="stat-card" style="border-left-color:#007bff">
                    <div class="stat-number" style="color:#007bff"><?= $product_clicks ?></div>
                    <div class="text-muted">Product Clicks</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="stat-card" style="border-left-color:#28a745">
                    <div class="stat-number" style="color:#28a745"><?= $service_clicks ?></div>
                    <div class="text-muted">Service Clicks</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="stat-card" style="border-left-color:#17a2b8">
                    <div class="stat-number" style="color:#17a2b8"><?= $affiliate['balance'] ?></div>
                    <div class="text-muted">Available Balance</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="stat-card" style="border-left-color:#6f42c1">
                    <div class="stat-number" style="color:#6f42c1"><?= $affiliate['commission_rate'] ?>%</div>
                    <div class="text-muted">Commission Rate</div>
                </div>
            </div>
        </div>

        <!-- General Referral Link -->
        <div class="card mb-4">
            <div class="card-header">Your General Referral Link</div>
            <div class="card-body">
                <div class="input-group">
                    <input type="text" class="form-control" id="referralLink" value="<?= htmlspecialchars($referral_link) ?>" readonly>
                    <button class="btn btn-primary" onclick="copyToClipboard('referralLink')"><i class="fas fa-copy"></i> Copy</button>
                </div>
                <div class="mt-2">
                    <small class="text-muted">Share this link with your friends and earn commissions!</small>
                </div>
            </div>
        </div>

        <!-- =========================================================
             PRODUCT & SERVICE REFERRAL LINKS
             ========================================================= -->
        <div class="card mb-4" id="products">
            <div class="card-header">
                <i class="fas fa-box"></i> Generate Product Referral Links
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-12">
                        <label class="form-label">Select Product</label>
                        <select class="form-control" id="productSelect" onchange="generateProductLink()">
                            <option value="">-- Select a product --</option>
                            <?php
                            $products = $conn->query("SELECT id, name, price FROM products WHERE is_active = 1");
                            while($p = $products->fetch_assoc()):
                            ?>
                            <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['name']) ?> (৳<?= number_format($p['price']) ?>)</option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
                
                <div class="mt-3" id="productLinkContainer">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> Select a product above to generate your referral link.
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4" id="services">
            <div class="card-header">
                <i class="fas fa-list-alt"></i> Generate Service Referral Links
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-12">
                        <label class="form-label">Select Service</label>
                        <select class="form-control" id="serviceSelect" onchange="generateServiceLink()">
                            <option value="">-- Select a service --</option>
                            <?php
                            $services = $conn->query("SELECT id, title, price FROM services WHERE is_active = 1");
                            while($s = $services->fetch_assoc()):
                            ?>
                            <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['title']) ?> (৳<?= number_format($s['price']) ?>)</option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
                
                <div class="mt-3" id="serviceLinkContainer">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> Select a service above to generate your referral link.
                    </div>
                </div>
            </div>
        </div>

        <!-- Referrals List -->
        <div class="card mt-4" id="referrals">
            <div class="card-header d-flex justify-content-between">
                <span><i class="fas fa-users"></i> Recent Referrals</span>
                <span class="badge bg-light text-dark"><?= $total_referrals ?> total</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr><th>Customer</th><th>Type</th><th>Order</th><th>Amount</th><th>Commission</th><th>Status</th><th>Date</th></tr>
                        </thead>
                        <tbody>
                        <?php if ($referrals && $referrals->num_rows > 0): while($r = $referrals->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($r['referred_customer_email'] ?? 'N/A') ?></td>
                                <td><span class="badge bg-secondary"><?= ucfirst($r['referral_type'] ?? 'general') ?></span></td>
                                <td>#<?= htmlspecialchars($r['order_number'] ?? '—') ?></td>
                                <td>৳<?= number_format($r['total_amount'] ?? 0, 2) ?></td>
                                <td>৳<?= number_format($r['commission_amount'], 2) ?></td>
                                <td><span class="badge badge-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span></td>
                                <td><?= date('d M Y', strtotime($r['created_at'])) ?></td>
                            </tr>
                        <?php endwhile; else: ?>
                            <tr><td colspan="7" class="text-center py-4">No referrals yet. Share your link!</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Payout History -->
        <div class="card mt-4" id="payouts">
            <div class="card-header"><i class="fas fa-money-bill-wave"></i> Payout History</div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr><th>Amount</th><th>Method</th><th>Status</th><th>Date</th></tr>
                        </thead>
                        <tbody>
                        <?php if ($payouts && $payouts->num_rows > 0): while($p = $payouts->fetch_assoc()): ?>
                            <tr>
                                <td>৳<?= number_format($p['amount'], 2) ?></td>
                                <td><?= strtoupper($p['payment_method']) ?></td>
                                <td><span class="badge badge-<?= $p['status'] == 'completed' ? 'success' : ($p['status'] == 'pending' ? 'warning' : 'secondary') ?>"><?= ucfirst($p['status']) ?></span></td>
                                <td><?= date('d M Y', strtotime($p['requested_at'])) ?></td>
                            </tr>
                        <?php endwhile; else: ?>
                            <tr><td colspan="4" class="text-center py-4">No payouts yet</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Request Payout -->
        <div class="card mt-4">
            <div class="card-header">Request Payout</div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label>Available Balance</label>
                        <h4>৳<?= number_format($affiliate['balance'], 2) ?></h4>
                    </div>
                    <div class="col-md-4">
                        <label>Payment Method</label>
                        <select class="form-control" id="payoutMethod">
                            <option value="bkash">bKash</option>
                            <option value="nagad">Nagad</option>
                            <option value="rocket">Rocket</option>
                            <option value="bank">Bank Transfer</option>
                        </select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button class="btn btn-success w-100" onclick="requestPayout()"><i class="fas fa-paper-plane"></i> Request Payout</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const baseUrl = '<?= $referral_link ?>';

function copyToClipboard(elementId) {
    const input = document.getElementById(elementId);
    if (input) {
        input.select();
        document.execCommand('copy');
        showToast('Link copied to clipboard!', 'success');
    }
}

function generateProductLink() {
    const productId = document.getElementById('productSelect').value;
    const container = document.getElementById('productLinkContainer');
    
    if (!productId) {
        container.innerHTML = '<div class="alert alert-info"><i class="fas fa-info-circle"></i> Select a product to generate your referral link.</div>';
        return;
    }
    
    const productName = document.getElementById('productSelect').options[document.getElementById('productSelect').selectedIndex].text;
    const productUrl = baseUrl + '&product_id=' + productId;
    const productPrice = productName.match(/\(৳([\d,]+)\)/)?.[1] || '';
    
    container.innerHTML = `
        <div class="generated-link">
            <h6><i class="fas fa-link text-success"></i> Product Referral Link</h6>
            <div class="input-group mb-2">
                <input type="text" class="form-control" id="productLink" value="${productUrl}" readonly>
                <button class="btn btn-primary" onclick="copyToClipboard('productLink')"><i class="fas fa-copy"></i> Copy</button>
            </div>
            <div class="btn-group flex-wrap">
                <a href="https://wa.me/?text=Check%20out%20this%20product%3A%20${encodeURIComponent(productName)}%20-%20${encodeURIComponent(productUrl)}" target="_blank" class="btn btn-success btn-sm"><i class="fab fa-whatsapp"></i> WhatsApp</a>
                <a href="https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(productUrl)}" target="_blank" class="btn btn-primary btn-sm"><i class="fab fa-facebook"></i> Facebook</a>
                <a href="mailto:?subject=Check%20out%20this%20product&body=I%20thought%20you%20might%20like%20this%20product%3A%20${encodeURIComponent(productName)}%0A%0A${encodeURIComponent(productUrl)}" class="btn btn-secondary btn-sm"><i class="fas fa-envelope"></i> Email</a>
            </div>
            <div class="mt-2">
                <small class="text-muted"><i class="fas fa-info-circle"></i> Share this link to earn commission on this product</small>
            </div>
        </div>
    `;
}

function generateServiceLink() {
    const serviceId = document.getElementById('serviceSelect').value;
    const container = document.getElementById('serviceLinkContainer');
    
    if (!serviceId) {
        container.innerHTML = '<div class="alert alert-info"><i class="fas fa-info-circle"></i> Select a service to generate your referral link.</div>';
        return;
    }
    
    const serviceName = document.getElementById('serviceSelect').options[document.getElementById('serviceSelect').selectedIndex].text;
    const serviceUrl = baseUrl + '&service_id=' + serviceId;
    
    container.innerHTML = `
        <div class="generated-link">
            <h6><i class="fas fa-link text-success"></i> Service Referral Link</h6>
            <div class="input-group mb-2">
                <input type="text" class="form-control" id="serviceLink" value="${serviceUrl}" readonly>
                <button class="btn btn-primary" onclick="copyToClipboard('serviceLink')"><i class="fas fa-copy"></i> Copy</button>
            </div>
            <div class="btn-group flex-wrap">
                <a href="https://wa.me/?text=Check%20out%20this%20service%3A%20${encodeURIComponent(serviceName)}%20-%20${encodeURIComponent(serviceUrl)}" target="_blank" class="btn btn-success btn-sm"><i class="fab fa-whatsapp"></i> WhatsApp</a>
                <a href="https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(serviceUrl)}" target="_blank" class="btn btn-primary btn-sm"><i class="fab fa-facebook"></i> Facebook</a>
                <a href="mailto:?subject=Check%20out%20this%20service&body=I%20thought%20you%20might%20like%20this%20service%3A%20${encodeURIComponent(serviceName)}%0A%0A${encodeURIComponent(serviceUrl)}" class="btn btn-secondary btn-sm"><i class="fas fa-envelope"></i> Email</a>
            </div>
            <div class="mt-2">
                <small class="text-muted"><i class="fas fa-info-circle"></i> Share this link to earn commission on this service</small>
            </div>
        </div>
    `;
}

function requestPayout() {
    const method = document.getElementById('payoutMethod').value;
    const amount = <?= $affiliate['balance'] ?>;
    if (amount <= 0) {
        showToast('Your balance is zero. Refer more customers first!', 'warning');
        return;
    }
    if (confirm(`Request payout of ৳${amount} via ${method.toUpperCase()}?`)) {
        $.post('request_payout.php', { method: method }, function(res) {
            if (res.success) {
                showToast('Payout request submitted successfully!', 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showToast(res.message || 'Error requesting payout', 'error');
            }
        }, 'json');
    }
}

// =========================================================
// TOAST NOTIFICATION SYSTEM
// =========================================================
function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer') || (() => {
        const c = document.createElement('div');
        c.id = 'toastContainer';
        c.style.cssText = 'position:fixed;bottom:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:10px;max-width:400px;width:100%;';
        document.body.appendChild(c);
        return c;
    })();
    
    const toast = document.createElement('div');
    const colors = {
        success: '#28a745',
        error: '#dc3545',
        warning: '#ffc107',
        info: '#17a2b8'
    };
    toast.style.cssText = `
        background: white;
        border-radius: 12px;
        padding: 15px 20px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        border-left: 4px solid ${colors[type] || colors.success};
        display: flex;
        align-items: center;
        gap: 12px;
        animation: slideInRight 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
        transform: translateX(120%);
        opacity: 0;
        font-family: 'Hind Siliguri', sans-serif;
    `;
    
    const icon = type === 'success' ? '✅' : type === 'error' ? '❌' : '⚠️';
    toast.innerHTML = `
        <span style="font-size:1.2rem;">${icon}</span>
        <span style="flex:1;font-size:0.95rem;">${message}</span>
        <button onclick="this.parentElement.remove()" style="background:none;border:none;font-size:1.2rem;cursor:pointer;color:#999;">&times;</button>
    `;
    container.appendChild(toast);
    
    requestAnimationFrame(() => {
        toast.style.transform = 'translateX(0)';
        toast.style.opacity = '1';
    });
    
    setTimeout(() => {
        toast.style.transform = 'translateX(120%)';
        toast.style.opacity = '0';
        toast.style.transition = 'all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
        setTimeout(() => toast.remove(), 500);
    }, 4000);
}

// Close sidebar on mobile when clicking outside
document.addEventListener('click', function(e) {
    const sidebar = document.getElementById('sidebar');
    const toggle = document.getElementById('menuToggle');
    if (window.innerWidth <= 992 && sidebar.classList.contains('show')) {
        if (!sidebar.contains(e.target) && !toggle.contains(e.target)) {
            sidebar.classList.remove('show');
        }
    }
});
</script>
</body>
</html>