<?php
// Safely start session
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

// Require database configuration
require_once 'config.php';

$user_number = $_SESSION['number'] ?? $_SESSION['mobile'] ?? $_SESSION['phone'] ?? $_SESSION['username'] ?? null; 

// Default values
$my_refercode = "ERROR";
$username = "Member" . rand(1000, 9999);
$recent_refers = [];

// Fetch user data safely
if ($user_number && isset($pdo)) {
    try {
        $stmt = $pdo->prepare("SELECT refercode, member_name FROM users WHERE number = ?");
        $stmt->execute([$user_number]);
        if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $my_refercode = !empty($user['refercode']) ? $user['refercode'] : "N/A";
            $username = !empty($user['member_name']) ? $user['member_name'] : "Member" . strtoupper(substr(md5($user_number), 0, 8));
        }
    } catch (PDOException $e) {
        try {
            $stmt = $pdo->prepare("SELECT refercode FROM users WHERE number = ?");
            $stmt->execute([$user_number]);
            if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $my_refercode = !empty($user['refercode']) ? $user['refercode'] : "N/A";
                $username = "Member" . strtoupper(substr(md5($user_number), 0, 8));
            }
        } catch (PDOException $e2) {
            $my_refercode = "DB_ERR";
        }
    }

    // Fetch Last 5 Referrals
    if ($my_refercode !== "ERROR" && $my_refercode !== "N/A" && $my_refercode !== "DB_ERR") {
        try {
            // Adjust 'created_at' if your timestamp column is named differently
            $stmt_ref = $pdo->prepare("SELECT member_name, number, created_at FROM users WHERE referedby = ? ORDER BY id DESC LIMIT 5");
            $stmt_ref->execute([$my_refercode]);
            $recent_refers = $stmt_ref->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            // Silently ignore if column doesn't exist
        }
    }
}

// Generate the unique referral URL
$refer_url = "https://pakclub24.club/signup.php?ref=" . $my_refercode;
$qr_api_url = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&margin=0&data=" . urlencode($refer_url);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
    <title>Share</title>
    <!-- FontAwesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- html2canvas for saving the poster as an image -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    
    <style>
        /* ========================================================
           HEADER
           ======================================================== */
        .header {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 15px 20px;
            background-color: var(--bg-header);
            position: relative;
            font-size: 18px;
            font-weight: 700;
            border-bottom: 1px solid var(--border-color);
        }

        .header .back-btn {
            position: absolute;
            left: 20px;
            color: var(--text-main);
            font-size: 20px;
            cursor: pointer;
            text-decoration: none;
        }

        /* ========================================================
           POSTER CONTAINER
           ======================================================== */
        .poster-wrapper {
            padding: 20px 15px;
        }

        #share-poster {
            background-color: #000000;
            border-radius: 12px;
            overflow: hidden;
            border: 1px solid var(--border-color);
            box-shadow: none; 
            position: relative;
        }

        .promo-img {
            width: 100%;
            display: block;
            border-bottom: 2px solid #222;
        }

        .black-div {
            background-color: #000000;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .info-left {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .profile-row {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .profile-img {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            object-fit: cover;
        }

        .username {
            font-size: 14px;
            font-weight: 600;
            color: #e0e0e0;
        }

        .data-row {
            font-size: 13px;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .data-row .highlight {
            color: var(--primary-orange);
            font-weight: 600;
        }

        .g-icon { width: 16px; height: 16px; }

        .qr-wrapper {
            background: #ffffff;
            padding: 5px;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .qr-code { width: 65px; height: 65px; display: block; }

        /* ========================================================
           ACTION BUTTONS & SOCIALS
           ======================================================== */
        .save-btn-wrapper {
            padding: 0 15px;
            margin-top: 10px;
            display: flex;
            justify-content: center;
        }

        .btn-save {
            background-color: var(--primary-orange);
            color: var(--text-main);
            border: none;
            padding: 12px 40px;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            box-shadow: 0 3px 0 #b86a12;
            transition: transform 0.1s;
        }

        .btn-save:active { transform: translateY(3px); box-shadow: none; }

        .share-divider {
            text-align: center;
            margin: 30px 15px 20px 15px;
            position: relative;
            color: var(--text-muted);
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .share-divider::before, .share-divider::after {
            content: "";
            height: 1px;
            width: 30px;
            background-color: var(--border-color);
        }

        .social-row {
            display: flex;
            justify-content: space-between;
            padding: 0 20px 30px 20px;
        }

        .social-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            text-decoration: none;
        }

        .social-icon {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background-color: var(--primary-orange);
            display: flex;
            justify-content: center;
            align-items: center;
            color: var(--text-main);
            font-size: 22px;
            transition: background-color 0.2s;
        }

        .social-label {
            font-size: 11px;
            color: var(--text-muted);
        }

        /* ========================================================
           RECENT REFERRALS LIST
           ======================================================== */
        .refers-wrapper {
            padding: 0 20px;
            margin-top: 10px;
        }

        .refers-title {
            font-size: 15px;
            font-weight: 700;
            color: var(--text-main);
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        .refer-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(255,255,255,0.03);
        }

        .refer-item:last-child { border-bottom: none; }

        .refer-left {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .refer-avatar {
            width: 32px;
            height: 32px;
            background-color: var(--bg-header);
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: var(--primary-orange);
            font-size: 14px;
        }

        .refer-name {
            font-size: 14px;
            color: #e0e0e0;
            font-weight: 500;
        }

        .refer-date {
            font-size: 12px;
            color: var(--text-muted);
        }

        .no-refers {
            text-align: center;
            color: var(--text-muted);
            font-size: 13px;
            padding: 20px 0;
        }

        /* ========================================================
           TOAST NOTIFICATION
           ======================================================== */
        #toast-container {
            position: fixed;
            bottom: 50px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
            display: flex;
            flex-direction: column;
            gap: 10px;
            pointer-events: none;
            width: max-content;
            max-width: 90%;
        }

        .toast {
            background-color: rgba(28, 28, 30, 0.95);
            -webkit-backdrop-filter: blur(10px);
            backdrop-filter: blur(10px);
            color: var(--text-main);
            padding: 12px 24px;
            border-radius: 30px;
            font-size: 13px;
            font-weight: 400;
            text-align: center;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        }

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

    </style>
</head>
<body>

    <!-- HIDDEN HEADER INCLUDE -->
    <div style="display: none; visibility: hidden; opacity: 0; width: 0; height: 0; overflow: hidden; position: absolute;">
        <?php include 'external/header.php'; ?>
    </div>

    <!-- Header -->
    <div class="header">
        <a href="earn.php" class="back-btn"><i class="fa-solid fa-angle-left"></i></a>
        Share
    </div>

    <!-- Visual Feedback Container -->
    <div id="toast-container"></div>

    <!-- Poster Region -->
    <div class="poster-wrapper">
        <div id="share-poster">
            <img src="https://pakclub.club/img/6004/other/125112903-31246-file_20260414125112886.webp" class="promo-img" alt="Promo" crossorigin="anonymous">
            
            <div class="black-div">
                <div class="info-left">
                    <div class="profile-row">
                        <img src="https://pakclub.club/images/1-BpxbCNk8.webp" class="profile-img" alt="Profile" crossorigin="anonymous">
                        <span class="username"><?php echo htmlspecialchars($username); ?></span>
                    </div>
                    <div class="data-row">
                        Invite code: <span class="highlight"><?php echo htmlspecialchars($my_refercode); ?></span>
                    </div>
                    <div class="data-row">
                        <svg class="g-icon" viewBox="0 0 24 24">
                            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                            <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                        </svg>
                        Google Search: <span class="highlight">pakclub24.club</span>
                    </div>
                </div>
                
                <div class="info-right">
                    <div class="qr-wrapper">
                        <img src="<?php echo $qr_api_url; ?>" class="qr-code" alt="QR Code" crossorigin="anonymous">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Save Button -->
    <div class="save-btn-wrapper">
        <button class="btn-save" id="download-btn" onclick="downloadPoster()">Save image</button>
    </div>

    <!-- Share Section -->
    <div class="share-divider">
        <i class="fa-solid fa-spade" style="font-size: 10px;"></i> Share to other apps to invite friend
    </div>

    <div class="social-row">
        <a href="javascript:void(0)" onclick="shareTo('whatsapp')" class="social-item">
            <div class="social-icon"><i class="fa-brands fa-whatsapp"></i></div>
            <div class="social-label">Whatsapp</div>
        </a>
        <a href="javascript:void(0)" onclick="shareTo('telegram')" class="social-item">
            <div class="social-icon"><i class="fa-brands fa-telegram"></i></div>
            <div class="social-label">Telegram</div>
        </a>
        <a href="javascript:void(0)" onclick="shareTo('facebook')" class="social-item">
            <div class="social-icon"><i class="fa-brands fa-facebook-f"></i></div>
            <div class="social-label">Facebook</div>
        </a>
        <a href="javascript:void(0)" onclick="shareTo('twitter')" class="social-item">
            <!-- Fail-proof Native SVG for 'X' Logo -->
            <div class="social-icon">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="width: 20px; height: 20px; fill: currentColor;">
                    <path d="M389.2 48h70.6L305.6 224.2 487 464H345L233.7 318.6 106.5 464H35.8L200.7 275.5 26.8 48H172.4L272.9 180.9 389.2 48zM364.4 421.8h39.1L151.1 88h-42L364.4 421.8z"/>
                </svg>
            </div>
            <div class="social-label">Twitter</div>
        </a>
        <div onclick="copyReferLink()" class="social-item">
            <div class="social-icon" id="copy-link-icon"><i class="fa-solid fa-link"></i></div>
            <div class="social-label">Copy Link</div>
        </div>
    </div>

    <!-- Last 5 Referrals Section -->
    <div class="refers-wrapper">
        <div class="refers-title">Recent Referrals</div>
        
        <?php if (empty($recent_refers)): ?>
            <div class="no-refers">No referrals yet.</div>
        <?php else: ?>
            <div class="refers-list">
                <?php foreach ($recent_refers as $ref): ?>
                    <?php
                        // Determine name to show
                        $display_name = !empty($ref['member_name']) ? $ref['member_name'] : $ref['number'];
                        
                        // Mask middle digits for privacy if it's a raw phone number
                        if (is_numeric($display_name) && strlen($display_name) > 6) {
                            $display_name = substr($display_name, 0, 3) . '****' . substr($display_name, -3);
                        }

                        // Format date nicely
                        $date_str = isset($ref['created_at']) ? date('M d, H:i', strtotime($ref['created_at'])) : '';
                    ?>
                    <div class="refer-item">
                        <div class="refer-left">
                            <div class="refer-avatar"><i class="fa-solid fa-user"></i></div>
                            <div class="refer-name"><?php echo htmlspecialchars($display_name); ?></div>
                        </div>
                        <div class="refer-date"><?php echo htmlspecialchars($date_str); ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        const referLink = "<?php echo $refer_url; ?>";
        const referMessage = "Join PakClub and start earning today! Use my invite code: <?php echo $my_refercode; ?>";

        function showToast(message) {
            const container = document.getElementById('toast-container');
            const existingToasts = container.querySelectorAll('.toast');
            for (let t of existingToasts) {
                if (t.innerText.trim() === message.trim()) return; 
            }

            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.innerText = message;
            container.appendChild(toast);
            
            setTimeout(() => toast.classList.add('show'), 10);
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => toast.remove(), 300);
            }, 2500);
        }

        function downloadPoster() {
            const btn = document.getElementById('download-btn');
            btn.innerText = "Saving...";
            
            const element = document.getElementById('share-poster');
            
            html2canvas(element, {
                useCORS: true,
                allowTaint: false,
                scale: 2, 
                backgroundColor: null
            }).then(canvas => {
                const image = canvas.toDataURL("image/png");
                const link = document.createElement('a');
                link.download = 'PakClub_Invite_<?php echo $my_refercode; ?>.png';
                link.href = image;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                btn.innerText = "Save image";
                showToast("Image saved successfully");
            }).catch(err => {
                btn.innerText = "Save image";
                showToast("Failed to save image. Try again.");
                console.error(err);
            });
        }

        function copyReferLink() {
            navigator.clipboard.writeText(referLink).then(function() {
                const iconDiv = document.getElementById('copy-link-icon');
                const originalHtml = iconDiv.innerHTML;
                
                iconDiv.innerHTML = '<i class="fa-solid fa-check"></i>';
                iconDiv.style.backgroundColor = '#32c149'; 
                
                setTimeout(() => {
                    iconDiv.innerHTML = originalHtml;
                    iconDiv.style.backgroundColor = ''; 
                }, 2000);
            }).catch(function() {
                showToast("Failed to copy link");
            });
        }

        function shareTo(platform) {
            let url = "";
            const encodedLink = encodeURIComponent(referLink);
            const encodedText = encodeURIComponent(referMessage);

            switch(platform) {
                case 'whatsapp':
                    url = `https://api.whatsapp.com/send?text=${encodedText}%0A${encodedLink}`;
                    break;
                case 'telegram':
                    url = `https://t.me/share/url?url=${encodedLink}&text=${encodedText}`;
                    break;
                case 'facebook':
                    url = `https://www.facebook.com/sharer/sharer.php?u=${encodedLink}`;
                    break;
                case 'twitter':
                    url = `https://twitter.com/intent/tweet?text=${encodedText}&url=${encodedLink}`;
                    break;
            }

            if (url) {
                window.open(url, '_blank');
            }
        }
    </script>

</body>
</html>