<?php
/* ==========================================================
   points.php
   CREDIT SCORE / POINTS SYSTEM
   ========================================================== */

session_start();
require_once "db.php";

date_default_timezone_set("Africa/Nairobi");


/* ==========================================================
   AUTH CHECK
   ========================================================== */

if (!isset($_SESSION['user_id']) || (int)$_SESSION['user_id'] <= 0) {

    header("Location: login.php");
    exit;

}

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


/* ==========================================================
   GET CURRENT USER
   ========================================================== */

$stmt = $conn->prepare("
    SELECT
        id,
        phone,
        referral_code,
        referred_by,
        created_at
    FROM users
    WHERE id = ?
    LIMIT 1
");

if (!$stmt) {
    die("Database error: " . $conn->error);
}

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

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

$stmt->close();


if (!$user) {

    session_destroy();

    header("Location: login.php");
    exit;

}


/* ==========================================================
   INITIAL CREDIT SCORE
   ========================================================== */

$initial_score = 60;


/* ==========================================================
   COUNT ACTIVE INVESTMENTS
   ==========================================================

   Every active investment = +5 points
========================================================== */

$active_investments = 0;

$stmt = $conn->prepare("
    SELECT COUNT(*) AS total
    FROM investments
    WHERE user_id = ?
      AND LOWER(Status) = 'active'
");

if ($stmt) {

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

    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    $active_investments = (int)($row['total'] ?? 0);

    $stmt->close();

}


/* ==========================================================
   INVESTMENT POINTS
   ========================================================== */

$investment_points =
    $active_investments * 5;


/* ==========================================================
   COUNT ACTIVE DIRECT REFERRALS
   ==========================================================

   A direct referral is:

   users.referred_by = current user's ID

   AND the referred user has at least one
   active investment.

   Every such direct member = +1 point.
========================================================== */

$active_direct_members = 0;

$stmt = $conn->prepare("
    SELECT COUNT(DISTINCT u.id) AS total
    FROM users u
    INNER JOIN investments i
        ON i.user_id = u.id
    WHERE u.referred_by = ?
      AND LOWER(i.Status) = 'active'
");

if ($stmt) {

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

    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    $active_direct_members =
        (int)($row['total'] ?? 0);

    $stmt->close();

}


/* ==========================================================
   DIRECT REFERRAL POINTS
   ========================================================== */

$referral_points =
    $active_direct_members;


/* ==========================================================
   TOTAL CREDIT SCORE
   ========================================================== */

$credit_score =
    $initial_score
    + $investment_points
    + $referral_points;


/* ==========================================================
   GAUGE VALUE
   ==========================================================

   Gauge design is 0 - 100.

   If actual score is above 100,
   needle stays at 100.
========================================================== */

$gauge_score = min(100, max(0, $credit_score));


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

$initial_score_display =
    number_format($initial_score);

$credit_score_display =
    number_format($credit_score);

$active_investments_display =
    number_format($active_investments);

$investment_points_display =
    number_format($investment_points);

$active_direct_members_display =
    number_format($active_direct_members);

$referral_points_display =
    number_format($referral_points);

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

<head>

<meta charset="UTF-8">

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

<title>Credit Score</title>


<style>

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

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

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

body{
    font-family:Arial,Helvetica,sans-serif;
    background:#f5f5f5;
    color:#333;
    overflow-x:hidden;
}


/* =====================================================
   HEADER
===================================================== */

.header{
    height:106px;
    background:#147238;
    color:#fff;

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

    position:relative;
}

.header-title{
    font-size:28px;
    font-weight:700;
    line-height:1;
}

.back{
    position:absolute;

    left:42px;
    top:50%;

    transform:translateY(-50%);

    width:28px;
    height:42px;

    cursor:pointer;
}

.back:before,
.back:after{

    content:"";

    position:absolute;

    width:27px;
    height:4px;

    background:#fff;

    border-radius:4px;

    left:0;
}

.back:before{
    top:12px;
    transform:rotate(45deg);
}

.back:after{
    top:30px;
    transform:rotate(-45deg);
}


/* =====================================================
   MAIN
===================================================== */

.main{
    width:100%;
    max-width:920px;

    margin:0 auto;

    padding-bottom:50px;
}


/* =====================================================
   SCORE CARD
===================================================== */

.score-card{

    width:calc(100% - 52px);

    margin:0 auto;

    background:#fff;

    border-radius:0 0 42px 42px;

    padding:42px 42px 35px;

    position:relative;
}


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

.score-title{

    color:#176f3b;

    font-size:28px;

    font-weight:700;

    line-height:1.2;
}


/* =====================================================
   TOP DOTS
===================================================== */

.dots{

    position:absolute;

    right:48px;
    top:51px;

    display:flex;

    align-items:center;

    gap:13px;
}

.dot{

    width:16px;
    height:16px;

    border-radius:50%;
}

.dot.one{
    background:#ed6398;
}

.dot.two{
    background:#f4d009;
}

.dot.three{
    background:#f18a08;
}

.dot.four{
    background:#e865a0;
}


/* =====================================================
   GAUGE AREA
===================================================== */

.gauge-wrap{

    width:100%;

    max-width:690px;

    margin:55px auto 0;

    position:relative;

    aspect-ratio:1 / 1;
}

.gauge{

    width:100%;
    height:100%;

    display:block;

    overflow:visible;
}


/* =====================================================
   SCORE DETAILS
===================================================== */

.score-details{

    margin-top:25px;

    display:grid;

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

    gap:14px;
}

.detail-box{

    background:#f5f6d9;

    border-radius:18px;

    padding:18px 20px;
}

.detail-title{

    color:#666;

    font-size:15px;

    margin-bottom:7px;
}

.detail-value{

    color:#176f3b;

    font-size:22px;

    font-weight:700;
}


/* =====================================================
   INSTRUCTIONS
===================================================== */

.instructions{

    width:calc(100% - 52px);

    margin:40px auto 0;

    background:#fff;

    border-radius:42px;

    padding:40px 42px 45px;
}


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

.instructions-title{

    display:flex;

    align-items:center;

    gap:14px;

    font-size:27px;

    font-weight:700;

    color:#303030;

    margin-bottom:35px;
}

.instructions-title:before{

    content:"";

    width:8px;
    height:36px;

    background:#f39a08;

    border-radius:8px;

    flex-shrink:0;
}


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

.initial{

    width:100%;

    min-height:105px;

    background:#f5f6d9;

    border-radius:24px;

    display:flex;

    align-items:center;

    justify-content:space-between;

    gap:15px;

    padding:0 32px;

    margin-bottom:32px;
}

.initial-label{

    font-size:21px;

    color:#686868;
}

.initial-score{

    font-size:25px;

    font-weight:700;

    color:#292929;

    white-space:nowrap;
}


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

.rule{

    display:grid;

    grid-template-columns:38px 1fr;

    gap:5px;

    margin-bottom:22px;
}

.rule-number{

    font-size:21px;

    color:#247943;

    font-weight:700;
}

.rule-text{

    font-size:20px;

    color:#666;

    line-height:1.5;
}


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

@media(max-width:700px){

    .header{
        height:56px;
    }

    .header-title{
        font-size:22px;
    }

    .back{
        left:43px;
    }

    .score-card{

        width:calc(100% - 52px);

        padding:38px 42px 32px;
    }

    .score-title{
        font-size:27px;
    }

    .dots{

        right:44px;
        top:52px;

        gap:11px;
    }

    .dot{

        width:15px;
        height:15px;
    }

    .gauge-wrap{

        width:100%;

        max-width:none;

        margin-top:55px;
    }

    .instructions{

        width:calc(100% - 52px);

        padding:38px 42px 43px;
    }

    .instructions-title{
        font-size:27px;
    }

    .initial{
        padding:0 32px;
    }

    .initial-label{
        font-size:20px;
    }

    .initial-score{
        font-size:24px;
    }

    .rule-number{
        font-size:20px;
    }

    .rule-text{
        font-size:20px;
    }

}


/* =====================================================
   MOBILE
===================================================== */

@media(max-width:500px){

    .header{
        height:56px;
    }

    .header-title{
        font-size:22px;
    }

    .back{

        left:43px;

        transform:
            translateY(-50%)
            scale(.85);
    }

    .score-card{

        width:calc(100% - 52px);

        padding:37px 42px 30px;

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

    .score-title{

        font-size:26px;

        white-space:nowrap;
    }

    .dots{

        right:42px;

        top:52px;

        gap:10px;
    }

    .dot{

        width:14px;
        height:14px;
    }

    .gauge-wrap{

        width:100%;

        margin-top:48px;
    }

    .score-details{

        grid-template-columns:1fr;

    }

    .instructions{

        width:calc(100% - 52px);

        margin-top:38px;

        padding:38px 42px 42px;

        border-radius:42px;
    }

    .instructions-title{

        font-size:26px;

        gap:14px;

        margin-bottom:35px;
    }

    .instructions-title:before{

        width:8px;
        height:34px;
    }

    .initial{

        min-height:105px;

        padding:0 30px;

        border-radius:24px;

        gap:12px;
    }

    .initial-label{

        font-size:19px;

        line-height:1.3;
    }

    .initial-score{
        font-size:20px;
    }

    .rule{

        grid-template-columns:32px 1fr;

        gap:4px;

        margin-bottom:20px;
    }

    .rule-number{
        font-size:16px;
    }

    .rule-text{

        font-size:15px;

        line-height:1.5;
    }

}


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

@media(max-width:380px){

    .score-card,
    .instructions{

        width:calc(100% - 36px);
    }

    .score-card{

        padding-left:30px;
        padding-right:30px;
    }

    .score-title{
        font-size:20px;
    }

    .dots{

        right:28px;

        gap:7px;
    }

    .dot{

        width:13px;
        height:13px;
    }

    .gauge-wrap{
        margin-top:45px;
    }

    .instructions{

        padding-left:30px;
        padding-right:30px;
    }

    .instructions-title{
        font-size:23px;
    }

    .instructions-title:before{

        width:7px;
        height:30px;
    }

    .initial{

        min-height:95px;

        padding:0 22px;
    }

    .initial-label{
        font-size:17px;
    }

    .initial-score{
        font-size:20px;
    }

    .rule{

        grid-template-columns:28px 1fr;
    }

    .rule-number{
        font-size:17px;
    }

    .rule-text{

        font-size:16px;

        line-height:1.5;
    }

}


/* =====================================================
   SVG GAUGE
===================================================== */

</style>

</head>


<body>


<!-- =====================================================
     HEADER
===================================================== -->

<header class="header">

    <div
        class="back"
        onclick="goBack()"
    ></div>

    <div class="header-title">
        Credit Score
    </div>

</header>



<main class="main">


<!-- =====================================================
     CREDIT SCORE CARD
===================================================== -->

<section class="score-card">


    <h1 class="score-title">
        My Credit Score
    </h1>


    <!-- TOP DOTS -->

    <div class="dots">

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

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

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

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

    </div>



    <!-- =================================================
         GAUGE
    ================================================== -->

    <div class="gauge-wrap">

        <svg
            id="creditGauge"
            class="gauge"
            viewBox="0 0 700 700"
            xmlns="http://www.w3.org/2000/svg"
        >

            <g id="gaugeSegments"></g>


            <!-- INNER WHITE RING -->

            <circle
                cx="350"
                cy="350"
                r="188"
                fill="none"
                stroke="#ffffff"
                stroke-width="38"
            />


            <!-- TICKS -->

            <g id="gaugeTicks"></g>


            <!-- NUMBERS -->

            <g
                id="gaugeNumbers"
                font-family="Arial, Helvetica, sans-serif"
                font-size="25"
                fill="#444"
                text-anchor="middle"
                dominant-baseline="middle"
            ></g>


            <!-- NEEDLE -->

            <g id="needle">

                <polygon
                    id="needleShape"
                    fill="#f3d000"
                ></polygon>

                <circle
                    cx="350"
                    cy="350"
                    r="9"
                    fill="#f3d000"
                />

            </g>


            <!-- CENTER TEXT -->

            <text
                x="350"
                y="390"
                text-anchor="middle"
                font-family="Arial, Helvetica, sans-serif"
                font-size="30"
                fill="#333"
            >
                Credit Score
            </text>


            <text
                id="scoreNumber"
                x="350"
                y="450"
                text-anchor="middle"
                font-family="Arial, Helvetica, sans-serif"
                font-size="54"
                font-weight="700"
                fill="#19743e"
            >
                <?php echo htmlspecialchars($credit_score_display); ?>
            </text>


        </svg>

    </div>


    <!-- =================================================
         POINT SUMMARY
    ================================================== -->

    <div class="score-details">

        <div class="detail-box">

            <div class="detail-title">
                Active Investments
            </div>

            <div class="detail-value">
                <?php echo $active_investments_display; ?>
            </div>

        </div>


        <div class="detail-box">

            <div class="detail-title">
                Investment Points
            </div>

            <div class="detail-value">
                +<?php echo $investment_points_display; ?>
            </div>

        </div>


        <div class="detail-box">

            <div class="detail-title">
                Active Direct Members
            </div>

            <div class="detail-value">
                <?php echo $active_direct_members_display; ?>
            </div>

        </div>


        <div class="detail-box">

            <div class="detail-title">
                Referral Points
            </div>

            <div class="detail-value">
                +<?php echo $referral_points_display; ?>
            </div>

        </div>

    </div>

</section>



<!-- =====================================================
     INSTRUCTIONS
===================================================== -->

<section class="instructions">


    <h2 class="instructions-title">
        Instructions
    </h2>


    <!-- INITIAL SCORE -->

    <div class="initial">

        <div class="initial-label">
            Initial credit score
        </div>

        <div class="initial-score">
            <?php echo $initial_score_display; ?> points
        </div>

    </div>


    <!-- RULE 1 -->

    <div class="rule">

        <div class="rule-number">
            1.
        </div>

        <div class="rule-text">
            +5 points for every active investment you make.
        </div>

    </div>


    <!-- RULE 2 -->

    <div class="rule">

        <div class="rule-number">
            2.
        </div>

        <div class="rule-text">
            +1 point for each direct member you invite who becomes an official employee with an active investment.
        </div>

    </div>


    <!-- RULE 3 -->

    <div class="rule">

        <div class="rule-number">
            3.
        </div>

        <div class="rule-text">
            Only direct referrals count. Indirect referrals do not add credit score points.
        </div>

    </div>


</section>


</main>



<script>

/* =====================================================
   CURRENT SCORE FROM PHP
===================================================== */

const CURRENT_SCORE =
    <?php echo (float)$gauge_score; ?>;


/* =====================================================
   SVG HELPERS
===================================================== */

const NS = "http://www.w3.org/2000/svg";

const svg =
    document.getElementById("creditGauge");

const segments =
    document.getElementById("gaugeSegments");

const ticks =
    document.getElementById("gaugeTicks");

const numbers =
    document.getElementById("gaugeNumbers");

const needle =
    document.getElementById("needleShape");


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

const CX = 350;
const CY = 350;

const OUTER_RADIUS = 238;

const OUTER_WIDTH = 67;

const START_ANGLE = 135;

const END_ANGLE = 405;


/* =====================================================
   POLAR COORDINATE
===================================================== */

function polar(
    cx,
    cy,
    radius,
    angle
){

    const radians =
        angle * Math.PI / 180;

    return {

        x:
            cx +
            radius *
            Math.cos(radians),

        y:
            cy +
            radius *
            Math.sin(radians)

    };

}


/* =====================================================
   ARC PATH
===================================================== */

function arcPath(
    cx,
    cy,
    radius,
    startAngle,
    endAngle
){

    const start =
        polar(
            cx,
            cy,
            radius,
            startAngle
        );

    const end =
        polar(
            cx,
            cy,
            radius,
            endAngle
        );

    const largeArc =
        (endAngle - startAngle) > 180
        ? 1
        : 0;

    return `
        M ${start.x} ${start.y}
        A ${radius} ${radius}
        0 ${largeArc} 1
        ${end.x} ${end.y}
    `;

}


/* =====================================================
   GAUGE SEGMENTS
===================================================== */

const colorSegments = [

    {
        from:0,
        to:30,
        color:"#ff4f55"
    },

    {
        from:30,
        to:50,
        color:"#ff8b00"
    },

    {
        from:50,
        to:70,
        color:"#ffd600"
    },

    {
        from:70,
        to:90,
        color:"#43c719"
    },

    {
        from:90,
        to:100,
        color:"#1689ec"
    }

];


colorSegments.forEach(
    function(segment){

        const start =
            START_ANGLE +
            (segment.from / 100) *
            (END_ANGLE - START_ANGLE);

        const end =
            START_ANGLE +
            (segment.to / 100) *
            (END_ANGLE - START_ANGLE);

        const path =
            document.createElementNS(
                NS,
                "path"
            );

        path.setAttribute(
            "d",
            arcPath(
                CX,
                CY,
                OUTER_RADIUS,
                start,
                end
            )
        );

        path.setAttribute(
            "fill",
            "none"
        );

        path.setAttribute(
            "stroke",
            segment.color
        );

        path.setAttribute(
            "stroke-width",
            OUTER_WIDTH
        );

        path.setAttribute(
            "stroke-linecap",
            "butt"
        );

        segments.appendChild(path);

    }
);


/* =====================================================
   TICKS
===================================================== */

const TOTAL_TICKS = 51;


for(
    let i = 0;
    i < TOTAL_TICKS;
    i++
){

    const value = i * 2;

    const angle =
        START_ANGLE +
        (value / 100) *
        (END_ANGLE - START_ANGLE);

    const radians =
        angle * Math.PI / 180;

    const major =
        value % 10 === 0;

    const outerRadius = 204;

    const innerRadius =
        major
        ? 166
        : 176;

    const x1 =
        CX +
        innerRadius *
        Math.cos(radians);

    const y1 =
        CY +
        innerRadius *
        Math.sin(radians);

    const x2 =
        CX +
        outerRadius *
        Math.cos(radians);

    const y2 =
        CY +
        outerRadius *
        Math.sin(radians);

    const line =
        document.createElementNS(
            NS,
            "line"
        );

    line.setAttribute("x1", x1);
    line.setAttribute("y1", y1);

    line.setAttribute("x2", x2);
    line.setAttribute("y2", y2);


    let tickColor;


    if(value <= 30){

        tickColor = "#f05458";

    }
    else if(value <= 50){

        tickColor = "#ef8500";

    }
    else if(value <= 70){

        tickColor = "#f2cf00";

    }
    else if(value <= 90){

        tickColor = "#45b927";

    }
    else{

        tickColor = "#1689ec";

    }


    line.setAttribute(
        "stroke",
        tickColor
    );

    line.setAttribute(
        "stroke-width",
        major ? "9" : "5"
    );

    line.setAttribute(
        "stroke-linecap",
        "butt"
    );

    ticks.appendChild(line);

}


/* =====================================================
   NUMBER LABELS
===================================================== */

for(
    let value = 0;
    value <= 100;
    value += 10
){

    const angle =
        START_ANGLE +
        (value / 100) *
        (END_ANGLE - START_ANGLE);

    const position =
        polar(
            CX,
            CY,
            292,
            angle
        );

    const text =
        document.createElementNS(
            NS,
            "text"
        );

    text.setAttribute(
        "x",
        position.x
    );

    text.setAttribute(
        "y",
        position.y
    );

    text.textContent = value;

    numbers.appendChild(text);

}


/* =====================================================
   NEEDLE
===================================================== */

const needleAngle =
    START_ANGLE +
    (CURRENT_SCORE / 100) *
    (END_ANGLE - START_ANGLE);


const needleLength = 157;

const needleWidth = 16;


const radians =
    needleAngle *
    Math.PI / 180;


const tip = {

    x:
        CX +
        needleLength *
        Math.cos(radians),

    y:
        CY +
        needleLength *
        Math.sin(radians)

};


const perpendicular = {

    x:
        Math.cos(
            radians +
            Math.PI / 2
        ),

    y:
        Math.sin(
            radians +
            Math.PI / 2
        )

};


const base1 = {

    x:
        CX +
        perpendicular.x *
        needleWidth,

    y:
        CY +
        perpendicular.y *
        needleWidth

};


const base2 = {

    x:
        CX -
        perpendicular.x *
        needleWidth,

    y:
        CY -
        perpendicular.y *
        needleWidth

};


needle.setAttribute(
    "points",

    `${tip.x},${tip.y}
     ${base1.x},${base1.y}
     ${base2.x},${base2.y}`
);


/* =====================================================
   BACK BUTTON
===================================================== */

function goBack(){

    if(
        document.referrer &&
        document.referrer.indexOf(
            window.location.host
        ) !== -1
    ){

        history.back();

    }
    else{

        window.location.href =
            "home.php";

    }

}

</script>


</body>
</html>