<?php
session_start();
require_once __DIR__ . '/auth/db.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['email'])) {
    die("Not logged in");
}

$email = $_SESSION['email'];

// 1. Get balances and mining status from users table
$stmt = $conn->prepare("SELECT mining_balance, task_balance, referral_balance, mining_start_time FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($miningBalance, $taskBalance, $referralBalance, $miningStartTime);
$stmt->fetch();
$stmt->close();

// Calculate live mining balance if session is active
if ($miningStartTime !== null) {
    $now = time();
    $elapsedHours = ($now - $miningStartTime) / 3600;
    $ratePerHour = 0.025;
    $maxHours = 8;
    $maxReward = $ratePerHour * $maxHours; // 0.2 GBL
    
    // Add current session mined amount to balance
    $sessionMined = min($elapsedHours * $ratePerHour, $maxReward);
    $miningBalance += $sessionMined;
}

// 2. Get user profile info
$user_id = null;
$first = '';
$middle = '';
$surname = '';
$kycStatus = 'Not Submitted';

$stmt = $conn->prepare("SELECT id, first_name, middle_name, surname, kyc_status FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($user_id, $first, $middle, $surname, $kycStatus);
$stmt->fetch();
$stmt->close();

// 3. Get list of referrals (users referred by this user)
$referrals = [];
$stmt = $conn->prepare("SELECT first_name, surname, email FROM users WHERE referred_by = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($ref_first, $ref_surname, $ref_email);
while ($stmt->fetch()) {
    $referrals[] = [
        'first_name' => $ref_first,
        'surname' => $ref_surname,
        'email' => $ref_email
    ];
}
$stmt->close();

// 4. Get count of referrals
$referralCount = 0;
$stmt = $conn->prepare("SELECT COUNT(*) AS total_referrals FROM users WHERE referred_by = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($referralCount);
$stmt->fetch();
$stmt->close();

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>User Profile - Gobolcoin</title>
    <link rel="icon" type="image/png" href="/favicon.png">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --maroon: #8B0000;
            --white: #ffffff;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body, html {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(to top right, #ffffff 70%, #8B0000 130%);
            color: #333;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .logo-box {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(139, 0, 0, 0.9);
            color: white;
            padding: 8px 14px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            z-index: 999;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
        }

        .logo-box img {
            width: 32px;
            height: 32px;
            object-fit: contain;
            margin-right: 10px;
        }

        .logo-box span {
            font-size: 1.2rem;
            font-weight: bold;
        }

        .container {
            max-width: 600px;
            margin: 100px auto 30px auto;
            background: #f9f9f9;
            padding: 2em;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
        }

        .container h1 {
            text-align: center;
            color: var(--maroon);
            margin-bottom: 1em;
        }

        .profile-picture-container {
            position: relative;
            width: 150px;
            height: 150px;
            margin: 20px auto;
            border-radius: 50%;
            overflow: hidden;
            border: 3px solid var(--maroon);
            cursor: pointer;
        }

        .profile-picture-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .upload-overlay {
            position: absolute;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            width: 100%;
            text-align: center;
            padding: 5px;
            color: #fff;
            font-size: 0.9em;
        }

        input[type="file"] {
            display: none;
        }

        .info-block {
            margin-bottom: 1em;
            font-size: 1em;
        }

        .info-block strong {
            display: inline-block;
            width: 150px;
            color: #600000;
        }

        .section {
            margin-top: 2em;
            padding: 1em;
            background-color: #fff;
            border-left: 4px solid var(--maroon);
            border-radius: 8px;
        }

        .section h2 {
            color: var(--maroon);
            margin-bottom: 0.5em;
            font-size: 1.2rem;
        }

        .referral-item {
            font-size: 0.95em;
            margin-left: 10px;
            margin-bottom: 0.5em;
        }

        .kyc-status {
            font-weight: bold;
            color: green;
        }

        footer {
            margin-top: auto;
            width: 100%;
            text-align: center;
            padding: 2em 1em;
            background-color: var(--white);
            color: #777;
            font-size: 0.9em;
        }

        .socials {
            margin-top: 1em;
        }

        .socials a {
            margin: 0 8px;
            display: inline-block;
        }

        .socials img {
            width: 24px;
            height: 24px;
        }

        @media (max-width: 600px) {
            .container {
                margin-top: 120px;
                padding: 1.5em;
            }

            .info-block strong {
                width: 120px;
            }

            .logo-box {
                top: 10px;
                left: 10px;
                padding: 6px 10px;
            }

            .logo-box img {
                width: 26px;
                height: 26px;
            }

            .logo-box span {
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>

<!-- Logo -->
<div class="logo-box">
    <img src="images/gobolcoin-logo.png" alt="Gobolcoin Logo">
    <span>Gobolchain Network</span>
</div>

<!-- Profile Container -->
<div class="container">
    <h1>User Profile</h1>

    <!-- Profile Picture -->
    <div class="profile-picture-container" onclick="document.getElementById('upload').click()">
        <img id="profilePic" src="<?php
        $profilePicPath = "profile-pictures/" . md5($email) . ".jpg";
        echo file_exists($profilePicPath) ? $profilePicPath : "default-profile.jpg";
        ?>" alt="Profile Picture">
        <div class="upload-overlay">Change Photo</div>
        <form id="uploadForm" enctype="multipart/form-data" method="POST" action="upload-profile.php">
            <input type="file" name="profilePic" id="upload" accept="image/*" onchange="document.getElementById('uploadForm').submit();">
        </form>
    </div>

    <!-- Profile Info -->
    <div class="info-block"><strong>Name:</strong> <span id="profileName"><?php echo $first . ' ' . $surname; ?></span></div>
    <div class="info-block"><strong>Email:</strong> <span id="profileEmail"><?php echo htmlspecialchars($email); ?></span></div>

    <!-- KYC Status, now fetched from the database -->
    <div class="info-block"><strong>KYC Status:</strong> <span class="kyc-status" style="color: <?php echo $kycStatus === 'Approved' ? 'green' : ($kycStatus === 'Rejected' ? 'red' : 'orange'); ?>;">
      <?php echo $kycStatus; ?>
    </span></div>

    <!-- Mining Balances -->
    <div class="section">
        <h2>Balance</h2>
<div class="info-block">
    <strong>Mining Balance:</strong> <?php echo number_format($miningBalance, 4); ?> GBL</li>
</div>

        <div class="info-block">
  <strong>Tasks Balance:</strong> <?php echo number_format($taskBalance, 4); ?> GBL
</div>

<div class="info-block">
    <strong>Referral Balance:</strong> <?php echo number_format($referralBalance, 4); ?> GBL
  </div>
</div>

    <!-- Referrals -->
    <div class="section">
        <h2>Referrals</h2>
        <div class="info-block"><strong>Your Link:</strong>
            <a href="https://gobolchain.com/register.html?ref=<?php echo urlencode($email); ?>" style="color: darkblue;">
                https://gobolchain.com/register.html?ref=<?php echo urlencode($email); ?>
            </a>
        </div>

        <?php if (!empty($referrals)): ?>
            <?php foreach ($referrals as $ref): ?>
                <div class="referral-item">Invited: <?php echo htmlspecialchars($ref['first_name'] . ' ' . $ref['surname']); ?> - +0.02 GBL</div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="referral-item">You haven’t referred anyone yet.</div>
        <?php endif; ?>
    </div>
</div>

<!-- Footer -->
<footer>
    <div class="socials">
        <a href="https://x.com/gobolcoin?s=08" target="_blank">
            <img src="https://cdn-icons-png.flaticon.com/512/733/733579.png" alt="Twitter">
        </a>
        <a href="https://youtube.com/@gobolcoin?si=ByrsmImTnkALKIzX" target="_blank">
            <img src="https://cdn-icons-png.flaticon.com/512/1384/1384060.png" alt="YouTube">
        </a>
        <a href="https://t.me/+DvAqx1PFYAE2MDE0" target="_blank">
            <img src="https://cdn-icons-png.flaticon.com/512/2111/2111646.png" alt="Telegram">
        </a>
    </div>
    <p style="margin-top: 0.5em;">All right reserve &copy; Gobolchain Network 2025</p>
</footer>

<script>
    function previewImage(event) {
        const reader = new FileReader();
        reader.onload = function () {
            document.getElementById('profilePic').src = reader.result;
        };
        reader.readAsDataURL(event.target.files[0]);

        setTimeout(() => {
            document.getElementById('uploadForm').submit();
        }, 500);
    }
</script>

<script>
    // Live Main Balance mining updater
    const mainBalanceDisplay = document.getElementById("mainBalance");

    const RATE_PER_SECOND = 0.0000069444; // 0.025 GBL/hr
    const TOTAL_SECONDS = 8 * 3600; // 8 hours

    let profileCycleStartTime = null; // ms
    let profileTotalBalance = 0;
    let profileInterval;

    function updateProfileBalance() {
        if (!profileCycleStartTime) return;

        const now = Date.now();
        let elapsed = Math.floor((now - profileCycleStartTime) / 1000);

        if (elapsed >= TOTAL_SECONDS) {
            elapsed = TOTAL_SECONDS;
        }

        const minedThisCycle = RATE_PER_SECOND * elapsed;
        mainBalanceDisplay.textContent = (profileTotalBalance + minedThisCycle).toFixed(4);
    }

    function startProfileBalanceLoop() {
        profileInterval = setInterval(updateProfileBalance, 1000);
        updateProfileBalance();
    }

    function fetchProfileMiningStatus() {
        fetch("get-mining-status.php")
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    profileTotalBalance = parseFloat(data.balance) || 0;
                    if (data.startTime) {
                        profileCycleStartTime = parseInt(data.startTime) * 1000;
                    }
                    startProfileBalanceLoop();
                }
            })
            .catch(err => console.error("Error loading mining status:", err));
    }

    // Run when profile page loads
    fetchProfileMiningStatus();
    
    <script>
// Function to update mining balance from the server
function updateProfileMiningBalance() {
    fetch("get-mining-status.php")
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const totalBalance = parseFloat(data.balance) || 0;
                const startTime = data.startTime ? parseInt(data.startTime) * 1000 : null;

                let displayBalance = totalBalance;

                if (startTime) {
                    const RATE_PER_SECOND = 0.0000069444; // same rate as mining dashboard
                    const now = Date.now();
                    const elapsed = Math.floor((now - startTime) / 1000);
                    const TOTAL_SECONDS = 8 * 3600; // 8 hours
                    const minedThisCycle = Math.min(elapsed, TOTAL_SECONDS) * RATE_PER_SECOND;
                    displayBalance = totalBalance + minedThisCycle;
                }

                document.getElementById("profileMiningBalance").textContent = displayBalance.toFixed(4);
            }
        })
        .catch(err => console.error("Error updating mining balance:", err));
}

// Update every second
setInterval(updateProfileMiningBalance, 1000);

// Initial update
updateProfileMiningBalance();
</script>
</script>

</body>
</html>