<?php
// بسم الله الرحمن الرحیم
// تنظیمات اولیه خطاگیری (در محیط پروداکشن ارورها را در لاگ ذخیره می‌کنیم)
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ob_start(); 
ini_set('log_errors', 1);
ini_set('error_log', 'error.log'); 
error_reporting(E_ALL);

date_default_timezone_set("asia/tehran");

// 1. فراخوانی فایل‌های مورد نیاز
require_once 'config.php'; 
require_once 'jdf.php';  

/**
 * ---------------------------------------------------------
 * بخش API (AJAX)
 * مسئول ارسال قیمت‌ها به صورت JSON به جاوااسکریپت
 * ---------------------------------------------------------
 */
if (isset($_GET['json']) && $_GET['json'] == '1') {
     
    ob_end_clean(); 
    header('Content-Type: application/json; charset=utf-8');

    // مقادیر پیش‌فرض (اگر دیتابیس قطع بود)
    $usdt_price = 60000;    
    $profit_margin = 0.10;   
    $prem_3_usd_base = 15;
    $prem_6_usd_base = 25;
    $prem_12_usd_base = 45;
    $star_usd_base = 0.035; 

    // خواندن از دیتابیس
    if (isset($db) && $db) {
        $settings = [];
        $query_keys = "'usd_irr', 'profit_margin', 'prem3_usd', 'prem6_usd', 'prem12_usd', 'star_usd'";
        
        $sql = "SELECT type_id, columnTwo, `type` FROM settings 
                WHERE `type_id` IN ($query_keys) OR `type` IN ($query_keys)";
        
        $settings_result = $db->query($sql);
        
        if ($settings_result) {
            while ($row = $settings_result->fetch_assoc()) {
                if (!empty($row['type_id'])) $settings[$row['type_id']] = $row;
                if (!empty($row['type'])) $settings[$row['type']] = $row;
            }
        }
        
        // جایگزینی مقادیر دیتابیس
        $usdt_price = (float)($settings['usd_irr']['columnTwo'] ?? $usdt_price);
        $profit_margin = (float)($settings['profit_margin']['type_id'] ?? $profit_margin);
        
        $prem_3_usd_base = (float)($settings['prem3_usd']['type_id'] ?? $prem_3_usd_base);
        $prem_6_usd_base = (float)($settings['prem6_usd']['type_id'] ?? $prem_6_usd_base);
        $prem_12_usd_base = (float)($settings['prem12_usd']['type_id'] ?? $prem_12_usd_base);
        $star_usd_base = (float)($settings['star_usd']['type_id'] ?? $star_usd_base);
    }

    // محاسبه قیمت نهایی
    $usdPriceWithProfit = $usdt_price * (1 + $profit_margin);
    
    $prem3 = $prem_3_usd_base * $usdPriceWithProfit;
    $prem6 = $prem_6_usd_base * $usdPriceWithProfit;
    $prem12 = $prem_12_usd_base * $usdPriceWithProfit;
    $starsPrice = $star_usd_base * $usdPriceWithProfit;

    // تابع رند کردن به بالا (ضریب 100 تومان)
    $format_price_func = function($price) {
        $rounded = ceil($price / 100) * 100;
        return number_format($rounded);
    };

    $output = [
        'prem3' => $format_price_func($prem3),
        'prem6' => $format_price_func($prem6),
        'prem12' => $format_price_func($prem12),
        'stars_base_price' => $starsPrice,
        'last_updated' => date('H:i:s')
    ];

    echo json_encode($output, JSON_UNESCAPED_UNICODE);
    exit; 
}
// --- پایان بخش API ---

ob_end_flush(); 

// مقادیر پیش‌فرض برای جلوگیری از خطای PHP در صورت نبود متغیرها
if (!isset($botusername)) { $botusername = 'YourBotUsername'; }
if (!isset($botName)) { $botName = 'Bot Name'; }
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo htmlspecialchars($botName); ?> - تعرفه خدمات</title>
    
    <script src="lottie/lottie-player.js"></script>
    
    <style>
        /* تعریف فونت‌ها */
        @font-face { font-family: 'Vazirmatn'; src: url('fonts/Vazirmatn-Regular.woff2') format('woff2'); font-weight: 400; font-display: swap; }
        @font-face { font-family: 'Vazirmatn'; src: url('fonts/Vazirmatn-Bold.woff2') format('woff2'); font-weight: 700; font-display: swap; }
        @font-face { font-family: 'Vazirmatn'; src: url('fonts/Vazirmatn-Black.woff2') format('woff2'); font-weight: 900; font-display: swap; }

        :root {
            /* پالت رنگی روشن (شیشه‌ای) */
            --bg-gradient: linear-gradient(135deg, #e0f2fe 0%, #f0f9ff 100%);
            --card-bg: rgba(255, 255, 255, 0.65);
            --card-border: rgba(255, 255, 255, 0.8);
            --text-primary: #1e293b;
            --text-secondary: #64748b;
            --accent: #3b82f6;
            --accent-glow: rgba(59, 130, 246, 0.4);
            --stars-color: #f59e0b;
            --stars-glow: rgba(245, 158, 11, 0.4);
            --input-bg: rgba(255, 255, 255, 0.5);
            --shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
            --radius: 24px;
        }

        body.dark-mode {
            /* پالت رنگی تیره (شیشه‌ای) */
            --bg-gradient: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
            --card-bg: rgba(30, 41, 59, 0.65);
            --card-border: rgba(255, 255, 255, 0.1);
            --text-primary: #f1f5f9;
            --text-secondary: #94a3b8;
            --input-bg: rgba(0, 0, 0, 0.2);
            --shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.3);
        }

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

        body {
            font-family: 'Vazirmatn', sans-serif;
            background: var(--bg-gradient);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            transition: background 0.3s ease, color 0.3s ease;
            overflow-x: hidden;
            position: relative;
        }

        .container {
            width: 100%;
            max-width: 900px;
            padding: 20px;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        /* Header */
        .header { text-align: center; margin: 40px 0 50px; }
        .header h1 {
            font-size: 2.8rem;
            font-weight: 900;
            margin-bottom: 10px;
            background: linear-gradient(to right, var(--accent), #8b5cf6);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .header p { color: var(--text-secondary); font-size: 1.1rem; }
        .last-updated {
            display: inline-block;
            margin-top: 15px;
            padding: 5px 15px;
            background: var(--input-bg);
            border-radius: 20px;
            font-size: 0.85rem;
            color: var(--text-secondary);
            border: 1px solid var(--card-border);
        }

        /* Dark Mode Toggle */
        .theme-switch {
            position: absolute;
            top: 25px;
            right: 25px;
            z-index: 100;
        }
        .switch-label {
            width: 60px;
            height: 32px;
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 50px;
            display: block;
            position: relative;
            cursor: pointer;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        .switch-label::after {
            content: '☀️';
            position: absolute;
            top: 3px;
            left: 3px;
            width: 24px;
            height: 24px;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        input:checked + .switch-label::after {
            transform: translateX(28px);
            content: '🌙';
            background: #334155;
            color: white;
        }
        input:checked + .switch-label { background: var(--accent); border-color: var(--accent); }

        /* Grid Layout */
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
            gap: 30px;
            margin-bottom: 60px;
        }

        /* Cards (Glassmorphism) */
        .card {
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: var(--radius);
            padding: 30px;
            box-shadow: var(--shadow);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            transition: transform 0.3s ease, box-shadow 0.3s ease, border-color 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .card.selected {
            border-color: var(--accent);
            box-shadow: 0 0 0 2px var(--accent), var(--shadow);
        }
        .card.card-stars.selected {
            border-color: var(--stars-color);
            box-shadow: 0 0 0 2px var(--stars-color), var(--shadow);
        }

        .card-head { display: flex; align-items: center; gap: 15px; margin-bottom: 25px; }
        .icon-box {
            width: 54px; height: 54px;
            border-radius: 16px;
            background: rgba(59, 130, 246, 0.1);
            display: flex; align-items: center; justify-content: center;
        }
        .card-stars .icon-box { background: rgba(245, 158, 11, 0.1); }
        .card-title { font-size: 1.4rem; font-weight: 800; }

        /* Price List */
        .price-list { list-style: none; }
        .price-item {
            display: flex; justify-content: space-between; align-items: center;
            padding: 18px;
            margin-bottom: 12px;
            background: var(--input-bg);
            border-radius: 16px;
            border: 1px solid transparent;
            cursor: pointer;
            transition: 0.2s ease;
        }
        .price-item:hover { background: rgba(255, 255, 255, 0.1); border-color: var(--card-border); }
        .price-item.selected {
            background: rgba(59, 130, 246, 0.1);
            border-color: var(--accent);
        }
        .price-item.selected .price { color: var(--accent); font-weight: 800; }
        
        .plan-name { font-weight: 600; }
        .price { font-weight: 700; font-size: 1.1rem; }
        .unit { font-size: 0.75rem; color: var(--text-secondary); margin-right: 4px; font-weight: normal; }

        /* Calculator */
        .calc-box { margin-top: 10px; }
        .calc-input {
            width: 100%;
            padding: 22px;
            border-radius: 18px;
            border: 2px solid var(--card-border);
            background: var(--input-bg);
            color: var(--text-primary);
            font-family: 'Vazirmatn';
            font-size: 1.3rem;
            font-weight: 700;
            text-align: center;
            outline: none;
            transition: 0.3s ease;
        }
        .calc-input:focus {
            border-color: var(--stars-color);
            background: var(--card-bg);
            box-shadow: 0 0 15px var(--stars-glow);
        }
        .calc-input::placeholder { color: var(--text-secondary); font-weight: 400; font-size: 1.1rem; }
        
        .result-area {
            text-align: center;
            min-height: 70px;
            display: flex; flex-direction: column;
            align-items: center; justify-content: center;
            margin-top: 15px;
        }
        .final-price {
            font-size: 2.2rem; font-weight: 900; color: var(--stars-color);
            text-shadow: 0 5px 10px rgba(0,0,0,0.05);
            line-height: 1.2;
        }
        .hint { font-size: 0.9rem; color: var(--text-secondary); }

        /* CTA Button - Center Fixed */
        .cta-wrapper {
            text-align: center;
            margin-top: auto; /* Push to bottom if flex needed */
            width: 100%;
            padding-bottom: 20px;
            display: flex;
            justify-content: center;
        }
        .btn-buy {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            background: var(--accent);
            color: white;
            text-decoration: none;
            font-size: 1.3rem;
            font-weight: 700;
            padding: 20px 50px;
            border-radius: 50px;
            box-shadow: 0 10px 25px var(--accent-glow);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            min-width: 280px;
        }
        .btn-buy:hover {
            transform: translateY(-4px) scale(1.02);
            box-shadow: 0 15px 35px var(--accent-glow);
        }
        .btn-buy:active { transform: scale(0.98); }
        .btn-buy svg { width: 26px; height: 26px; }

        /* Loading Animation */
        .shimmer {
            color: transparent !important;
            background: linear-gradient(90deg, transparent 0%, rgba(150,150,150,0.2) 50%, transparent 100%);
            background-size: 200% 100%;
            animation: shim 1.5s infinite;
            border-radius: 5px;
        }
        @keyframes shim { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }

        footer { text-align: center; padding: 30px; color: var(--text-secondary); font-size: 0.9rem; }
        footer a { color: var(--accent); text-decoration: none; font-weight: bold; }

        @media (max-width: 600px) {
            .header h1 { font-size: 2.2rem; }
            .grid { grid-template-columns: 1fr; }
            .btn-buy { width: 100%; }
        }
    </style>
</head>
<body>

    <div class="theme-switch">
        <input type="checkbox" id="dark-toggle" style="display:none;">
        <label for="dark-toggle" class="switch-label"></label>
    </div>

    <div class="container">
        
        <header class="header">
            <h1>تعرفه خدمات</h1>
            <p>لیست قیمت لحظه‌ای سرویس‌های تلگرام</p>
            <div class="last-updated">آخرین بروزرسانی: <span id="last-update-time">...</span></div>
        </header>

        <div class="grid">
            <div class="card" id="card-premium">
                <div class="card-head">
                    <div class="icon-box">
                        <lottie-player src="lottie/premium.json" background="transparent" speed="1" style="width: 45px; height: 45px;" loop autoplay></lottie-player>
                    </div>
                    <span class="card-title">اشتراک پرمیوم</span>
                </div>
                <ul class="price-list">
                    <li class="price-item" data-plan="prem_3" data-name="اشتراک ۳ ماهه">
                        <span class="plan-name">۳ ماهه</span>
                        <span class="price shimmer" id="price-prem3">...</span>
                    </li>
                    <li class="price-item" data-plan="prem_6" data-name="اشتراک ۶ ماهه">
                        <span class="plan-name">۶ ماهه</span>
                        <span class="price shimmer" id="price-prem6">...</span>
                    </li>
                    <li class="price-item" data-plan="prem_12" data-name="اشتراک ۱۲ ماهه">
                        <span class="plan-name">۱۲ ماهه</span>
                        <span class="price shimmer" id="price-prem12">...</span>
                    </li>
                </ul>
            </div>

            <div class="card card-stars" id="card-stars">
                <div class="card-head">
                    <div class="icon-box">
                        <lottie-player src="lottie/stars.json" background="transparent" speed="1" style="width: 45px; height: 45px;" loop autoplay></lottie-player>
                    </div>
                    <span class="card-title">استارز (Stars)</span>
                </div>
                <div class="calc-box">
                    <input type="number" id="stars-input" class="calc-input" placeholder="تعداد استار (مثلا 500)" inputmode="numeric">
                </div>
                <div class="result-area" id="stars-result">
                    <span class="hint">تعداد را وارد کنید</span>
                </div>
            </div>
        </div>

        <div class="cta-wrapper">
            <a href="https://t.me/<?php echo htmlspecialchars($botusername); ?>" id="cta-btn" class="btn-buy">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span id="cta-text">ورود به ربات</span>
            </a>
        </div>

    </div>

    <footer>
        © <?php echo jdate('Y'); ?> <a href="https://t.me/<?php echo htmlspecialchars($botusername); ?>"><?php echo htmlspecialchars($botName); ?></a>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // DOM Elements
            const els = {
                prem3: document.getElementById('price-prem3'),
                prem6: document.getElementById('price-prem6'),
                prem12: document.getElementById('price-prem12'),
                lastUpdate: document.getElementById('last-update-time'),
                starsIn: document.getElementById('stars-input'),
                starsRes: document.getElementById('stars-result'),
                btn: document.getElementById('cta-btn'),
                btnText: document.getElementById('cta-text'),
                cardPrem: document.getElementById('card-premium'),
                cardStars: document.getElementById('card-stars'),
                premItems: document.querySelectorAll('.price-item'),
                toggle: document.getElementById('dark-toggle')
            };

            let starsBase = 0;
            const botLink = "https://t.me/<?php echo htmlspecialchars($botusername); ?>";

            // 1. Formatter
            const fmt = (n) => new Intl.NumberFormat('fa-IR').format(Math.ceil(n / 100) * 100);

            // 2. Update UI Text
            const setText = (el, val) => {
                el.innerText = fmt(val) + ' تومان';
                el.classList.remove('shimmer');
            };

            // 3. Fetch Data
            const loadData = async () => {
                try {
                    const req = await fetch('?json=1&t=' + Date.now());
                    const data = await req.json();

                    setText(els.prem3, data.prem3.replace(/,/g,''));
                    setText(els.prem6, data.prem6.replace(/,/g,''));
                    setText(els.prem12, data.prem12.replace(/,/g,''));
                    
                    els.lastUpdate.innerText = data.last_updated;
                    starsBase = parseFloat(data.stars_base_price);

                    if(els.starsIn.value) calc();

                } catch(e) { console.error(e); }
            };

            // 4. Calculate Stars
            const calc = () => {
                const v = parseInt(els.starsIn.value);
                if(!v || v < 1) {
                    els.starsRes.innerHTML = '<span class="hint">تعداد را وارد کنید</span>';
                    // Reset selection if input is empty
                    if(document.activeElement !== els.starsIn) {
                        els.cardStars.classList.remove('selected');
                    }
                    return;
                }
                const price = v * starsBase;
                els.starsRes.innerHTML = `<div class="final-price">${fmt(price)} <span class="unit">تومان</span></div>`;
                
                // UI Selection Logic
                els.premItems.forEach(i => i.classList.remove('selected'));
                els.cardPrem.classList.remove('selected');
                els.cardStars.classList.add('selected');

                els.btn.href = `${botLink}?start=stars_${v}`;
                els.btnText.innerText = `خرید ${v} استار`;
            };

            // 5. Event Listeners
            
            // Premium Selection
            els.premItems.forEach(item => {
                item.addEventListener('click', () => {
                    // Reset UI
                    els.premItems.forEach(i => i.classList.remove('selected'));
                    item.classList.add('selected');
                    
                    els.cardStars.classList.remove('selected');
                    els.starsIn.value = '';
                    els.starsRes.innerHTML = '<span class="hint">تعداد را وارد کنید</span>';
                    els.cardPrem.classList.add('selected');

                    const plan = item.dataset.plan;
                    const name = item.dataset.name;
                    els.btn.href = `${botLink}?start=${plan}`;
                    els.btnText.innerText = `خرید ${name}`;
                });
            });

            // Stars Inputs
            els.starsIn.addEventListener('input', calc);
            els.starsIn.addEventListener('focus', () => {
                els.premItems.forEach(i => i.classList.remove('selected'));
                els.cardPrem.classList.remove('selected');
                els.cardStars.classList.add('selected');
            });

            // Dark Mode
            const saved = localStorage.getItem('theme');
            if(saved === 'dark') {
                document.body.classList.add('dark-mode');
                els.toggle.checked = true;
            }
            
            els.toggle.addEventListener('change', (e) => {
                if(e.target.checked) {
                    document.body.classList.add('dark-mode');
                    localStorage.setItem('theme', 'dark');
                } else {
                    document.body.classList.remove('dark-mode');
                    localStorage.setItem('theme', 'light');
                }
            });

            // Initial Load
            loadData();
            setInterval(loadData, 30000);
        });
    </script>
</body>
</html>