<?php
require 'element/connection.php';
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$sessionId = $_SESSION['user_id'];

// Fetch user details securely with prepared statement
$user_query = mysqli_prepare($conn, "SELECT * FROM users WHERE user_id = ?");
mysqli_stmt_bind_param($user_query, "i", $sessionId);
mysqli_stmt_execute($user_query);
$user_result = mysqli_stmt_get_result($user_query);
$user = mysqli_fetch_assoc($user_result);

if (!$user) {
    session_destroy();
    header("Location: login.php");
    exit();
}

// Generate referral link
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
$referral_link = $base_url . "/register.php?referrer=" . urlencode($user['user_id']);

// Get referral statistics
$referral_stats_query = mysqli_prepare($conn, "SELECT COUNT(*) as total_referrals FROM users WHERE referred_by = ?");
mysqli_stmt_bind_param($referral_stats_query, "i", $user['user_id']);
mysqli_stmt_execute($referral_stats_query);
$stats_result = mysqli_stmt_get_result($referral_stats_query);
$referral_stats = mysqli_fetch_assoc($stats_result);

// Get recent referrals
$recent_ref_query = mysqli_prepare($conn, "SELECT name, email, created_at FROM users WHERE referred_by = ? ORDER BY created_at DESC LIMIT 5");
mysqli_stmt_bind_param($recent_ref_query, "i", $user['user_id']);
mysqli_stmt_execute($recent_ref_query);
$recent_ref_result = mysqli_stmt_get_result($recent_ref_query);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title><?php echo htmlspecialchars($user['name']); ?> || Referral Program</title>
    <meta content="" name="description">
    <meta content="" name="keywords">

    <!-- Favicons -->
    <link href="../img/logo/logo22222.png" rel="icon">

    <!-- Google Fonts -->
    <link href="https://fonts.gstatic.com" rel="preconnect">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/quill/quill.snow.css" rel="stylesheet">
    <link href="assets/vendor/quill/quill.bubble.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">

    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --warning-gradient: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%);
            --primary-color: #667eea;
            --secondary-color: #764ba2;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
        }

        /* Modern Card Design */
        .modern-card {
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            border: none;
            transition: all 0.3s ease;
            overflow: hidden;
            margin-bottom: 25px;
        }

        .modern-card:hover {
            box-shadow: 0 30px 60px rgba(102, 126, 234, 0.15);
        }

        .card-header-modern {
            padding: 25px 30px;
            background: var(--primary-gradient);
            color: white;
            border-bottom: none;
        }

        .card-header-modern h5 {
            margin: 0;
            font-weight: 700;
            font-size: 1.3rem;
            letter-spacing: 0.5px;
        }

        /* Welcome Letter */
        .welcome-letter {
            background: linear-gradient(135deg, #667eea10 0%, #764ba210 100%);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            border: 1px solid rgba(102, 126, 234, 0.2);
            position: relative;
            overflow: hidden;
        }

        .welcome-letter::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .welcome-letter h3 {
            color: #1e293b;
            font-weight: 700;
            margin-bottom: 15px;
        }

        .welcome-letter p {
            color: #475569;
            line-height: 1.8;
            margin-bottom: 20px;
        }

        .welcome-signature {
            font-style: italic;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
            padding-top: 20px;
            margin-top: 20px;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            text-align: center;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.15);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
            font-size: 24px;
            background: var(--primary-gradient);
            color: white;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #64748b;
            font-weight: 600;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* Referral Link Box */
        .referral-box {
            background: #f8fafc;
            border-radius: 16px;
            padding: 20px;
            margin: 20px 0;
            border: 2px dashed #cbd5e1;
        }

        .referral-link-container {
            display: flex;
            gap: 10px;
            align-items: center;
            background: white;
            border-radius: 12px;
            padding: 5px;
            border: 1px solid #e2e8f0;
        }

        .referral-link-container input {
            flex: 1;
            border: none;
            padding: 12px 15px;
            font-size: 0.95rem;
            background: transparent;
            color: #1e293b;
            font-family: monospace;
        }

        .referral-link-container input:focus {
            outline: none;
        }

        .copy-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 10px;
            background: var(--primary-gradient);
            color: white;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .copy-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .copy-btn.copied {
            background: #10b981;
        }

        /* Share Buttons */
        .share-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            gap: 15px;
            margin: 30px 0;
        }

        .share-btn {
            padding: 15px;
            border: none;
            border-radius: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            color: white;
            border: none;
        }

        .share-btn i {
            font-size: 24px;
        }

        .share-btn:hover {
            transform: translateY(-5px);
            filter: brightness(1.1);
        }

        .share-btn.whatsapp { background: #25D366; }
        .share-btn.telegram { background: #0088cc; }
        .share-btn.facebook { background: #1877f2; }
        .share-btn.twitter { background: #1DA1F2; }
        .share-btn.email { background: #EA4335; }
        .share-btn.linkedin { background: #0077b5; }

        /* QR Code */
        .qr-container {
            background: white;
            border-radius: 20px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-top: 20px;
        }

        .qr-code {
            width: 200px;
            height: 200px;
            margin: 0 auto;
            background: #f1f5f9;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* Table Styles */
        .table-container {
            background: white;
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
        }

        .recent-ref-table {
            width: 100%;
        }

        .recent-ref-table th {
            padding: 15px;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            font-size: 0.8rem;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e2e8f0;
        }

        .recent-ref-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #f1f5f9;
            color: #334155;
        }

        .recent-ref-table tr:hover td {
            background: #f8fafc;
        }

        /* Modal */
        .share-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .share-modal.show {
            opacity: 1;
            visibility: visible;
        }

        .modal-content-custom {
            background: white;
            border-radius: 30px;
            max-width: 500px;
            width: 90%;
            padding: 40px;
            position: relative;
            transform: scale(0.9);
            transition: all 0.3s ease;
        }

        .share-modal.show .modal-content-custom {
            transform: scale(1);
        }

        .modal-close {
            position: absolute;
            top: 20px;
            right: 20px;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #94a3b8;
        }

        .toast-notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #1e293b;
            color: white;
            padding: 12px 24px;
            border-radius: 50px;
            font-weight: 500;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.3s ease;
            z-index: 10000;
        }

        .toast-notification.show {
            transform: translateY(0);
            opacity: 1;
        }

        .toast-notification.success {
            background: #10b981;
        }

        .toast-notification.error {
            background: #ef4444;
        }
    </style>
</head>

<body>

    <!-- Header & Sidebar -->
    <?php include 'element/header.php'; ?>
    <?php include 'element/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Referral Program</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Referral Program</li>
                </ol>
            </nav>
        </div>

        <!-- Welcome Letter -->
        <div class="welcome-letter animate-slide">
            <h3>Welcome to SDB Innovations Private Limited! 🎉</h3>
            <p>Dear <?php echo htmlspecialchars($user['name']); ?>,</p>
            <p>We're excited to have you as part of our growing community! Share your unique referral link with friends and colleagues, and earn rewards when they join. The more people you refer, the more benefits you unlock.</p>
            <div class="welcome-signature">
                <i class="fas fa-hand-peace me-2"></i> Warm regards,<br>
                <strong>The SDB Innovations Team</strong>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-value"><?php echo $referral_stats['total_referrals']; ?></div>
                <div class="stat-label">Total Referrals</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-star"></i>
                </div>
                <div class="stat-value">Level 1</div>
                <div class="stat-label">Referral Level</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-gift"></i>
                </div>
                <div class="stat-value">₹0</div>
                <div class="stat-label">Earnings</div>
            </div>
        </div>

        <!-- Main Referral Card -->
        <div class="modern-card">
            <div class="card-header-modern">
                <h5><i class="fas fa-share-alt me-2"></i> Your Referral Link</h5>
            </div>
            <div class="card-body p-4">
                <!-- Referral Link Box -->
                <div class="referral-box">
                    <label class="form-label fw-bold mb-3">
                        <i class="fas fa-link me-2"></i>Share this link with your friends
                    </label>
                    <div class="referral-link-container">
                        <input type="text" id="referralLink" value="<?php echo htmlspecialchars($referral_link); ?>" readonly>
                        <button class="copy-btn" onclick="copyReferralLink(this)">
                            <i class="fas fa-copy"></i> Copy
                        </button>
                    </div>
                </div>

                <!-- Quick Share Buttons -->
                <label class="form-label fw-bold mb-3">
                    <i class="fas fa-share-alt me-2"></i>Quick Share
                </label>
                <div class="share-grid">
                    <button class="share-btn whatsapp" onclick="shareVia('whatsapp')">
                        <i class="fab fa-whatsapp"></i>
                        <span>WhatsApp</span>
                    </button>
                    <button class="share-btn telegram" onclick="shareVia('telegram')">
                        <i class="fab fa-telegram"></i>
                        <span>Telegram</span>
                    </button>
                    <button class="share-btn facebook" onclick="shareVia('facebook')">
                        <i class="fab fa-facebook"></i>
                        <span>Facebook</span>
                    </button>
                    <button class="share-btn twitter" onclick="shareVia('twitter')">
                        <i class="fab fa-twitter"></i>
                        <span>Twitter</span>
                    </button>
                    <button class="share-btn email" onclick="shareVia('email')">
                        <i class="fas fa-envelope"></i>
                        <span>Email</span>
                    </button>
                    <button class="share-btn linkedin" onclick="shareVia('linkedin')">
                        <i class="fab fa-linkedin"></i>
                        <span>LinkedIn</span>
                    </button>
                </div>

                <!-- QR Code -->
                <div class="qr-container">
                    <label class="form-label fw-bold mb-3">
                        <i class="fas fa-qrcode me-2"></i>Scan QR Code
                    </label>
                    <div class="qr-code" id="qrCode">
                        <!-- QR code will be generated here -->
                        <i class="fas fa-qrcode fa-4x text-muted"></i>
                    </div>
                    <p class="text-muted mt-2 small">Scan to open referral link</p>
                </div>
            </div>
        </div>

        <!-- Recent Referrals -->
        <div class="modern-card">
            <div class="card-header-modern">
                <h5><i class="fas fa-history me-2"></i> Recent Referrals</h5>
            </div>
            <div class="card-body p-4">
                <div class="table-container">
                    <table class="recent-ref-table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Joined Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (mysqli_num_rows($recent_ref_result) > 0): ?>
                                <?php while ($ref = mysqli_fetch_assoc($recent_ref_result)): ?>
                                <tr>
                                    <td><i class="fas fa-user-circle me-2 text-primary"></i><?php echo htmlspecialchars($ref['name']); ?></td>
                                    <td><?php echo htmlspecialchars($ref['email']); ?></td>
                                    <td><?php echo date('d M Y', strtotime($ref['created_at'])); ?></td>
                                    <td><span class="badge bg-success">Active</span></td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center py-4">
                                        <i class="fas fa-user-plus fa-3x text-muted mb-3"></i>
                                        <p class="text-muted">No referrals yet. Share your link to get started!</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Referral Benefits -->
        <div class="modern-card">
            <div class="card-header-modern">
                <h5><i class="fas fa-gift me-2"></i> Referral Benefits</h5>
            </div>
            <div class="card-body p-4">
                <div class="row g-4">
                    <div class="col-md-4">
                        <div class="text-center">
                            <div class="stat-icon" style="background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);">
                                <i class="fas fa-rupee-sign"></i>
                            </div>
                            <h5 class="mt-3 fw-bold">Cash Rewards</h5>
                            <p class="text-muted">Earn ₹100 for every successful referral</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <div class="stat-icon" style="background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);">
                                <i class="fas fa-trophy"></i>
                            </div>
                            <h5 class="mt-3 fw-bold">Bonus Points</h5>
                            <p class="text-muted">Get 500 bonus points for 5+ referrals</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="text-center">
                            <div class="stat-icon" style="background: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%);">
                                <i class="fas fa-crown"></i>
                            </div>
                            <h5 class="mt-3 fw-bold">Premium Upgrades</h5>
                            <p class="text-muted">Unlock premium features with 10+ referrals</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Footer -->
    <footer id="footer" class="footer">
        <div class="copyright">
            &copy; Copyright <strong><span>Healthy Life Mission</span></strong>. All Rights Reserved
        </div>
    </footer>

    <a href="#" class="back-to-top d-flex align-items-center justify-content-center">
        <i class="bi bi-arrow-up-short"></i>
    </a>

    <!-- Toast Notification -->
    <div class="toast-notification" id="toast">
        <i class="fas fa-check-circle me-2"></i>
        <span id="toastMessage">Link copied to clipboard!</span>
    </div>

    <!-- Scripts -->
    <script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>

    <script>
        const referralLink = "<?php echo $referral_link; ?>";
        const userName = "<?php echo htmlspecialchars($user['name']); ?>";
        const welcomeMessage = `Welcome to SDB Innovations Private Limited! 🎉\n\nJoin using my referral link and become part of our growing community.\n\n${referralLink}\n\nSee you inside! 🚀`;

        // Generate QR Code
        document.addEventListener('DOMContentLoaded', function() {
            const qrContainer = document.getElementById('qrCode');
            qrContainer.innerHTML = ''; // Clear existing content
            new QRCode(qrContainer, {
                text: referralLink,
                width: 180,
                height: 180,
                colorDark: "#667eea",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        });

        // Copy referral link
        function copyReferralLink(button) {
            const linkInput = document.getElementById('referralLink');
            linkInput.select();
            linkInput.setSelectionRange(0, 99999); // For mobile devices
            
            try {
                document.execCommand('copy');
                showToast('Link copied to clipboard!', 'success');
                
                // Visual feedback
                button.classList.add('copied');
                button.innerHTML = '<i class="fas fa-check"></i> Copied!';
                
                setTimeout(() => {
                    button.classList.remove('copied');
                    button.innerHTML = '<i class="fas fa-copy"></i> Copy';
                }, 3000);
            } catch (err) {
                showToast('Failed to copy link', 'error');
            }
        }

        // Share via social media
        function shareVia(platform) {
            const encodedUrl = encodeURIComponent(referralLink);
            const encodedMessage = encodeURIComponent(welcomeMessage);
            let shareUrl = '';

            switch(platform) {
                case 'whatsapp':
                    shareUrl = `https://wa.me/?text=${encodedMessage}`;
                    break;
                case 'telegram':
                    shareUrl = `https://t.me/share/url?url=${encodedUrl}&text=${encodeURIComponent('Join me on SDB Innovations!')}`;
                    break;
                case 'facebook':
                    shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`;
                    break;
                case 'twitter':
                    shareUrl = `https://twitter.com/intent/tweet?url=${encodedUrl}&text=${encodeURIComponent('Join me on SDB Innovations!')}`;
                    break;
                case 'email':
                    shareUrl = `mailto:?subject=${encodeURIComponent('Join me on SDB Innovations')}&body=${encodedMessage}`;
                    break;
                case 'linkedin':
                    shareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`;
                    break;
            }

            if (shareUrl) {
                window.open(shareUrl, '_blank', 'width=600,height=400');
            }
        }

        // Show toast notification
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            const toastMessage = document.getElementById('toastMessage');
            
            toast.className = 'toast-notification ' + type;
            toastMessage.textContent = message;
            toast.classList.add('show');
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // Copy on click anywhere in the referral box
        document.querySelector('.referral-link-container')?.addEventListener('click', function(e) {
            if (e.target.tagName !== 'BUTTON') {
                const copyBtn = this.querySelector('.copy-btn');
                copyReferralLink(copyBtn);
            }
        });

        // Animation on scroll
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, observerOptions);

        document.querySelectorAll('.stat-card, .modern-card').forEach(el => {
            el.style.opacity = '0';
            el.style.transform = 'translateY(20px)';
            el.style.transition = 'all 0.5s ease';
            observer.observe(el);
        });

        // Add smooth scrolling
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({ behavior: 'smooth' });
                }
            });
        });
    </script>

</body>
</html>