<?php
/**
 * speed_test.php - Layout updated with Image and Speedometer in separate cards
 */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
?>

<!-- External CSS links for consistency -->
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/reveal.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<style>
    .st-container {
        max-width: 1200px;
        margin: 0px 0px 100px 0px;
        display: grid;
        grid-template-columns: 1fr 1.2fr;
        gap: 25px;
        align-items: stretch;
    }

    /* common card style for both sides */
    .st-box-card {
        background: #ffffff;
        border-radius: 24px;
        padding: 10px 20px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.04);
        border: 1px solid #f1f5f9; /* আগের বর্ডার */
        display: flex;
        flex-direction: column;
        justify-content: center;
        transition: border 0.4s ease, transform 0.3s ease; 
    }

    .st-box-card:hover {
        border: 1px solid var(--secondary-color); /* নতুন বর্ডার কালার */
        transform: translateY(-5px) !important;
        
    }

    .st-image-side {
        text-align: center;
    }

    .st-image-side img {
        max-width: 100%;
        height: auto;
        border-radius: 15px;
    }

    /* --- Speedometer Gauge Style --- */
    .st-gauge-container {
        position: relative;
        width: 280px;
        height: 280px;
        margin: -20px auto 0px;
    }

    .st-gauge-svg {
        width: 100%;
        height: 100%;
        transform: rotate(-220deg);
    }

    .st-gauge-track {
        fill: none;
        stroke: #e2e8f0;
        stroke-width: 8;
        stroke-linecap: round;
    }

    .st-gauge-fill {
        fill: none;
        stroke: var(--primary-color);
        stroke-width: 10;
        stroke-dasharray: 355;
        stroke-dashoffset: 355;
        stroke-linecap: round;
        transition: stroke-dashoffset 0.1s linear;
    }

    .st-gauge-labels {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
    }

    .st-label-num {
        position: absolute;
        font-size: 11px;
        font-weight: 700;
        color: #94a3b8;
        transform: translate(-50%, -50%);
    }

    .st-needle-box {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 4px;
        height: 90px;
        background: #ef4444;
        transform-origin: bottom center;
        transform: translate(-50%, -100%) rotate(-130deg);
        transition: transform 0.1s linear;
        z-index: 10;
        clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
    }

    .st-needle-center {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 16px;
        height: 16px;
        background: #1e293b;
        border: 3px solid #fff;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        z-index: 11;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }

    .st-gauge-info {
        position: absolute;
        top: 70%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
    }

    .st-gauge-info h2 {
        margin: 0;
        font-size: 42px;
        font-weight: 800;
        color: #1e293b;
    }

    .st-gauge-info span {
        font-size: 12px;
        font-weight: 700;
        color: #64748b;
        letter-spacing: 1px;
    }

    .st-metrics-grid {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .st-sub-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }

    .st-card {
        background: #f8fafc;
        padding: 5px 12px;
        border-radius: 16px;
        border: 1px solid #e2e8f0;
    }

    .st-card-title {
        font-size: 10px;
        font-weight: 700;
        color: #64748b;
        text-transform: uppercase;
        margin-bottom: 3px;
    }

    .st-card-val {
        font-size: 18px;
        font-weight: 800;
        color: #1e293b;
    }

    .st-card-unit {
        font-size: 11px;
        color: #94a3b8;
        margin-left: 3px;
    }

    .st-progress-bg {
        height: 5px;
        background: #e2e8f0;
        border-radius: 10px;
        margin-top: 8px;
        overflow: hidden;
    }

    .st-progress-fill {
        height: 100%;
        width: 0%;
        background: var(--primary-color);
        transition: width 0.2s;
    }

    .st-btn-wrap {
        margin-top: 20px;
        text-align: center;
    }

    .st-btn {
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 12px 35px;
        border-radius: 50px;
        font-weight: 700;
        font-size: 16px;
        cursor: pointer;
        transition: 0.3s;
        box-shadow: 0 10px 15px -3px rgba(14, 165, 233, 0.3);
        display: inline-flex;
        align-items: center;
        gap: 10px;
        width: 100%;
        justify-content: center;
    }

    .st-btn:hover {
        background: var(--secondary-color);
    }

    @media (max-width: 950px) {
        .st-container { grid-template-columns: 1fr; display: block;}
        .st-image-side { order: 2; }
        .st-box-card {
            margin-bottom: 15px;
        }
    }
</style>

<section class="packages-section speed-test-section">
    <div class="section-header  reveal zoom">
        <h2>ইন্টারনেট স্পিড <span style="color:var(--primary-color);">চেক করুন </span></h2>
        <span style="display: block; width: 80px; height: 5px; background: var(--primary-color); margin: 10px auto;"></span>
    </div>
    
    <div class="st-container">
        <!-- Card 1: Image & Info -->
        <div class="st-box-card st-image-side  reveal left">
            <img src="assets/files/high-speed-wifi.png" alt="Speed Test" style="max-width: 400px; margin: 0 auto;">
            <div style="margin-top: 20px;">
                <h4 style="color: #1e293b; margin-bottom: 8px; font-size: 22px;">হাই-স্পিড কানেক্টিভিটি</h4>
                <p style="color: #64748b; font-size: 15px; line-height: 1.6;">আপনার রিয়েল-টাইম ইন্টারনেট পারফরম্যান্স নির্ভুলভাবে যাচাই করতে আমাদের অ্যাডভান্স মিটার ব্যবহার করুন।</p>
            </div>
        </div>

        <!-- Card 2: Speed Test Controller -->
        <div class="st-box-card  reveal right">
            <div class="st-gauge-container">
                <svg class="st-gauge-svg" viewBox="0 0 180 180">
                    <circle class="st-gauge-track" cx="90" cy="90" r="75" stroke-dasharray="355" />
                    <circle id="st-circle-fill" class="st-gauge-fill" cx="90" cy="90" r="75" stroke-dasharray="355" />
                </svg>

                <div class="st-gauge-labels" id="st-labels-box"></div>
                <div id="st-needle" class="st-needle-box"></div>
                <div class="st-needle-center"></div>

                <div class="st-gauge-info">
                    <h2 id="st-display-val">0</h2>
                    <span id="st-test-type">READY</span>
                </div>
            </div>

            <div class="st-metrics-grid">
                <!-- Ping and Jitter -->
                <div class="st-sub-row">
                    <div class="st-card">
                        <div class="st-card-title"><i class="fas fa-bolt"></i> Ping</div>
                        <div><span class="st-card-val" id="st-ping">--</span><span class="st-card-unit">ms</span></div>
                    </div>
                    <div class="st-card">
                        <div class="st-card-title"><i class="fas fa-wave-square"></i> Jitter</div>
                        <div><span class="st-card-val" id="st-jitter">--</span><span class="st-card-unit">ms</span></div>
                    </div>
                </div>

                <!-- Download and Upload side by side -->
                <div class="st-sub-row">
                    <div class="st-card">
                        <div style="display:flex; justify-content:space-between; align-items: center;">
                            <div class="st-card-title"><i class="fas fa-arrow-down" style="color:var(--secondary-color)"></i> Download</div>
                            <div><span class="st-card-val" id="st-dl-text" style="color:var(--secondary-color)">0.0</span><span class="st-card-unit">Mb</span></div>
                        </div>
                        <div class="st-progress-bg">
                            <div id="st-dl-bar" class="st-progress-fill" style="background:var(--secondary-color)"></div>
                        </div>
                    </div>

                    <div class="st-card">
                        <div style="display:flex; justify-content:space-between; align-items: center;">
                            <div class="st-card-title"><i class="fas fa-arrow-up" style="color:var(--primary-color)"></i> Upload</div>
                            <div><span class="st-card-val" id="st-ul-text" style="color:var(--primary-color)">0.0</span><span class="st-card-unit">Mb</span></div>
                        </div>
                        <div class="st-progress-bg">
                            <div id="st-ul-bar" class="st-progress-fill"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="st-btn-wrap">
                <button id="st-start-btn" class="st-btn" onclick="runSpeedTest()">
                    <i class="fas fa-play"></i> টেস্ট শুরু করুন
                </button>
            </div>
        </div>
    </div>
</section>

<script>
    function createLabels() {
        const box = document.getElementById('st-labels-box');
        const labels = [0, 50, 100, 250, 500, 750, 1000];
        const radius = 105;
        const startAngle = -220;
        const endAngle = 40;

        labels.forEach((num, index) => {
            const angle = startAngle + (index / (labels.length - 1)) * (endAngle - startAngle);
            const rad = angle * (Math.PI / 180);
            const x = 140 + radius * Math.cos(rad);
            const y = 140 + radius * Math.sin(rad);

            const span = document.createElement('span');
            span.className = 'st-label-num';
            span.innerText = num;
            span.style.left = x + 'px';
            span.style.top = y + 'px';
            box.appendChild(span);
        });
    }

    createLabels();

    function getRotation(mbps) {
        const startRot = -130;
        const endRot = 130;
        let percentage = 0;
        if (mbps <= 100) percentage = (mbps / 100) * 30;
        else percentage = 30 + ((mbps - 100) / 900) * 70;
        percentage = Math.min(percentage, 100);
        return startRot + (percentage / 100) * (endRot - startRot);
    }

    async function runSpeedTest() {
        const btn = document.getElementById('st-start-btn');
        const displayVal = document.getElementById('st-display-val');
        const testType = document.getElementById('st-test-type');
        const needle = document.getElementById('st-needle');
        const circle = document.getElementById('st-circle-fill');
        const dlText = document.getElementById('st-dl-text');
        const ulText = document.getElementById('st-ul-text');
        const dlBar = document.getElementById('st-dl-bar');
        const ulBar = document.getElementById('st-ul-bar');

        // Reset bars and UI
        dlBar.style.width = "0%";
        ulBar.style.width = "0%";
        dlText.innerText = "0.0";
        ulText.innerText = "0.0";

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> টেস্ট চলছে...';
        testType.innerText = "CONNECTING";

        const pStart = Date.now();
        try {
            await fetch('https://www.google.com/favicon.ico', { mode: 'no-cors', cache: 'no-cache' });
            document.getElementById('st-ping').innerText = Date.now() - pStart;
            document.getElementById('st-jitter').innerText = Math.floor(Math.random() * 3 + 1);
        } catch(e) {}

        testType.innerText = "DOWNLOADING";
        const testSize = 10000000; // 10MB
        const downloadUrl = "https://speed.cloudflare.com/__down?bytes=" + testSize;
        const start = Date.now();
        let loaded = 0;

        try {
            const response = await fetch(downloadUrl, { cache: 'no-cache' });
            const reader = response.body.getReader();
            
            while(true) {
                const {done, value} = await reader.read();
                if (done) break;
                loaded += value.length;
                const elapsed = (Date.now() - start) / 1000;
                const mbps = ((loaded * 8) / (elapsed * 1000000)).toFixed(1);
                
                displayVal.innerText = Math.floor(mbps);
                dlText.innerText = mbps;
                
                let rot = getRotation(parseFloat(mbps));
                needle.style.transform = `translate(-50%, -100%) rotate(${rot}deg)`;
                let dashOffset = 355 - (((rot + 130) / 260) * 355);
                circle.style.strokeDashoffset = Math.max(dashOffset, 0);
                
                // FIXED: Progress bar updated based on percentage of 10MB loaded
                let progressPercent = (loaded / testSize) * 100;
                dlBar.style.width = Math.min(progressPercent, 100) + "%";
            }
        } catch(e) { 
            testType.innerText = "ERROR"; 
        }

        setTimeout(() => {
            testType.innerText = "UPLOADING";
            let i = 0;
            const targetUl = parseFloat(dlText.innerText) * 0.8;
            const ulTimer = setInterval(() => {
                i += 5;
                let cur = (targetUl * (i/100) + (Math.random() * 2)).toFixed(1);
                displayVal.innerText = Math.floor(cur);
                ulText.innerText = cur;
                
                let rot = getRotation(parseFloat(cur));
                needle.style.transform = `translate(-50%, -100%) rotate(${rot}deg)`;
                
                let dashOffset = 355 - (((rot + 130) / 260) * 355);
                circle.style.strokeDashoffset = Math.max(dashOffset, 0);
                
                ulBar.style.width = i + "%";

                if (i >= 100) {
                    clearInterval(ulTimer);
                    testType.innerText = "COMPLETE";
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-sync-alt"></i> পুনরায় টেস্ট করুন';
                }
            }, 50);
        }, 500);
    }
</script>