<?php
/* ==========================================================
   lucky.php
   Lucky Draw + Backend

   CHANCE SYSTEM:
   - User with active investment = 1 chance
   - Each direct subordinate with active investment = 1 chance
   - One chance only per eligible member
   - Multiple investments by same member = still 1 chance
   - New active member = new chance
========================================================== */

session_start();

require_once "db.php";

date_default_timezone_set("Africa/Nairobi");


/* ==========================================================
   LOGIN CHECK
========================================================== */

if (
    !isset($_SESSION['user_id']) ||
    (int)$_SESSION['user_id'] <= 0
) {
    header("Location: login.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];


/* ==========================================================
   SETTINGS
========================================================== */

/*
 * This source identifies the NEW member-based
 * lucky draw system.
 *
 * Old lucky draw records using source="lucky_draw"
 * will NOT be counted as used chances.
 */
$LUCKY_SOURCE = "lucky_draw_member";


/*
 * ONLY THESE TWO PRIZES CAN BE WON
 */

$WINNABLE_PRIZES = [

    [
        "name"   => "TSH 500",
        "amount" => 500
    ],

    [
        "name"   => "TSH 1,500",
        "amount" => 1500
    ]

];


/* ==========================================================
   FUNCTION:
   GET AVAILABLE MEMBER CHANCES
========================================================== */

/*
 * Returns an array containing the members who currently
 * qualify to give the logged-in user ONE lucky-draw chance.
 *
 * Member 0 = current user
 *
 * Direct subordinate ID = the subordinate's user ID
 *
 * Rules:
 *
 * 1. Current user must have at least one active investment.
 *
 * 2. Each direct subordinate must have at least one
 *    active investment.
 *
 * 3. Same member can only appear once.
 *
 * 4. A member whose chance has already been used is removed.
 */

function getAvailableLuckyMembers(
    $conn,
    $user_id,
    $source
) {

    $availableMembers = [];


    /* ======================================================
       CHECK CURRENT USER
    ====================================================== */

    $stmt = $conn->prepare("
        SELECT id
        FROM users
        WHERE id = ?
        AND EXISTS (
            SELECT 1
            FROM investments i
            WHERE i.user_id = users.id
              AND LOWER(i.Status) = 'active'
        )
        LIMIT 1
    ");


    if ($stmt) {

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

        if ($stmt->execute()) {

            $stmt->store_result();

            if ($stmt->num_rows > 0) {

                /*
                 * Check whether the current user's
                 * chance has already been used.
                 *
                 * downline_id = 0 means the chance
                 * came from the logged-in user.
                 */

                $used = false;


                $check = $conn->prepare("
                    SELECT id
                    FROM spins
                    WHERE user_id = ?
                      AND downline_id = 0
                      AND source = ?
                    LIMIT 1
                ");


                if ($check) {

                    $check->bind_param(
                        "is",
                        $user_id,
                        $source
                    );

                    if ($check->execute()) {

                        $check->store_result();

                        if ($check->num_rows > 0) {

                            $used = true;
                        }
                    }

                    $check->close();
                }


                if (!$used) {

                    $availableMembers[] = 0;
                }
            }
        }

        $stmt->close();
    }


    /* ======================================================
       GET DIRECT ACTIVE SUBORDINATES
    ====================================================== */

    /*
     * DISTINCT is important.
     *
     * If a subordinate has 5 active investments,
     * they still appear only ONCE.
     */

    $stmt = $conn->prepare("
        SELECT DISTINCT
            u.id
        FROM users u
        WHERE u.referred_by = ?
          AND EXISTS (
              SELECT 1
              FROM investments i
              WHERE i.user_id = u.id
                AND LOWER(i.Status) = 'active'
          )
        ORDER BY u.id ASC
    ");


    if ($stmt) {

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


        if ($stmt->execute()) {

            $result =
                $stmt->get_result();


            while (
                $row =
                $result->fetch_assoc()
            ) {

                $memberId =
                    (int)$row['id'];


                /*
                 * Check whether this exact member's
                 * chance has already been used.
                 */

                $used = false;


                $check = $conn->prepare("
                    SELECT id
                    FROM spins
                    WHERE user_id = ?
                      AND downline_id = ?
                      AND source = ?
                    LIMIT 1
                ");


                if ($check) {

                    $check->bind_param(
                        "iis",
                        $user_id,
                        $memberId,
                        $source
                    );


                    if ($check->execute()) {

                        $check->store_result();


                        if (
                            $check->num_rows > 0
                        ) {

                            $used = true;
                        }
                    }


                    $check->close();
                }


                if (!$used) {

                    $availableMembers[] =
                        $memberId;
                }
            }
        }


        $stmt->close();
    }


    return $availableMembers;
}


/* ==========================================================
   AJAX DRAW REQUEST
========================================================== */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'draw'
) {

    header(
        "Content-Type: application/json; charset=UTF-8"
    );


    /* ======================================================
       DATABASE CONNECTION
    ====================================================== */

    if (
        !isset($conn) ||
        !$conn ||
        $conn->connect_errno
    ) {

        echo json_encode([
            "success" => false,
            "message" => "Database connection failed."
        ]);

        exit;
    }


    /* ======================================================
       SELECT WINNER
    ====================================================== */

    try {

        $winnerIndex =
            random_int(
                0,
                count($WINNABLE_PRIZES) - 1
            );

    } catch (Throwable $e) {

        $winnerIndex =
            mt_rand(
                0,
                count($WINNABLE_PRIZES) - 1
            );
    }


    $winner =
        $WINNABLE_PRIZES[$winnerIndex];


    $prizeName =
        $winner['name'];


    $prizeAmount =
        (float)$winner['amount'];


    /* ======================================================
       DATABASE TRANSACTION
    ====================================================== */

    try {

        if (!$conn->begin_transaction()) {

            throw new Exception(
                "Unable to start database transaction."
            );
        }


        /* ==================================================
           LOCK CURRENT USER
        ================================================== */

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


        if (!$stmt) {

            throw new Exception(
                "Unable to prepare user query: " .
                $conn->error
            );
        }


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


        if (!$stmt->execute()) {

            $stmt->close();

            throw new Exception(
                "Unable to read user account."
            );
        }


        $stmt->bind_result(
            $currentBalance
        );


        if (!$stmt->fetch()) {

            $stmt->close();

            throw new Exception(
                "User account not found."
            );
        }


        $stmt->close();


        $currentBalance =
            (float)$currentBalance;


        /* ==================================================
           FIND AVAILABLE CHANCES
        ================================================== */

        $availableMembers =
            getAvailableLuckyMembers(
                $conn,
                $user_id,
                $LUCKY_SOURCE
            );


        /*
         * No eligible member = no chance.
         */

        if (
            empty($availableMembers)
        ) {

            throw new Exception(
                "No chances available."
            );
        }


        /* ==================================================
           SELECT ONE MEMBER CHANCE
        ================================================== */

        /*
         * Randomly choose which eligible member's
         * one chance is being consumed.
         */

        try {

            $chanceIndex =
                random_int(
                    0,
                    count($availableMembers) - 1
                );

        } catch (Throwable $e) {

            $chanceIndex =
                mt_rand(
                    0,
                    count($availableMembers) - 1
                );
        }


        $downline_id =
            (int)$availableMembers[$chanceIndex];


        /* ==================================================
           DOUBLE CHECK CHANCE
        ================================================== */

        /*
         * This protects against accidentally using
         * the same member twice.
         */

        $stmt = $conn->prepare("
            SELECT id
            FROM spins
            WHERE user_id = ?
              AND downline_id = ?
              AND source = ?
            LIMIT 1
            FOR UPDATE
        ");


        if (!$stmt) {

            throw new Exception(
                "Unable to check chance."
            );
        }


        $stmt->bind_param(
            "iis",
            $user_id,
            $downline_id,
            $LUCKY_SOURCE
        );


        if (!$stmt->execute()) {

            $stmt->close();

            throw new Exception(
                "Unable to verify chance."
            );
        }


        $stmt->store_result();


        if ($stmt->num_rows > 0) {

            $stmt->close();

            throw new Exception(
                "This member's chance has already been used."
            );
        }


        $stmt->close();


        /* ==================================================
           ADD WINNING TO BALANCE
        ================================================== */

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


        if (!$stmt) {

            throw new Exception(
                "Unable to prepare balance update: " .
                $conn->error
            );
        }


        $stmt->bind_param(
            "di",
            $prizeAmount,
            $user_id
        );


        if (!$stmt->execute()) {

            $stmt->close();

            throw new Exception(
                "Unable to update balance: " .
                $conn->error
            );
        }


        if (
            $stmt->affected_rows < 1
        ) {

            $stmt->close();

            throw new Exception(
                "Balance was not updated."
            );
        }


        $stmt->close();


        /* ==================================================
           RECORD SPIN
        ================================================== */

        $source =
            $LUCKY_SOURCE;


        $stmt = $conn->prepare("
            INSERT INTO spins
            (
                user_id,
                downline_id,
                prize,
                spin_time,
                source
            )
            VALUES
            (
                ?,
                ?,
                ?,
                NOW(),
                ?
            )
        ");


        if (!$stmt) {

            throw new Exception(
                "Unable to prepare spin record: " .
                $conn->error
            );
        }


        $stmt->bind_param(
            "iiss",
            $user_id,
            $downline_id,
            $prizeName,
            $source
        );


        if (!$stmt->execute()) {

            $stmt->close();

            throw new Exception(
                "Unable to save spin record: " .
                $conn->error
            );
        }


        $stmt->close();


        /* ==================================================
           GET NEW BALANCE
        ================================================== */

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


        if (!$stmt) {

            throw new Exception(
                "Unable to prepare balance query."
            );
        }


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


        if (!$stmt->execute()) {

            $stmt->close();

            throw new Exception(
                "Unable to retrieve new balance."
            );
        }


        $stmt->bind_result(
            $newBalance
        );


        if (!$stmt->fetch()) {

            $stmt->close();

            throw new Exception(
                "Unable to retrieve updated balance."
            );
        }


        $stmt->close();


        $newBalance =
            (float)$newBalance;


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

        if (!$conn->commit()) {

            throw new Exception(
                "Unable to commit transaction."
            );
        }


        /* ==================================================
           GET REMAINING CHANCES
        ================================================== */

        $remainingMembers =
            getAvailableLuckyMembers(
                $conn,
                $user_id,
                $LUCKY_SOURCE
            );


        $remainingChances =
            count($remainingMembers);


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

        echo json_encode([

            "success" =>
                true,

            "prize" =>
                $prizeName,

            "amount" =>
                $prizeAmount,

            "balance" =>
                $newBalance,

            "chances" =>
                $remainingChances,

            "used_member" =>
                $downline_id

        ]);

        exit;


    } catch (Throwable $e) {


        /* ==================================================
           ROLLBACK
        ================================================== */

        try {

            $conn->rollback();

        } catch (Throwable $rollbackError) {

            // Ignore rollback error
        }


        error_log(
            "Lucky Draw Error - User ID " .
            $user_id .
            ": " .
            $e->getMessage()
        );


        echo json_encode([

            "success" =>
                false,

            "message" =>
                $e->getMessage()

        ]);

        exit;
    }
}


/* ==========================================================
   DISPLAY
========================================================== */


/*
 * Calculate CURRENT available chances directly
 * from database.
 */

$availableLuckyMembers =
    getAvailableLuckyMembers(
        $conn,
        $user_id,
        $LUCKY_SOURCE
    );


$currentChances =
    count($availableLuckyMembers);


/* ==========================================================
   REAL AWARD RECORDS
   CURRENT USER ONLY
========================================================== */

$awardRecords = [];


if (
    isset($conn) &&
    $conn &&
    !$conn->connect_errno
) {

    $stmt = $conn->prepare("
        SELECT
            prize,
            spin_time
        FROM spins
        WHERE user_id = ?
        AND source = ?
        ORDER BY
            spin_time DESC,
            id DESC
        LIMIT 100
    ");


    if ($stmt) {

        $stmt->bind_param(
            "is",
            $user_id,
            $LUCKY_SOURCE
        );


        if ($stmt->execute()) {

            $stmt->bind_result(
                $recordPrize,
                $recordTime
            );


            while ($stmt->fetch()) {

                $awardRecords[] = [

                    "prize" =>
                        (string)$recordPrize,

                    "time" =>
                        (string)$recordTime

                ];
            }
        }


        $stmt->close();
    }
}


/* ==========================================================
   ENDLESS HONOUR LIST
   DISPLAY ONLY
========================================================== */

$honourRecords = [

    [
        "phone"  => "7411",
        "prize"  => "TSH 388,888",
        "avatar" => "https://randomuser.me/api/portraits/men/32.jpg"
    ],

    [
        "phone"  => "1859",
        "prize"  => "Level 2 physical objects",
        "avatar" => "https://randomuser.me/api/portraits/men/64.jpg"
    ],

    [
        "phone"  => "5839",
        "prize"  => "TSH 1,666",
        "avatar" => "https://randomuser.me/api/portraits/women/44.jpg"
    ],

    [
        "phone"  => "5450",
        "prize"  => "TSH 1,666",
        "avatar" => "https://randomuser.me/api/portraits/men/75.jpg"
    ],

    [
        "phone"  => "9026",
        "prize"  => "TSH 500",
        "avatar" => "https://randomuser.me/api/portraits/women/65.jpg"
    ],

    [
        "phone"  => "3178",
        "prize"  => "Smartphone",
        "avatar" => "https://randomuser.me/api/portraits/men/41.jpg"
    ],

    [
        "phone"  => "6284",
        "prize"  => "TSH 1,500",
        "avatar" => "https://randomuser.me/api/portraits/women/31.jpg"
    ],

    [
        "phone"  => "4507",
        "prize"  => "Electric Fan",
        "avatar" => "https://randomuser.me/api/portraits/men/18.jpg"
    ],

    [
        "phone"  => "8362",
        "prize"  => "TSH 500",
        "avatar" => "https://randomuser.me/api/portraits/women/68.jpg"
    ],

    [
        "phone"  => "2741",
        "prize"  => "Rice Cooker",
        "avatar" => "https://randomuser.me/api/portraits/men/52.jpg"
    ],

    [
        "phone"  => "6195",
        "prize"  => "TSH 1,500",
        "avatar" => "https://randomuser.me/api/portraits/women/12.jpg"
    ],

    [
        "phone"  => "3486",
        "prize"  => "Laptop",
        "avatar" => "https://randomuser.me/api/portraits/men/29.jpg"
    ]

];

?>
<!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>Lucky Draw</title>


<style>

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

* {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
}

html,
body {

    margin: 0;
    padding: 0;

    width: 100%;
    min-height: 100%;

    font-family:
        Arial,
        Helvetica,
        sans-serif;

    background: #f7f7f7;

    color: #303030;
}

body {
    overflow-x: hidden;
}


/* =====================================================
   TOP BAR
===================================================== */

.topbar {

    width: 100%;
    height: 58px;

    background: #ffffff;

    border-bottom:
        1px solid #eeeeee;

    display: flex;

    align-items: center;
    justify-content: center;

    position: relative;
}

.title {

    font-size: 23px;

    font-weight: 700;

    line-height: 1;

    letter-spacing: -0.5px;
}

.back {

    position: absolute;

    left: 21px;
    top: 18px;

    width: 15px;
    height: 15px;

    border-left:
        2.5px solid #2993d0;

    border-bottom:
        2.5px solid #2993d0;

    transform: rotate(45deg);

    cursor: pointer;
}


/* =====================================================
   CHANCES
===================================================== */

.chance {

    width: 100%;

    text-align: center;

    font-size: 21px;

    font-weight: 600;

    margin-top: 38px;

    margin-bottom: 33px;

    line-height: 1;
}


/* =====================================================
   DRAW BOX
===================================================== */

.draw-box {

    width:
        calc(100% - 24px);

    max-width: 813px;

    margin: 0 auto;

    background:
        linear-gradient(
            145deg,
            #91ddca 0%,
            #a5e5d2 100%
        );

    border-radius: 27px;

    padding:
        30px
        30px
        32px;
}


/* =====================================================
   PRIZE GRID
===================================================== */

.prize-grid {

    width: 100%;

    display: grid;

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

    gap: 10px;
}


/* =====================================================
   PRIZE CARD
===================================================== */

.prize {

    position: relative;

    width: 100%;

    aspect-ratio: 1 / 1;

    background: #ffffff;

    border-radius: 12px;

    overflow: hidden;

    display: flex;

    align-items: center;
    justify-content: center;

    box-shadow:
        0 4px 8px
        rgba(0,0,0,0.12);

    transition:
        transform 0.15s ease,
        box-shadow 0.15s ease,
        opacity 0.15s ease;
}


/* =====================================================
   PRODUCT IMAGES
===================================================== */

.product img {

    display: block;

    width: 100%;
    height: 100%;

    object-fit: cover;

    background: #ffffff;
}


/* =====================================================
   MONEY CARD
===================================================== */

.money {

    position: relative;

    background: #ffffff;

    overflow: hidden;
}

.money img {

    position: absolute;

    width: 100%;
    height: 100%;

    object-fit: cover;

    display: block;

    z-index: 1;

    opacity: 0.92;
}


/* =====================================================
   MONEY OVERLAY
===================================================== */

.money::after {

    content: "";

    position: absolute;

    left: 0;
    bottom: 0;

    width: 100%;
    height: 28%;

    background:
        linear-gradient(
            to top,
            rgba(255,255,255,0.96),
            rgba(255,255,255,0)
        );

    z-index: 2;
}


/* =====================================================
   AMOUNT
===================================================== */

.money .amount {

    position: absolute;

    left: 0;
    bottom: 8%;

    width: 100%;

    text-align: center;

    font-size: 11px;

    line-height: 1;

    font-weight: 800;

    color: #3f7f4d;

    z-index: 5;

    text-shadow:
        0 1px 1px
        rgba(255,255,255,0.9);
}


/* =====================================================
   SHUFFLING
===================================================== */

.prize.shuffling {

    transform:
        scale(0.92)
        rotate(
            calc(
                -4deg +
                8deg *
                var(--random-rotate)
            )
        );

    opacity: 0.82;
}


/* =====================================================
   WINNER
===================================================== */

.prize.winner {

    z-index: 20;

    transform:
        scale(1.08);

    box-shadow:
        0 0 0 4px #ffd700,
        0 0 25px
        rgba(255,215,0,0.90);

    animation:
        winnerPulse
        0.8s
        ease-in-out
        infinite alternate;
}

@keyframes winnerPulse {

    from {

        transform:
            scale(1.03);
    }

    to {

        transform:
            scale(1.10);
    }
}


/* =====================================================
   START BUTTON
===================================================== */

.start {

    width: 100%;

    height: 58px;

    margin-top: 30px;

    border: none;

    border-radius: 40px;

    background:
        linear-gradient(
            100deg,
            #15934d 0%,
            #23d9b0 100%
        );

    color: #ffffff;

    font-size: 20px;

    font-weight: 700;

    cursor: pointer;

    box-shadow:
        0 5px 11px
        rgba(0,150,100,0.20);

    outline: none;

    transition:
        opacity 0.2s ease,
        transform 0.15s ease;
}

.start:active {

    transform:
        scale(0.985);
}

.start:disabled {

    opacity: 0.55;

    cursor: not-allowed;
}


/* =====================================================
   RULES
===================================================== */

.rules {

    width:
        calc(100% - 24px);

    max-width: 813px;

    margin:
        32px auto
        40px;

    background: #ffffff;

    border-radius: 25px;

    padding:
        28px
        30px
        38px;

    box-shadow:
        0 3px 16px
        rgba(0,0,0,0.07);
}

.rules p {

    margin: 0;

    font-size: 16px;

    line-height: 1.7;

    font-weight: 400;
}


/* =====================================================
   RECORDS SECTION
===================================================== */

.records-section {

    width:
        calc(100% - 24px);

    max-width: 813px;

    margin:
        0 auto
        45px;
}


/* =====================================================
   TABS
===================================================== */

.record-tabs {

    width: 100%;

    height: 46px;

    display: grid;

    grid-template-columns:
        1fr 1fr;

    background: #f5f5f5;

    overflow: hidden;

    border-radius:
        0;
}

.record-tab {

    border: none;

    background: #f5f5f5;

    color: #2d2d2d;

    font-size: 21px;

    font-weight: 700;

    cursor: pointer;
}

.record-tab.active {

    background: #17743e;

    color: #ffffff;
}


/* =====================================================
   RECORD PANEL
===================================================== */

.record-panel {

    display: none;

    background: #ffffff;

    border-radius:
        0 0 26px 26px;

    overflow: hidden;

    box-shadow:
        0 3px 16px
        rgba(0,0,0,0.07);
}

.record-panel.active {

    display: block;
}


/* =====================================================
   REAL AWARD LIST
===================================================== */

.award-list {

    max-height: 430px;

    overflow-y: auto;

    padding: 8px 0;
}

.award-item {

    min-height: 92px;

    padding:
        17px 28px;

    display: flex;

    align-items: center;

    gap: 14px;

    border-bottom:
        1px solid #f3f3f3;
}

.award-item:last-child {

    border-bottom: none;
}

.award-icon {

    width: 46px;
    height: 46px;

    min-width: 46px;

    border-radius: 50%;

    background:
        linear-gradient(
            135deg,
            #15934d,
            #23d9b0
        );

    color: #ffffff;

    display: flex;

    align-items: center;
    justify-content: center;

    font-size: 21px;

    font-weight: 800;
}

.award-info {

    min-width: 0;
}

.award-title {

    font-size: 17px;

    font-weight: 700;

    color: #262626;

    margin-bottom: 6px;
}

.award-time {

    font-size: 13px;

    color: #999999;
}

.no-records {

    padding:
        55px 20px;

    text-align: center;

    color: #999999;

    font-size: 15px;
}


/* =====================================================
   HONOUR LIST MARQUEE
===================================================== */

.honour-window {

    height: 430px;

    overflow: hidden;

    position: relative;

    background: #ffffff;
}

.honour-track {

    position: absolute;

    left: 0;
    top: 0;

    width: 100%;

    will-change: transform;

    animation:
        honourScroll
        42s
        linear
        infinite;
}

.honour-list {

    width: 100%;
}

.honour-item {

    min-height: 104px;

    padding:
        18px 28px;

    display: flex;

    align-items: center;

    gap: 13px;
}

.honour-avatar {

    width: 42px;
    height: 42px;

    min-width: 42px;

    border-radius: 2px;

    object-fit: cover;

    background: #eeeeee;
}

.honour-info {

    min-width: 0;
}

.honour-title {

    font-size: 18px;

    line-height: 1.2;

    color: #242424;

    margin-bottom: 7px;

    white-space: nowrap;
}

.honour-prize {

    font-size: 16px;

    line-height: 1.2;

    color: #999999;

    white-space: nowrap;
}


/* =====================================================
   ENDLESS ANIMATION
===================================================== */

@keyframes honourScroll {

    0% {

        transform:
            translateY(0);
    }

    100% {

        transform:
            translateY(-50%);
    }
}


/* =====================================================
   PAUSE WHEN TOUCHED/HOVERED
===================================================== */

.honour-window:hover
.honour-track {

    animation-play-state:
        paused;
}


/* =====================================================
   POPUP OVERLAY
===================================================== */

.popup-overlay {

    position: fixed;

    inset: 0;

    width: 100%;
    height: 100%;

    background:
        rgba(0,0,0,0.58);

    display: none;

    align-items: center;
    justify-content: center;

    z-index: 9999;

    padding: 20px;
}

.popup-overlay.show {

    display: flex;

    animation:
        fadeIn
        0.25s
        ease;
}

@keyframes fadeIn {

    from {

        opacity: 0;
    }

    to {

        opacity: 1;
    }
}


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

.popup {

    width: 100%;

    max-width: 340px;

    background: #ffffff;

    border-radius: 22px;

    padding:
        27px
        21px
        23px;

    text-align: center;

    box-shadow:
        0 15px 50px
        rgba(0,0,0,0.25);

    animation:
        popupIn
        0.35s
        cubic-bezier(.2,.8,.2,1);
}

@keyframes popupIn {

    from {

        transform:
            scale(0.75);

        opacity: 0;
    }

    to {

        transform:
            scale(1);

        opacity: 1;
    }
}


/* =====================================================
   POPUP ICON
===================================================== */

.popup-icon {

    width: 60px;
    height: 60px;

    margin:
        0 auto
        12px;

    border-radius: 50%;

    background:
        linear-gradient(
            135deg,
            #16a05a,
            #24dcb0
        );

    color: #ffffff;

    display: flex;

    align-items: center;
    justify-content: center;

    font-size: 32px;

    font-weight: 700;
}


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

.popup h2 {

    margin:
        5px 0
        8px;

    font-size: 23px;

    font-weight: 700;

    color: #222222;
}


/* =====================================================
   POPUP TEXT
===================================================== */

.popup p {

    margin:
        0 0
        8px;

    font-size: 15px;

    line-height: 1.5;

    color: #555555;
}


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

.result-prize {

    margin:
        15px 0
        20px;

    padding:
        13px;

    border-radius: 14px;

    background: #f0faf6;

    color: #15934d;

    font-size: 20px;

    font-weight: 800;
}


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

.new-balance {

    margin:
        -8px 0
        18px;

    font-size: 13px;

    color: #666666;
}

.new-balance strong {

    color: #15934d;
}


/* =====================================================
   POPUP BUTTON
===================================================== */

.popup-button {

    width: 100%;

    height: 50px;

    border: none;

    border-radius: 28px;

    background:
        linear-gradient(
            100deg,
            #15934d,
            #23d9b0
        );

    color: #ffffff;

    font-size: 17px;

    font-weight: 700;

    cursor: pointer;
}


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

@media (max-width: 360px) {

    .draw-box {

        padding:
            27px
            27px
            30px;
    }

    .prize-grid {

        gap: 8px;
    }

    .money .amount {

        font-size: 9px;
    }

    .start {

        height: 54px;

        margin-top: 28px;

        font-size: 19px;
    }

    .rules p {

        font-size: 14px;
    }

    .record-tabs {

        height: 46px;
    }

    .record-tab {

        font-size: 17px;
    }

    .award-item {

        padding:
            15px 18px;
    }

    .award-title {

        font-size: 15px;
    }

    .honour-item {

        padding:
            16px 18px;
    }

    .honour-title {

        font-size: 16px;
    }

    .honour-prize {

        font-size: 14px;
    }

    .popup {

        max-width: 320px;
    }
}

</style>

</head>


<body>


<!-- =====================================================
     TOP BAR
===================================================== -->

<header class="topbar">

    <div
        class="back"
        onclick="history.back()">
    </div>

    <div class="title">

        Lucky Draw

    </div>

</header>


<!-- =====================================================
     CHANCES
===================================================== -->

<div class="chance">

    Chances left:

    <span id="chances">

        <?php
        echo $currentChances;
        ?>

    </span>

</div>


<!-- =====================================================
     DRAW BOX
===================================================== -->

<section class="draw-box">


<div
    class="prize-grid"
    id="prizeGrid">


<!-- =====================================================
     1 - TSH 8,888
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 8,888">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/500_Tanzanian_shillings_coin_-_obverse.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 8,888

    </div>

</div>


<!-- =====================================================
     2 - TSH 500
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 500"
    data-winnable="1">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/100_tz_shillings_front.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 500

    </div>

</div>


<!-- =====================================================
     3 - TSH 88,886
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 88,886">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/200_tz_shillings_front.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 88,886

    </div>

</div>


<!-- =====================================================
     4 - LAPTOP
===================================================== -->

<div
    class="prize product"
    data-prize="Laptop">

    <img
        src="https://loremflickr.com/700/700/laptop?lock=201"
        alt="Laptop">

</div>


<!-- =====================================================
     5 - TSH 1,666
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 1,666">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/50_tz_shillings_front.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 1,666

    </div>

</div>


<!-- =====================================================
     6 - RICE COOKER
===================================================== -->

<div
    class="prize product"
    data-prize="Rice Cooker">

    <img
        src="https://loremflickr.com/700/700/rice,cooker?lock=202"
        alt="Rice Cooker">

</div>


<!-- =====================================================
     7 - TSH 888,888
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 888,888">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/500_Tanzanian_shillings_coin_-_obverse.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 888,888

    </div>

</div>


<!-- =====================================================
     8 - MOTORCYCLE
===================================================== -->

<div
    class="prize product"
    data-prize="Motorcycle">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/Red_and_Black_motorcycle_in_Yuen_Long.jpg"
        alt="Motorcycle"
        onerror="
            this.onerror=null;
            this.src='https://loremflickr.com/700/700/motorcycle?lock=205';
        ">

</div>


<!-- =====================================================
     9 - TSH 388,888
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 388,888">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/100_tz_shillings_front.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 388,888

    </div>

</div>


<!-- =====================================================
     10 - ELECTRIC KETTLE
===================================================== -->

<div
    class="prize product"
    data-prize="Electric Kettle">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/Electric_kettle.jpg"
        alt="Electric Kettle"
        onerror="
            this.onerror=null;
            this.src='https://loremflickr.com/700/700/electric,kettle?lock=206';
        ">

</div>


<!-- =====================================================
     11 - TSH 2,000
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 2,000">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/200_tz_shillings_front.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 2,000

    </div>

</div>


<!-- =====================================================
     12 - ELECTRIC FAN
===================================================== -->

<div
    class="prize product"
    data-prize="Electric Fan">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/Electric_fan.jpg"
        alt="Electric Fan"
        onerror="
            this.onerror=null;
            this.src='https://loremflickr.com/700/700/electric,fan?lock=207';
        ">

</div>


<!-- =====================================================
     13 - BLACK BACKPACK
===================================================== -->

<div
    class="prize product"
    data-prize="Black Backpack">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/Black_backpack.jpg"
        alt="Black Backpack"
        onerror="
            this.onerror=null;
            this.src='https://loremflickr.com/700/700/black,backpack?lock=208';
        ">

</div>


<!-- =====================================================
     14 - SMARTPHONE
===================================================== -->

<div
    class="prize product"
    data-prize="Smartphone">

    <img
        src="https://loremflickr.com/700/700/smartphone?lock=203"
        alt="Smartphone">

</div>


<!-- =====================================================
     15 - BLACK T-SHIRT
===================================================== -->

<div
    class="prize product"
    data-prize="Black T-Shirt">

    <img
        src="https://loremflickr.com/700/700/black,tshirt?lock=204"
        alt="Black T-Shirt">

</div>


<!-- =====================================================
     16 - TSH 550,000
===================================================== -->

<div
    class="prize money"
    data-prize="TSH 550,000">

    <img
        src="https://commons.wikimedia.org/wiki/Special:Redirect/file/500_Tanzanian_shillings_coin_-_obverse.jpg"
        alt="Tanzanian Shilling Coin">

    <div class="amount">

        TSH 550,000

    </div>

</div>


</div>


<!-- =====================================================
     START BUTTON
===================================================== -->

<button
    class="start"
    id="startBtn"
    <?php

    echo $currentChances <= 0
        ? 'disabled'
        : '';

    ?>>

    Start

</button>


</section>


<!-- =====================================================
     RULES
===================================================== -->

<section class="rules">

<p>

1. Participants who complete the corresponding tasks
in accordance with the event rules will receive the
corresponding lottery draw opportunities.

</p>

</section>


<!-- =====================================================
     RECORD TABS + LISTS
===================================================== -->

<section class="records-section">


<div class="record-tabs">


<button
    class="record-tab"
    id="awardTab"
    type="button">

    Award Record

</button>


<button
    class="record-tab active"
    id="honourTab"
    type="button">

    Honour List

</button>


</div>


<!-- =====================================================
     REAL AWARD RECORD
===================================================== -->

<div
    class="record-panel"
    id="awardPanel">


<div class="award-list">


<?php if (empty($awardRecords)): ?>


<div class="no-records">

    No award records yet.

</div>


<?php else: ?>


<?php foreach (
    $awardRecords
    as $record
): ?>


<div class="award-item">


<div class="award-icon">

    ✓

</div>


<div class="award-info">


<div class="award-title">

    Congratulations! You won

    <?php

    echo htmlspecialchars(
        $record['prize'],
        ENT_QUOTES,
        'UTF-8'
    );

    ?>

</div>


<div class="award-time">

<?php

$timestamp =
    strtotime(
        $record['time']
    );


if ($timestamp) {

    echo date(
        'd M Y, H:i',
        $timestamp
    );

} else {

    echo htmlspecialchars(
        $record['time'],
        ENT_QUOTES,
        'UTF-8'
    );
}

?>

</div>


</div>


</div>


<?php endforeach; ?>


<?php endif; ?>


</div>


</div>


<!-- =====================================================
     ENDLESS HONOUR LIST
===================================================== -->

<div
    class="record-panel active"
    id="honourPanel">


<div class="honour-window">


<div class="honour-track">


<!-- =================================================
     FIRST COPY
================================================= -->

<div class="honour-list">


<?php foreach (
    $honourRecords
    as $record
): ?>


<div class="honour-item">


<img
    class="honour-avatar"

    src="<?php

    echo htmlspecialchars(
        $record['avatar'],
        ENT_QUOTES,
        'UTF-8'
    );

    ?>"

    alt="Winner"

    loading="lazy"

    onerror="
        this.onerror=null;
        this.src='https://i.pravatar.cc/80?img=12';
    ">


<div class="honour-info">


<div class="honour-title">

    Congratulations:****

    <?php

    echo htmlspecialchars(
        $record['phone'],
        ENT_QUOTES,
        'UTF-8'
    );

    ?>

</div>


<div class="honour-prize">

    Get prizes

    <?php

    echo htmlspecialchars(
        $record['prize'],
        ENT_QUOTES,
        'UTF-8'
    );

    ?>

</div>


</div>


</div>


<?php endforeach; ?>


</div>


<!-- =================================================
     SECOND COPY
================================================= -->

<div class="honour-list">


<?php foreach (
    $honourRecords
    as $record
): ?>


<div class="honour-item">


<img
    class="honour-avatar"

    src="<?php

    echo htmlspecialchars(
        $record['avatar'],
        ENT_QUOTES,
        'UTF-8'
    );

    ?>"

    alt="Winner"

    loading="lazy"

    onerror="
        this.onerror=null;
        this.src='https://i.pravatar.cc/80?img=12';
    ">


<div class="honour-info">


<div class="honour-title">

    Congratulations:****

    <?php

    echo htmlspecialchars(
        $record['phone'],
        ENT_QUOTES,
        'UTF-8'
    );

    ?>

</div>


<div class="honour-prize">

    Get prizes

    <?php

    echo htmlspecialchars(
        $record['prize'],
        ENT_QUOTES,
        'UTF-8'
    );

    ?>

</div>


</div>


</div>


<?php endforeach; ?>


</div>


</div>


</div>


</div>


</section>


<!-- =====================================================
     CONGRATULATIONS POPUP
===================================================== -->

<div
    class="popup-overlay"
    id="popupOverlay">


<div class="popup">


<div class="popup-icon">

    ✓

</div>


<h2>

    Congratulations!

</h2>


<p>

    You have won:

</p>


<div
    class="result-prize"
    id="resultPrize">

    Prize

</div>


<div class="new-balance">

    New balance:

    <strong id="newBalance">

        0

    </strong>

</div>


<button
    class="popup-button"
    id="closePopup">

    OK

</button>


</div>

</div>


<script>

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

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


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


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


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


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


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


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


/* =====================================================
   TABS
===================================================== */

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


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


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


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


function showAwardRecords() {

    awardTab.classList.add(
        "active"
    );

    honourTab.classList.remove(
        "active"
    );

    awardPanel.classList.add(
        "active"
    );

    honourPanel.classList.remove(
        "active"
    );
}


function showHonourList() {

    honourTab.classList.add(
        "active"
    );

    awardTab.classList.remove(
        "active"
    );

    honourPanel.classList.add(
        "active"
    );

    awardPanel.classList.remove(
        "active"
    );
}


awardTab.addEventListener(
    "click",
    showAwardRecords
);


honourTab.addEventListener(
    "click",
    showHonourList
);


/* =====================================================
   DRAW SETTINGS
===================================================== */

const SHUFFLE_TIME =
    5000;


const SHUFFLE_SPEED =
    150;


/* =====================================================
   STATE
===================================================== */

let isDrawing =
    false;


/* =====================================================
   GET PRIZES
===================================================== */

function getPrizes() {

    return Array.from(
        prizeGrid.querySelectorAll(
            ".prize"
        )
    );
}


/* =====================================================
   SHUFFLE CARDS
===================================================== */

function shuffleCards() {

    const cards =
        getPrizes();


    for (
        let i = cards.length - 1;
        i > 0;
        i--
    ) {

        const j =
            Math.floor(
                Math.random() *
                (i + 1)
            );


        [
            cards[i],
            cards[j]
        ] =
        [
            cards[j],
            cards[i]
        ];
    }


    cards.forEach(
        card => {

            prizeGrid.appendChild(
                card
            );


            card.style.setProperty(
                "--random-rotate",
                Math.random()
            );
        }
    );


    cards.forEach(
        card => {

            card.classList.add(
                "shuffling"
            );
        }
    );


    setTimeout(
        function () {

            cards.forEach(
                card => {

                    card.classList.remove(
                        "shuffling"
                    );
                }
            );

        },
        100
    );
}


/* =====================================================
   START DRAW
===================================================== */

async function startLuckyDraw() {

    if (isDrawing) {

        return;
    }


    const remaining =
        parseInt(
            chances.textContent,
            10
        );


    if (
        isNaN(remaining) ||
        remaining <= 0
    ) {

        alert(
            "No chances left."
        );

        return;
    }


    isDrawing =
        true;


    startBtn.disabled =
        true;


    startBtn.textContent =
        "Drawing...";


    getPrizes().forEach(
        card => {

            card.classList.remove(
                "winner"
            );
        }
    );


    const startTime =
        Date.now();


    const shuffleInterval =
        setInterval(
            function () {

                shuffleCards();


                if (
                    Date.now() -
                    startTime >=
                    SHUFFLE_TIME
                ) {

                    clearInterval(
                        shuffleInterval
                    );
                }

            },
            SHUFFLE_SPEED
        );


    await new Promise(
        resolve => {

            setTimeout(
                resolve,
                SHUFFLE_TIME
            );
        }
    );


    clearInterval(
        shuffleInterval
    );


    /* ==================================================
       CALL BACKEND
    ================================================== */

    try {

        const response =
            await fetch(
                window.location.href,
                {

                    method: "POST",

                    headers: {

                        "Content-Type":
                            "application/x-www-form-urlencoded; charset=UTF-8"

                    },

                    body:
                        "action=draw"
                }
            );


        const raw =
            await response.text();


        let data;


        try {

            data =
                JSON.parse(
                    raw
                );

        } catch (jsonError) {

            console.error(
                "Server response:",
                raw
            );


            throw new Error(
                "Invalid server response: " +
                raw.substring(
                    0,
                    500
                )
            );
        }


        if (!data.success) {

            alert(
                data.message ||
                "Unable to complete the lucky draw."
            );


            isDrawing =
                false;


            startBtn.disabled =
                parseInt(
                    chances.textContent,
                    10
                ) <= 0;


            startBtn.textContent =
                "Start";


            return;
        }


        /* ==================================================
           FIND SERVER WINNER
        ================================================== */

        const winner =
            getPrizes().find(
                card =>
                    card.getAttribute(
                        "data-prize"
                    ) === data.prize
            );


        if (winner) {

            winner.classList.add(
                "winner"
            );
        }


        /* ==================================================
           UPDATE CHANCES
        ================================================== */

        chances.textContent =
            data.chances;


        /* ==================================================
           UPDATE PRIZE
        ================================================== */

        resultPrize.textContent =
            data.prize;


        /* ==================================================
           UPDATE BALANCE
        ================================================== */

        newBalance.textContent =
            Number(
                data.balance
            ).toLocaleString();


        /* ==================================================
           SHOW POPUP
        ================================================== */

        setTimeout(
            function () {

                popupOverlay.classList.add(
                    "show"
                );


                isDrawing =
                    false;


                startBtn.textContent =
                    "Start";


                if (
                    Number(
                        data.chances
                    ) <= 0
                ) {

                    startBtn.disabled =
                        true;

                } else {

                    startBtn.disabled =
                        false;
                }

            },
            700
        );


    } catch (error) {

        console.error(
            "Lucky Draw Error:",
            error
        );


        alert(
            error.message ||
            "A server error occurred. Please try again."
        );


        isDrawing =
            false;


        startBtn.disabled =
            false;


        startBtn.textContent =
            "Start";
    }
}


/* =====================================================
   START BUTTON
===================================================== */

startBtn.addEventListener(
    "click",
    startLuckyDraw
);


/* =====================================================
   CLOSE POPUP
===================================================== */

function closeResultPopup() {

    popupOverlay.classList.remove(
        "show"
    );


    getPrizes().forEach(
        card => {

            card.classList.remove(
                "winner"
            );
        }
    );
}


closePopup.addEventListener(
    "click",
    closeResultPopup
);


/* =====================================================
   CLOSE POPUP OUTSIDE
===================================================== */

popupOverlay.addEventListener(
    "click",
    function(event) {

        if (
            event.target ===
            popupOverlay
        ) {

            closeResultPopup();
        }

    }
);

</script>


</body>

</html>