<?php
session_start();
include 'db.php';

$user_id = $_SESSION['user_id'] ?? 0;

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

/* =========================================================
   POPUP MESSAGE
========================================================= */

$popupMessage = "";
$popupType = "";


/* =========================================================
   USER
========================================================= */

$stmt = $conn->prepare("
    SELECT balance, referred_by
    FROM users
    WHERE id=?
");

$stmt->bind_param("i",$user_id);
$stmt->execute();

$user = $stmt->get_result()->fetch_assoc();

$balance = (float)$user['balance'];
$ref1 = $user['referred_by'];


/* =========================================================
   MY EARNINGS FROM TASK RECORDS
========================================================= */

$myEarnings = 0;

$earningsStmt = $conn->prepare("
    SELECT COALESCE(SUM(reward),0) AS total_earnings
    FROM task_records
    WHERE user_id=?
");

$earningsStmt->bind_param("i",$user_id);
$earningsStmt->execute();

$earningsResult = $earningsStmt->get_result();

if($earningsResult->num_rows){
    $earningsRow = $earningsResult->fetch_assoc();
    $myEarnings = (float)$earningsRow['total_earnings'];
}


/* =========================================================
   CURRENT LEVEL
========================================================= */

$currentLevel = 0;

$q = $conn->prepare("
    SELECT level
    FROM investments
    WHERE user_id=?
    AND status='active'
    ORDER BY level DESC
    LIMIT 1
");

$q->bind_param("i",$user_id);
$q->execute();

$r = $q->get_result();

if($r->num_rows){
    $currentLevel = (int)$r->fetch_assoc()['level'];
}


/* =========================================================
   LEVEL PRICES
========================================================= */

$prices = [
    1 => 40000,
    2 => 140000,
    3 => 450000
];


/* =========================================================
   UPGRADE
========================================================= */

if(isset($_POST['upgrade'])){

    $level = intval($_POST['level'] ?? 0);

    if(!isset($prices[$level])){

        $popupMessage = "Invalid level selected.";
        $popupType = "error";

    }else{

        $amount = $prices[$level];

        /* Cannot downgrade / buy same level */

        if($level <= $currentLevel){

            $popupMessage =
                "You are already at this level or a higher level.";
            $popupType = "error";

        }

        /* Check balance */

        elseif($balance < $amount){

            $popupMessage =
                "Insufficient balance.<br><br>" .
                "Required: TSH " . number_format($amount) .
                "<br>Available: TSH " . number_format($balance);

            $popupType = "error";

        }

        else{

            $conn->begin_transaction();

            try{

                /* =================================================
                   DEDUCT BALANCE
                ================================================= */

                $newBalance = $balance - $amount;

                $u = $conn->prepare("
                    UPDATE users
                    SET balance=?
                    WHERE id=?
                ");

                $u->bind_param(
                    "di",
                    $newBalance,
                    $user_id
                );

                if(!$u->execute()){
                    throw new Exception("Balance update failed");
                }


                /* =================================================
                   CREATE INVESTMENT
                ================================================= */

                $status = "active";

                $ins = $conn->prepare("
                    INSERT INTO investments
                    (
                        user_id,
                        amount,
                        level,
                        status,
                        created_at
                    )
                    VALUES(?,?,?,?,NOW())
                ");

                $ins->bind_param(
                    "iiis",
                    $user_id,
                    $amount,
                    $level,
                    $status
                );

                if(!$ins->execute()){
                    throw new Exception("Investment creation failed");
                }


                /* =================================================
                   LEVEL 1 REFERRAL BONUS - 10%
                ================================================= */

                if($ref1){

                    $ref1 = intval($ref1);

                    if($ref1 > 0 && $ref1 != $user_id){

                        $bonus1 = $amount * 0.10;

                        $b1 = $conn->prepare("
                            INSERT INTO referral_bonuses
                            (
                                user_id,
                                from_user_id,
                                bonus_amount,
                                created_at
                            )
                            VALUES(?,?,?,NOW())
                        ");

                        $b1->bind_param(
                            "iid",
                            $ref1,
                            $user_id,
                            $bonus1
                        );

                        if(!$b1->execute()){
                            throw new Exception("Level 1 bonus failed");
                        }


                        $u1 = $conn->prepare("
                            UPDATE users
                            SET balance = balance + ?
                            WHERE id=?
                        ");

                        $u1->bind_param(
                            "di",
                            $bonus1,
                            $ref1
                        );

                        if(!$u1->execute()){
                            throw new Exception("Level 1 balance update failed");
                        }


                        /* =========================================
                           LEVEL 2 - 3%
                        ========================================= */

                        $r2 = $conn->prepare("
                            SELECT referred_by
                            FROM users
                            WHERE id=?
                            LIMIT 1
                        ");

                        $r2->bind_param(
                            "i",
                            $ref1
                        );

                        $r2->execute();

                        $result2 = $r2->get_result();

                        if($result2->num_rows){

                            $row2 = $result2->fetch_assoc();

                            $ref2 = intval($row2['referred_by'] ?? 0);

                            if($ref2 > 0 && $ref2 != $user_id){

                                $bonus2 = $amount * 0.03;

                                $b2 = $conn->prepare("
                                    INSERT INTO referral_bonuses
                                    (
                                        user_id,
                                        from_user_id,
                                        bonus_amount,
                                        created_at
                                    )
                                    VALUES(?,?,?,NOW())
                                ");

                                $b2->bind_param(
                                    "iid",
                                    $ref2,
                                    $user_id,
                                    $bonus2
                                );

                                if(!$b2->execute()){
                                    throw new Exception("Level 2 bonus failed");
                                }


                                $u2 = $conn->prepare("
                                    UPDATE users
                                    SET balance = balance + ?
                                    WHERE id=?
                                ");

                                $u2->bind_param(
                                    "di",
                                    $bonus2,
                                    $ref2
                                );

                                if(!$u2->execute()){
                                    throw new Exception("Level 2 balance update failed");
                                }


                                /* =================================
                                   LEVEL 3 - 1%
                                ================================= */

                                $r3 = $conn->prepare("
                                    SELECT referred_by
                                    FROM users
                                    WHERE id=?
                                    LIMIT 1
                                ");

                                $r3->bind_param(
                                    "i",
                                    $ref2
                                );

                                $r3->execute();

                                $result3 = $r3->get_result();

                                if($result3->num_rows){

                                    $row3 = $result3->fetch_assoc();

                                    $ref3 = intval(
                                        $row3['referred_by'] ?? 0
                                    );

                                    if(
                                        $ref3 > 0 &&
                                        $ref3 != $user_id &&
                                        $ref3 != $ref1 &&
                                        $ref3 != $ref2
                                    ){

                                        $bonus3 = $amount * 0.01;

                                        $b3 = $conn->prepare("
                                            INSERT INTO referral_bonuses
                                            (
                                                user_id,
                                                from_user_id,
                                                bonus_amount,
                                                created_at
                                            )
                                            VALUES(?,?,?,NOW())
                                        ");

                                        $b3->bind_param(
                                            "iid",
                                            $ref3,
                                            $user_id,
                                            $bonus3
                                        );

                                        if(!$b3->execute()){
                                            throw new Exception("Level 3 bonus failed");
                                        }


                                        $u3 = $conn->prepare("
                                            UPDATE users
                                            SET balance = balance + ?
                                            WHERE id=?
                                        ");

                                        $u3->bind_param(
                                            "di",
                                            $bonus3,
                                            $ref3
                                        );

                                        if(!$u3->execute()){
                                            throw new Exception("Level 3 balance update failed");
                                        }

                                    }
                                }
                            }
                        }
                    }
                }


                /* =================================================
                   COMMIT
                ================================================= */

                $conn->commit();


                /* =================================================
                   SUCCESS POPUP
                ================================================= */

                $popupMessage =
                    "Upgrade successful!<br><br>" .
                    "You have successfully joined S" . $level . ".<br>" .
                    "Amount: TSH " . number_format($amount);

                $popupType = "success";


                /* Refresh displayed values */

                $balance = $newBalance;

                $currentLevel = $level;


            }catch(Exception $e){

                $conn->rollback();

                $popupMessage =
                    "Something went wrong.<br><br>" .
                    "Please try again.";

                $popupType = "error";
            }
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<title>VIP Center</title>

<style>

/* =========================
   RESET
========================= */

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

html,
body{
    width:100%;
    min-height:100%;
}

body{
    font-family:Arial,Helvetica,sans-serif;
    background:#087f65;
    color:#222;
    overflow-x:hidden;
    padding-bottom:85px;
}


/* =========================
   PAGE
========================= */

.page{
    width:100%;
    min-height:100vh;

    position:relative;

    overflow:hidden;

    background:
        radial-gradient(
            circle at 50% 20%,
            rgba(255,255,255,.08),
            transparent 28%
        ),
        linear-gradient(
            180deg,
            #078063 0%,
            #149c7d 55%,
            #0b896d 100%
        );
}


/* Background decoration */

.page::before{
    content:"";

    position:absolute;

    width:150px;
    height:150px;

    left:190px;
    top:120px;

    background:rgba(255,255,255,.035);

    border-radius:10px;

    box-shadow:
        85px 40px 0 rgba(255,255,255,.025),
        -80px 85px 0 rgba(255,255,255,.025),
        160px 95px 0 rgba(255,255,255,.025);
}

.page::after{
    content:"";

    position:absolute;

    width:500px;
    height:500px;

    right:-300px;
    bottom:-180px;

    background:rgba(255,255,255,.05);

    border-radius:50%;
}


/* =========================
   CONTENT
========================= */

.content{
    position:relative;

    z-index:2;

    width:100%;

    padding-top:25px;
    padding-bottom:30px;
}


/* =========================
   TITLE
========================= */

.title{
    text-align:center;

    color:#fff;

    font-size:31px;

    line-height:1;

    font-weight:700;

    margin-bottom:35px;
}


/* =========================
   PROGRESS
========================= */

.progress-area{
    width:250px;

    height:32px;

    margin:0 auto 23px auto;

    position:relative;
}

.progress-line{
    position:absolute;

    top:13px;

    left:22px;
    right:22px;

    height:5px;

    background:#c5c5c5;

    border-radius:10px;

    overflow:hidden;
}

.progress-fill{
    position:absolute;

    left:0;
    top:0;

    width:0%;

    height:100%;

    background:#a8e85b;

    border-radius:10px;

    transition:width:.25s ease;
}

.dot{
    position:absolute;

    width:23px;
    height:23px;

    top:3px;

    border-radius:50%;

    background:#c4c4c4;

    transition:.25s ease;
}

.dot.one{
    left:3px;
}

.dot.two{
    left:76px;
}

.dot.three{
    left:149px;
}

.dot.four{
    right:3px;
}

.dot.active{
    width:30px;
    height:30px;

    top:0;

    background:#fff;

    border:5px solid #a8e85b;

    box-shadow:
        0 0 0 1px rgba(255,255,255,.15);
}


/* =========================
   LEVEL SLIDER
========================= */

.level-slider{
    width:100%;

    display:flex;

    overflow-x:auto;
    overflow-y:hidden;

    scroll-snap-type:x mandatory;

    scrollbar-width:none;

    -webkit-overflow-scrolling:touch;

    padding-left:3.5%;
    padding-right:3.5%;
}

.level-slider::-webkit-scrollbar{
    display:none;
}


/* =========================
   LEVEL SLIDE
========================= */

.level-slide{
    flex:0 0 93%;

    scroll-snap-align:center;

    margin-right:3.5%;

    position:relative;
}


/* =========================
   LEVEL CARD
========================= */

.level-card{
    width:100%;

    height:255px;

    position:relative;

    overflow:hidden;

    border-radius:0 32px 32px 32px;

    background:
        radial-gradient(
            circle at 78% 48%,
            rgba(0,170,145,.18),
            transparent 29%
        ),
        linear-gradient(
            110deg,
            #fff 0%,
            #f5ffff 48%,
            #d8eeee 100%
        );

    box-shadow:
        0 7px 18px rgba(0,0,0,.10),
        inset 0 0 0 1px rgba(0,0,0,.04);
}


/* =========================
   LEVEL LABEL
========================= */

.level-label{
    position:absolute;

    top:0;
    left:0;

    width:190px;
    height:52px;

    background:
        linear-gradient(
            110deg,
            #ead1a5,
            #f3ae3d
        );

    border-radius:0 0 31px 0;

    display:flex;

    align-items:center;

    padding-left:19px;

    color:#fff;

    font-size:17px;

    font-weight:400;
}


/* =========================
   LEVEL CONTENT
========================= */

.level-content{
    position:absolute;

    top:68px;

    left:24px;

    right:18px;
}

.level-name{
    color:#d77c50;

    font-size:26px;

    line-height:1.05;

    font-weight:700;

    margin-bottom:8px;

    max-width:60%;
}

.tasks{
    font-size:17px;

    font-weight:700;

    color:#242424;

    margin-bottom:31px;
}

.tasks span{
    font-weight:400;

    margin-left:8px;
}

.validity{
    font-size:14px;

    line-height:1.4;

    color:#e69b1a;

    font-weight:400;

    max-width:62%;
}


/* =========================
   BADGE
========================= */

.badge{
    position:absolute;

    right:18px;

    top:72px;

    width:98px;
    height:98px;

    object-fit:contain;

    filter:
        drop-shadow(
            0 7px 11px rgba(0,0,0,.10)
        );
}


/* =========================
   UPGRADE BUTTON
========================= */

.upgrade-btn{
    position:absolute;

    right:16px;

    bottom:17px;

    width:112px;

    height:35px;

    border:0;

    border-radius:5px;

    background:
        linear-gradient(
            180deg,
            #ffd83d 0%,
            #f5bd00 100%
        );

    color:#171717;

    font-size:11px;

    font-weight:700;

    cursor:pointer;

    box-shadow:
        0 3px 6px rgba(0,0,0,.12);

    transition:
        transform .15s ease,
        box-shadow .15s ease;
}

.upgrade-btn:active{
    transform:scale(.96);

    box-shadow:
        0 2px 4px rgba(0,0,0,.10);
}


/* =========================
   EARNINGS
========================= */

.stats{
    width:93%;

    margin:22px auto 0 auto;

    display:flex;

    gap:12px;
}


/* =========================
   STAT CARD
========================= */

.stat-card{
    flex:1;

    height:105px;

    background:rgba(255,255,255,.97);

    border-radius:5px;

    display:flex;

    flex-direction:column;

    align-items:center;

    justify-content:center;

    text-align:center;

    box-shadow:
        0 3px 12px rgba(0,0,0,.06);

    transition:.2s ease;
}


/* =========================
   STAT VALUE
========================= */

.stat-value{
    font-size:31px;

    font-weight:700;

    line-height:1;

    margin-bottom:5px;

    transition:
        opacity .15s ease;
}

.daily .stat-value{
    color:#48ad52;
}

.earnings .stat-value{
    color:#f49a00;
}


/* =========================
   CURRENCY
========================= */

.currency{
    font-size:15px;

    color:#999;

    margin-bottom:11px;

    font-weight:400;
}


/* =========================
   STAT TITLE
========================= */

.stat-title{
    font-size:12px;

    font-weight:700;

    letter-spacing:.15px;
}

.daily .stat-title{
    color:#4ba956;
}

.earnings .stat-title{
    color:#efa00c;
}


/* =========================
   STAT BOTTOM
========================= */

.stat-bottom{
    margin-top:5px;

    font-size:11px;

    color:#333;
}


/* =========================
   EARNINGS IMAGE
========================= */

.earnings-image{
    width:93%;

    margin:22px auto 0 auto;

    display:block;

    border-radius:18px;

    box-shadow:
        0 3px 12px rgba(0,0,0,.08);
}


/* =========================
   TABLET / DESKTOP
========================= */

@media(min-width:701px){

    .content{
        padding-top:35px;
    }

    .title{
        font-size:38px;

        margin-bottom:42px;
    }

    .progress-area{
        width:290px;

        margin-bottom:28px;
    }

    .level-slider{
        padding-left:4%;
        padding-right:4%;
    }

    .level-slide{
        flex-basis:92%;

        margin-right:3%;
    }

    .level-card{
        height:310px;
    }

    .level-label{
        width:250px;
        height:65px;

        font-size:21px;
    }

    .level-content{
        top:85px;
        left:35px;
    }

    .level-name{
        font-size:33px;
    }

    .tasks{
        font-size:21px;

        margin-bottom:43px;
    }

    .validity{
        font-size:17px;
    }

    .badge{
        width:130px;
        height:130px;

        right:30px;
        top:95px;
    }

    .upgrade-btn{
        width:145px;
        height:42px;

        right:27px;
        bottom:22px;

        font-size:13px;
    }

    .stats{
        width:92%;

        gap:20px;

        margin-top:28px;
    }

    .stat-card{
        height:145px;
    }

    .stat-value{
        font-size:38px;
    }

    .stat-title{
        font-size:14px;
    }

    .currency{
        font-size:17px;
    }

    .earnings-image{
        width:92%;
        margin-top:28px;
        border-radius:5px;
    }
}


/* =========================
   SMALL PHONES
========================= */

@media(max-width:360px){

    .content{
        padding-top:22px;
    }

    .title{
        font-size:28px;

        margin-bottom:32px;
    }

    .progress-area{
        width:235px;

        margin-bottom:21px;
    }

    .level-slider{
        padding-left:3%;
        padding-right:3%;
    }

    .level-slide{
        flex-basis:94%;

        margin-right:3%;
    }

    .level-card{
        height:245px;

        border-radius:0 29px 29px 29px;
    }

    .level-label{
        width:178px;
        height:49px;

        font-size:16px;
    }

    .level-content{
        top:63px;

        left:21px;
    }

    .level-name{
        font-size:24px;
    }

    .tasks{
        font-size:16px;

        margin-bottom:28px;
    }

    .validity{
        font-size:13px;
    }

    .badge{
        width:88px;
        height:88px;

        right:12px;
        top:68px;
    }

    .upgrade-btn{
        width:103px;
        height:32px;

        right:11px;
        bottom:14px;

        font-size:10px;
    }

    .stats{
        width:94%;

        gap:9px;

        margin-top:19px;
    }

    .stat-card{
        height:115px;

        border-radius:16px;
    }

    .stat-value{
        font-size:28px;
    }

    .currency{
        font-size:14px;

        margin-bottom:9px;
    }

    .stat-title{
        font-size:10px;
    }

    .stat-bottom{
        font-size:10px;

        margin-top:4px;
    }

    .earnings-image{
        width:94%;

        margin-top:19px;

        border-radius:16px;
    }
}


/* =========================
   BOTTOM NAV
========================= */

.bottom-nav{
    position:fixed;

    left:0;
    right:0;
    bottom:0;

    height:64px;

    background:#fff;

    border-top:1px solid #eee;

    display:grid;

    grid-template-columns:repeat(5,1fr);

    z-index:100;
}

.nav{
    display:flex;

    flex-direction:column;

    align-items:center;

    justify-content:center;

    gap:3px;

    font-size:14px;

    color:#333;

    text-decoration:none;

    position:relative;
}

.nav svg{
    width:30px;
    height:30px;
}

.nav.active{
    color:#258fc5;
}

.vip{
    position:relative;
}

.vip-circle{
    position:absolute;

    top:-40px;

    width:68px;
    height:68px;

    border-radius:50%;

    background:#087b63;

    border:5px solid #fff;

    display:flex;

    align-items:center;

    justify-content:center;
}

.vip-diamond{
    width:35px;
    height:28px;

    border:3px solid #fff;

    clip-path:
        polygon(
            15% 0,
            85% 0,
            100% 35%,
            50% 100%,
            0 35%
        );

    background:transparent;
}

.vip span{
    margin-top:500px;
}


/* =========================================================
   UPGRADE CONFIRM POPUP
========================================================= */

#upgradePopup{
    display:none;

    position:fixed;

    left:0;
    top:0;

    width:100%;
    height:100%;

    background:rgba(0,0,0,.45);

    z-index:99999;

    backdrop-filter:blur(2px);
}


/* Popup box */

.upgrade-box{
    position:absolute;

    left:50%;
    top:50%;

    transform:translate(-50%,-50%);

    width:280px;

    background:#fff;

    border-radius:14px;

    padding:20px;

    box-shadow:
        0 10px 35px rgba(0,0,0,.25);

    text-align:center;

    animation:
        popupIn .2s ease;
}

@keyframes popupIn{

    from{
        opacity:0;
        transform:
            translate(-50%,-50%)
            scale(.90);
    }

    to{
        opacity:1;
        transform:
            translate(-50%,-50%)
            scale(1);
    }
}


/* Popup icon */

.popup-icon{
    width:48px;
    height:48px;

    margin:0 auto 12px auto;

    border-radius:50%;

    display:flex;

    align-items:center;

    justify-content:center;

    font-size:25px;

    font-weight:bold;
}

.popup-icon.success{
    background:#e7f8eb;
    color:#27a548;
}

.popup-icon.error{
    background:#fff0f0;
    color:#e04444;
}


/* Popup title */

.popup-title{
    font-size:18px;

    font-weight:700;

    margin-bottom:10px;

    color:#222;
}


/* Popup message */

.popup-message{
    font-size:12px;

    line-height:1.6;

    color:#555;

    margin-bottom:18px;
}


/* Popup button */

.popup-close{
    width:100%;

    height:38px;

    border:0;

    border-radius:7px;

    background:#087c48;

    color:#fff;

    font-size:12px;

    font-weight:700;

    cursor:pointer;
}

.popup-close:active{
    transform:scale(.98);
}


/* Confirm popup buttons */

.confirm-buttons{
    display:flex;

    justify-content:space-between;

    gap:10px;
}

.confirm-buttons button{
    flex:1;

    height:36px;

    border:0;

    border-radius:7px;

    font-size:11px;

    font-weight:700;

    cursor:pointer;
}

.cancel-btn{
    background:#e5e5e5;

    color:#333;
}

.confirm-btn{
    background:#087c48;

    color:#fff;
}

</style>

</head>


<body>


<div class="page">

<div class="content">


<!-- =====================================================
     TITLE
===================================================== -->

<div class="title">
    VIP Center
</div>


<!-- =====================================================
     PROGRESS
===================================================== -->

<div class="progress-area">

    <div class="progress-line">

        <div
            class="progress-fill"
            id="progressFill">
        </div>

    </div>

    <div class="dot one active"></div>

    <div class="dot two"></div>

    <div class="dot three"></div>

    <div class="dot four"></div>

</div>


<!-- =====================================================
     LEVEL SLIDER
===================================================== -->

<div
    class="level-slider"
    id="levelSlider"
>


<!-- =====================================================
     S0
===================================================== -->

<div
    class="level-slide"
    data-level="0"
    data-daily="1200"
    data-earnings="1200.00"
>

<div class="level-card">

    <div class="level-label">
        <?php
        echo ($currentLevel == 0)
            ? "Current level"
            : "S0 Level";
        ?>
    </div>


    <div class="level-content">

        <div class="level-name">
            Temporario
        </div>

        <div class="tasks">
            Daily Tasks:
            <span>3</span>
        </div>

        <div class="validity">
            Internship validity period: 2-3<br>
            days
        </div>

    </div>


    <img
        src="s0.png"
        class="badge"
        alt="S0"
    >

</div>

</div>


<!-- =====================================================
     S1
===================================================== -->

<div
    class="level-slide"
    data-level="1"
    data-daily="1,335"
    data-earnings="800.00"
>

<div class="level-card">

    <div class="level-label">
        <?php
        echo ($currentLevel == 1)
            ? "Current level"
            : "S1 Level";
        ?>
    </div>


    <div class="level-content">

        <div class="level-name">
            S1
        </div>

        <div class="tasks">
            Daily Tasks:
            <span>5</span>
        </div>

        <div class="validity">
            S1 validity period: 360<br>
            days
        </div>

    </div>


    <img
        src="s1.png"
        class="badge"
        alt="S1"
    >


    <?php if($currentLevel < 1): ?>

    <button
        class="upgrade-btn"
        onclick="showUpgrade(1,40000)"
    >
        TSH 40,000
    </button>

    <?php endif; ?>


</div>

</div>


<!-- =====================================================
     S2
===================================================== -->

<div
    class="level-slide"
    data-level="2"
    data-daily="4,669"
    data-earnings="1,200.00"
>

<div class="level-card">

    <div class="level-label">
        <?php
        echo ($currentLevel == 2)
            ? "Current level"
            : "S2 Level";
        ?>
    </div>


    <div class="level-content">

        <div class="level-name">
            S2
        </div>

        <div class="tasks">
            Daily Tasks:
            <span>7</span>
        </div>

        <div class="validity">
            S2 validity period: 360<br>
            days
        </div>

    </div>


    <img
        src="s2.png"
        class="badge"
        alt="S2"
    >


    <?php if($currentLevel < 2): ?>

    <button
        class="upgrade-btn"
        onclick="showUpgrade(2,140000)"
    >
        TSH 140,000
    </button>

    <?php endif; ?>

</div>

</div>


<!-- =====================================================
     S3
===================================================== -->

<div
    class="level-slide"
    data-level="3"
    data-daily="15,000"
    data-earnings="1,600.00"
>

<div class="level-card">

    <div class="level-label">
        <?php
        echo ($currentLevel == 3)
            ? "Current level"
            : "S3 Level";
        ?>
    </div>


    <div class="level-content">

        <div class="level-name">
            S3
        </div>

        <div class="tasks">
            Daily Tasks:
            <span>10</span>
        </div>

        <div class="validity">
            S3 validity period: 360<br>
            days
        </div>

    </div>


    <img
        src="s3.png"
        class="badge"
        alt="S3"
    >


    <?php if($currentLevel < 3): ?>

    <button
        class="upgrade-btn"
        onclick="showUpgrade(3,450000)"
    >
        TSH 450,000
    </button>

    <?php endif; ?>


</div>

</div>


</div>


<!-- =====================================================
     FIXED EARNINGS
===================================================== -->

<div class="stats">


    <!-- DAILY EARNINGS -->

    <div class="stat-card daily">

        <div
            class="stat-value"
            id="dailyValue"
        >
            1200
        </div>

        <div class="currency">
            TSH
        </div>

        <div class="stat-title">
            DAILY EARNINGS
        </div>

        <div class="stat-bottom">
            
        </div>

    </div>


    <!-- MY EARNINGS -->

    <div class="stat-card earnings">

        <div
            class="stat-value"
            id="earningsValue"
        >
            <?php echo number_format($myEarnings, 2); ?>
        </div>

        <div class="currency">
            TSH
        </div>

        <div class="stat-title">
            MY EARNINGS
        </div>

    </div>


</div>


<!-- =====================================================
     EARNINGS IMAGE
===================================================== -->

<img
    src="earnings.jpeg"
    class="earnings-image"
    alt="Earnings Details"
>


</div>
</div>


<!-- =====================================================
     BOTTOM NAVIGATION
===================================================== -->

<nav class="bottom-nav">

<a href="home.php" class="nav">

<svg viewBox="0 0 40 40" fill="none">

<path
    d="M5 19L20 5l15 14"
    stroke="currentColor"
    stroke-width="2.5"
/>

<path
    d="M9 18v15h8V23h6v10h8V18"
    stroke="currentColor"
    stroke-width="2.5"
/>

</svg>

<span>Home</span>

</a>


<a href="promotion.php" class="nav">

<svg viewBox="0 0 40 40" fill="none">

<circle
    cx="20"
    cy="20"
    r="14"
    stroke="currentColor"
    stroke-width="2.5"
/>

<path
    d="M20 17v9M20 12h.01"
    stroke="currentColor"
    stroke-width="3"
    stroke-linecap="round"
/>

</svg>

<span>Promotion</span>

</a>


<a href="#" class="nav active">

<div class="vip-circle">

<div class="vip-diamond"></div>

</div>

<span></span>

</a>


<a href="invite.php" class="nav">

<svg viewBox="0 0 40 40" fill="none">

<circle
    cx="20"
    cy="11"
    r="4"
    stroke="currentColor"
    stroke-width="2"
/>

<circle
    cx="10"
    cy="25"
    r="4"
    stroke="currentColor"
    stroke-width="2"
/>

<circle
    cx="30"
    cy="25"
    r="4"
    stroke="currentColor"
    stroke-width="2"
/>

<path
    d="M17 13l-5 8M23 13l5 8M14 25h12"
    stroke="currentColor"
    stroke-width="2"
/>

</svg>

<span>Invite</span>

</a>


<a href="me.php" class="nav">

<svg viewBox="0 0 40 40" fill="none">

<circle
    cx="20"
    cy="11"
    r="5"
    stroke="currentColor"
    stroke-width="2.5"
/>

<path
    d="M9 34c1-7 5-11 11-11s10 4 11 11"
    stroke="currentColor"
    stroke-width="2.5"
/>

</svg>

<span>My</span>

</a>

</nav>


<!-- =====================================================
     CONFIRMATION POPUP
===================================================== -->

<div id="upgradePopup">

    <div class="upgrade-box">

        <div
            class="popup-icon"
            id="confirmIcon"
        >
            ?
        </div>

        <div
            class="popup-title"
            id="confirmTitle"
        >
            Confirm Upgrade
        </div>

        <div
            class="popup-message"
            id="popupText"
        >
        </div>

        <form method="POST">

            <input
                type="hidden"
                name="level"
                id="popupLevel"
            >

            <div class="confirm-buttons">

                <button
                    type="button"
                    class="cancel-btn"
                    onclick="closePopup()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    name="upgrade"
                    class="confirm-btn"
                >
                    Confirm
                </button>

            </div>

        </form>

    </div>

</div>


<!-- =====================================================
     RESULT POPUP
===================================================== -->

<?php if($popupMessage): ?>

<div
    id="resultPopup"
    style="
        display:block;
        position:fixed;
        left:0;
        top:0;
        width:100%;
        height:100%;
        background:rgba(0,0,0,.45);
        z-index:100000;
        backdrop-filter:blur(2px);
    "
>

<div class="upgrade-box">

    <div
        class="popup-icon <?php echo $popupType === 'success' ? 'success' : 'error'; ?>"
    >

        <?php
        echo $popupType === 'success'
            ? '✓'
            : '!';
        ?>

    </div>


    <div class="popup-title">

        <?php
        echo $popupType === 'success'
            ? 'Success'
            : 'Error';
        ?>

    </div>


    <div class="popup-message">

        <?php
        echo $popupMessage;
        ?>

    </div>


    <button
        type="button"
        class="popup-close"
        onclick="closeResultPopup()"
    >
        OK
    </button>

</div>

</div>

<?php endif; ?>


<script>

/* =========================================================
   CONFIRM UPGRADE POPUP
========================================================= */

function showUpgrade(level, amount){

    document.getElementById("popupLevel").value = level;

    document.getElementById("popupText").innerHTML =
        "Are you sure you want to use TSH " +
        Number(amount).toLocaleString() +
        " to join S" +
        level +
        "?";

    document.getElementById("upgradePopup").style.display =
        "block";
}


function closePopup(){

    document.getElementById("upgradePopup").style.display =
        "none";
}


/* =========================================================
   RESULT POPUP
========================================================= */

function closeResultPopup(){

    const popup =
        document.getElementById("resultPopup");

    if(popup){
        popup.style.display = "none";
    }

}


/* =========================================================
   ELEMENTS
========================================================= */

const slider =
    document.getElementById("levelSlider");

const slides =
    document.querySelectorAll(".level-slide");

const dailyValue =
    document.getElementById("dailyValue");

const earningsValue =
    document.getElementById("earningsValue");

const dots =
    document.querySelectorAll(".dot");

const progressFill =
    document.getElementById("progressFill");


/* =========================================================
   CURRENT SLIDER LEVEL
========================================================= */

let sliderLevel = 0;


/* =========================================================
   UPDATE LEVEL
========================================================= */

function updateLevel(index){

    const slide =
        slides[index];

    if(!slide){
        return;
    }

    sliderLevel = index;


    const daily =
        slide.getAttribute("data-daily");


    /*
       MY EARNINGS IS NOW FROM DATABASE
       task_records SUM(reward)

       Therefore we DO NOT replace it
       when changing the slider.
    */


    dailyValue.textContent =
        daily;


    dots.forEach(
        (dot,i)=>{

            dot.classList.toggle(
                "active",
                i === index
            );

        }
    );


    const percentage =
        (index / (slides.length - 1)) * 100;

    progressFill.style.width =
        percentage + "%";
}


/* =========================================================
   DETECT CENTER SLIDE
========================================================= */

function detectCurrentLevel(){

    const sliderRect =
        slider.getBoundingClientRect();

    const center =
        sliderRect.left +
        sliderRect.width / 2;

    let closest = 0;

    let distance = Infinity;


    slides.forEach(
        (slide,index)=>{

            const rect =
                slide.getBoundingClientRect();

            const slideCenter =
                rect.left +
                rect.width / 2;

            const currentDistance =
                Math.abs(
                    center -
                    slideCenter
                );


            if(
                currentDistance <
                distance
            ){

                distance =
                    currentDistance;

                closest =
                    index;
            }

        }
    );


    updateLevel(closest);
}


/* =========================================================
   SCROLL
========================================================= */

let scrollTimeout;

slider.addEventListener(
    "scroll",
    function(){

        clearTimeout(
            scrollTimeout
        );

        scrollTimeout =
            setTimeout(
                detectCurrentLevel,
                40
            );

    },
    {
        passive:true
    }
);


/* =========================================================
   INITIAL
========================================================= */

updateLevel(0);


/* =========================================================
   RESIZE
========================================================= */

window.addEventListener(
    "resize",
    function(){

        detectCurrentLevel();

    }
);

</script>


</body>
</html>