<?php
require_once 'includes/config.php';
require_once 'includes/device_security.php';
requireLogin();
$user = getCurrentUser();
$db   = getDB();

// User's current package
$userPkg = null;
try {
    $s = $db->prepare("SELECT p.* FROM users u LEFT JOIN user_packages p ON u.package_id=p.id WHERE u.id=?");
    $s->execute([$user['id']]);
    $userPkg = $s->fetch();
    if (!$userPkg) {
        $userPkg = ['id'=>1,'name'=>'Basic','color'=>'#1a3c8f','upgrade_fee'=>0,'topup_commission'=>0,'intl_commission'=>0,'pin_commission'=>0,'gift_commission'=>0,'card_commission'=>0,'drive_commission'=>0,'manual_drive_commission'=>0];
    }
} catch(Exception $e) { $userPkg = ['id'=>1,'name'=>'Basic','color'=>'#1a3c8f']; }

// Available packages for upgrade
$availPkgs = [];
try {
    $availPkgs = $db->query("SELECT * FROM user_packages WHERE is_active=1 ORDER BY id")->fetchAll();
} catch(Exception $e) {}

// Get all active currencies
$currencies = [];
try {
    $currencies = $db->query("SELECT * FROM currencies WHERE is_active=1 ORDER BY is_default DESC, code")->fetchAll();
} catch(Exception $e) {}

$userCurrCode = $user['preferred_currency'] ?? 'BDT';

// Load user devices
$myDevices = [];
$maxDevices = intval(getSetting('max_devices') ?? 3);
try {
    initDeviceTables();
    $s = $db->prepare("SELECT * FROM user_devices WHERE user_id=? ORDER BY last_seen DESC");
    $s->execute([$user['id']]); $myDevices = $s->fetchAll();
} catch(Exception $e) {}
$currentToken = $_SESSION['device_token'] ?? '';
?>
<!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>Profile - <?= SITE_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        *{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
        :root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
        body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;padding-bottom:90px}
        .hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px;position:sticky;top:0;z-index:50}
        .hdr-in{display:flex;align-items:center;gap:12px;height:58px;max-width:480px;margin:0 auto}
        .back-btn{width:36px;height:36px;background:rgba(255,255,255,0.15);border:none;color:white;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:17px;cursor:pointer}
        .hdr-title{color:white;font-size:18px;font-weight:700}

        .content{max-width:480px;margin:0 auto;padding:18px}

        /* Profile Card */
        .profile-card{background:linear-gradient(135deg,var(--dark),var(--primary));border-radius:20px;padding:24px;text-align:center;margin-bottom:18px;color:white}
        .avatar{width:72px;height:72px;background:rgba(255,255,255,0.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;margin:0 auto 12px}
        .p-name{font-size:20px;font-weight:800}
        .p-phone{font-size:14px;opacity:0.7;margin-top:4px}
        .p-role{display:inline-block;background:rgba(255,255,255,0.2);padding:4px 12px;border-radius:20px;font-size:12px;font-weight:600;margin-top:8px}
        .p-bal{background:rgba(255,255,255,0.12);border-radius:12px;padding:12px 16px;margin-top:14px;display:flex;justify-content:space-between;align-items:center}
        .p-bal-lbl{font-size:12px;opacity:0.7}
        .p-bal-val{font-size:22px;font-weight:800}

        .section{background:white;border-radius:16px;padding:18px;margin-bottom:14px;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
        .sec-title{font-size:14px;font-weight:700;color:var(--dark);margin-bottom:14px;display:flex;align-items:center;gap:8px;border-bottom:2px solid #f5f5f5;padding-bottom:10px}
        .info-row{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid #f5f5f5}
        .info-row:last-child{border:none}
        .info-lbl{font-size:13px;color:#888}
        .info-val{font-size:13px;font-weight:600;color:#333}

        /* Currency Selector */
        .cur-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-top:10px}
        .cur-item{border:2px solid #e8ecf4;border-radius:12px;padding:10px 8px;text-align:center;cursor:pointer;transition:0.2s;background:white}
        .cur-item.active{border-color:var(--primary);background:#eef2ff}
        .cur-item:active{transform:scale(0.96)}
        .cur-sym{font-size:18px;font-weight:800;color:var(--primary);display:block;margin-bottom:3px}
        .cur-code{font-size:11px;font-weight:700;color:#333;display:block}
        .cur-name{font-size:10px;color:#888;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .cur-rate{font-size:9px;color:#aaa;display:block;font-family:monospace}

        .note-box{background:#eef2ff;border-radius:10px;padding:10px 14px;font-size:12px;color:#1a3c8f;margin-top:12px;display:flex;align-items:flex-start;gap:8px}

        .save-btn{width:100%;padding:14px;background:var(--primary);color:white;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer;margin-top:14px;display:flex;align-items:center;justify-content:center;gap:8px}
        .save-btn:active{background:#152f70}

        .toast{position:fixed;bottom:90px;left:50%;transform:translateX(-50%);background:#333;color:white;padding:10px 20px;border-radius:20px;font-size:13px;font-weight:600;z-index:999;opacity:0;transition:0.3s;white-space:nowrap}
        .toast.show{opacity:1}

        .menu-item{display:flex;align-items:center;gap:14px;padding:14px 0;border-bottom:1px solid #f5f5f5;cursor:pointer;text-decoration:none;color:#333}
        .menu-item:last-child{border:none}
        .menu-ic{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
        .menu-txt{flex:1;font-size:14px;font-weight:600}
        .menu-arrow{color:#ddd;font-size:12px}
        /* Package */
        .pkg-current{background:linear-gradient(135deg,var(--c,#1a3c8f),var(--c2,#2856c8));border-radius:14px;padding:16px;color:white;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between}
        .pkg-badge-big{font-size:18px;font-weight:800}
        .pkg-comm-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;margin-top:10px}
        .pkg-comm-item{background:rgba(255,255,255,0.15);border-radius:8px;padding:6px 8px;text-align:center}
        .pkg-comm-item .pci-val{font-size:14px;font-weight:800}
        .pkg-comm-item .pci-lbl{font-size:9px;opacity:0.8;margin-top:1px}
        .pkg-upgrade-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px}
        .pkg-upgrade-item{border:2px solid #e8ecf4;border-radius:13px;padding:12px;cursor:pointer;transition:0.2s;background:#f8fafc;position:relative}
        .pkg-upgrade-item.current{border-color:var(--primary);background:#eef2ff}
        .pkg-upgrade-item:active{transform:scale(0.97)}
        .pkg-upgrade-item .pui-name{font-size:13px;font-weight:800;margin-bottom:4px}
        .pkg-upgrade-item .pui-fee{font-size:12px;color:#e53e3e;font-weight:700}
        .pkg-upgrade-item .pui-free{font-size:12px;color:#38a169;font-weight:700}
        .pkg-upgrade-item .pui-comms{font-size:10px;color:#888;margin-top:4px;line-height:1.6}
        .pkg-upgrade-item .pui-dot{width:10px;height:10px;border-radius:50%;display:inline-block;margin-right:4px}
        .current-badge{position:absolute;top:8px;right:8px;background:var(--primary);color:white;font-size:9px;font-weight:700;padding:2px 7px;border-radius:10px}


        /* Upgrade Confirm Modal */
        .upg-modal-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.45);z-index:9999;align-items:flex-end;justify-content:center}
        .upg-modal-bg.show{display:flex;animation:fadeIn 0.2s ease}
        @keyframes fadeIn{from{opacity:0}to{opacity:1}}
        .upg-modal{background:white;border-radius:24px 24px 0 0;padding:24px 20px 36px;width:100%;max-width:480px;animation:slideUp 0.3s cubic-bezier(0.34,1.2,0.64,1)}
        @keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}
        .upg-icon{width:64px;height:64px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;margin:0 auto 14px}
        .upg-title{text-align:center;font-size:20px;font-weight:800;color:#222;margin-bottom:6px}
        .upg-sub{text-align:center;font-size:13px;color:#888;margin-bottom:18px}
        .upg-info{background:#f8fafc;border-radius:14px;padding:14px 16px;margin-bottom:18px}
        .upg-info-row{display:flex;justify-content:space-between;padding:7px 0;border-bottom:1px solid #f0f0f0;font-size:13px}
        .upg-info-row:last-child{border:none}
        .upg-info-row .ul{color:#888}
        .upg-info-row .uv{font-weight:700;color:#222}
        .upg-fee-box{background:#fff5f5;border-radius:12px;padding:12px 16px;margin-bottom:18px;display:flex;align-items:center;justify-content:space-between}
        .upg-fee-free{background:#f0fff4}
        .upg-fee-box .uf-lbl{font-size:13px;color:#666}
        .upg-fee-box .uf-val{font-size:18px;font-weight:800;color:#e53e3e}
        .upg-fee-free .uf-val{color:#38a169}
        .upg-btns{display:grid;grid-template-columns:1fr 1fr;gap:10px}
        .upg-cancel{padding:14px;border:2px solid #e8ecf4;border-radius:14px;background:white;font-size:14px;font-weight:700;cursor:pointer;color:#666}
        .upg-confirm{padding:14px;border:none;border-radius:14px;font-size:14px;font-weight:700;cursor:pointer;color:white}
    </style>
</head>
<body>

<div class="hdr">
    <div class="hdr-in">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <div class="hdr-title">Profile</div>
    </div>
</div>

<div class="content">

    <!-- Profile Card -->
    <div class="profile-card">
        <div class="avatar"><i class="fas fa-user"></i></div>
        <div class="p-name"><?= htmlspecialchars($user['name']) ?></div>
        <div class="p-phone"><?= $user['phone'] ?></div>
        <span class="p-role"><?= ucfirst($user['role']) ?></span>
        <div class="p-bal">
            <div>
                <div class="p-bal-lbl">Balance</div>
                <div class="p-bal-val"><?= CURRENCY ?><?= number_format($user['balance'],2) ?></div>
            </div>
            <div style="text-align:right">
                <div class="p-bal-lbl">Due Balance</div>
                <div style="font-size:16px;font-weight:700"><?= CURRENCY ?><?= number_format($user['due_balance']??0,2) ?></div>
            </div>
        </div>
    </div>

    <!-- Account Info -->
    <div class="section">
        <div class="sec-title"><i class="fas fa-user-circle" style="color:var(--primary)"></i> Account Info</div>
        <div class="info-row"><span class="info-lbl">Name</span><span class="info-val"><?= htmlspecialchars($user['name']) ?></span></div>
        <div class="info-row"><span class="info-lbl">Phone</span><span class="info-val"><?= $user['phone'] ?></span></div>
        <div class="info-row"><span class="info-lbl">Role</span><span class="info-val"><?= ucfirst($user['role']) ?></span></div>
        <div class="info-row"><span class="info-lbl">Member Since</span><span class="info-val"><?= date('d M Y', strtotime($user['created_at'])) ?></span></div>
    </div>

    <!-- Package Section -->
    <div class="section">
        <div class="sec-title"><i class="fas fa-tags" style="color:#805ad5"></i> My Package</div>

        <!-- Current Package Card -->
        <div style="background:linear-gradient(135deg,<?= $userPkg['color'] ?>,<?= $userPkg['color'] ?>99);border-radius:16px;padding:18px;margin-bottom:16px;color:white">
            <div style="font-size:10px;opacity:0.7;font-weight:700;letter-spacing:1px;margin-bottom:6px">CURRENT PACKAGE</div>
            <div style="font-size:22px;font-weight:800;margin-bottom:12px">
                🎯 <?= htmlspecialchars($userPkg['name']) ?>
            </div>
            <?php if(floatval($userPkg['topup_commission']??0)>0 || floatval($userPkg['intl_commission']??0)>0): ?>
            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px">
                <?php
                $comms = [
                    ['📱','Topup',        $userPkg['topup_commission']??0],
                    ['🌍','Intl',         $userPkg['intl_commission']??0],
                    ['🔑','PIN',          $userPkg['pin_commission']??0],
                    ['🎁','Gift',         $userPkg['gift_commission']??0],
                    ['📞','Card',         $userPkg['card_commission']??0],
                    ['⚡','Drive',        $userPkg['drive_commission']??0],
                    ['📦','Manual Drive', $userPkg['manual_drive_commission']??0],
                ];
                foreach($comms as [$icon,$label,$val]): ?>
                <div style="background:rgba(255,255,255,0.18);border-radius:10px;padding:8px;text-align:center">
                    <div style="font-size:16px;font-weight:800"><?= floatval($val) ?>%</div>
                    <div style="font-size:10px;opacity:0.85;margin-top:2px"><?= $icon ?> <?= $label ?></div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div style="background:rgba(255,255,255,0.15);border-radius:10px;padding:10px;text-align:center;font-size:13px;opacity:0.85">
                No commission on Basic package.<br>Upgrade to earn commission!
            </div>
            <?php endif; ?>
        </div>

        <!-- Upgrade Packages -->
        <?php if(count($availPkgs) > 1): ?>
        <div style="font-size:12px;font-weight:700;color:#666;margin-bottom:12px;text-transform:uppercase;letter-spacing:0.5px">
            🔼 Available Packages
        </div>
        <?php foreach($availPkgs as $p):
            $isCurrent = ($p['id'] == ($userPkg['id']??1));
            $fee = floatval($p['upgrade_fee'] ?? 0);
        ?>
        <div style="border:2px solid <?= $isCurrent ? $p['color'] : '#e8ecf4' ?>;border-radius:14px;padding:14px;margin-bottom:10px;background:<?= $isCurrent ? '#f8f5ff' : 'white' ?>;transition:0.2s"
             data-pkg-id="<?= $p['id'] ?>"
             data-pkg-name="<?= htmlspecialchars($p['name'],ENT_QUOTES) ?>"
             data-pkg-fee="<?= $fee ?>"
             data-is-current="<?= $isCurrent?1:0 ?>"
             <?= !$isCurrent ? 'onclick="cardUpgrade(this)"' : '' ?>>
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px">
                <div style="display:flex;align-items:center;gap:8px">
                    <div style="width:12px;height:12px;border-radius:50%;background:<?= $p['color'] ?>"></div>
                    <span style="font-size:15px;font-weight:800;color:#222"><?= htmlspecialchars($p['name']) ?></span>
                    <?php if($isCurrent): ?>
                    <span style="background:<?= $p['color'] ?>;color:white;font-size:10px;font-weight:700;padding:2px 8px;border-radius:10px">✓ Active</span>
                    <?php endif; ?>
                </div>
                <?php if(!$isCurrent): ?>
                <span style="background:<?= $fee>0?'#fff5f5':'#f0fff4' ?>;color:<?= $fee>0?'#c53030':'#276749' ?>;font-size:12px;font-weight:700;padding:4px 10px;border-radius:10px;border:1px solid <?= $fee>0?'#fed7d7':'#c6f6d5' ?>">
                    <?= $fee>0 ? 'Fee: '.CURRENCY.number_format($fee,0) : '🆓 Free' ?>
                </span>
                <?php endif; ?>
            </div>
            <?php if(floatval($p['topup_commission'])>0 || floatval($p['intl_commission'])>0): ?>
            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:6px">
                <?php
                $pComms = [
                    ['📱','Topup',        $p['topup_commission']],
                    ['🌍','Intl',         $p['intl_commission']],
                    ['🔑','PIN',          $p['pin_commission']],
                    ['🎁','Gift',         $p['gift_commission']],
                    ['📞','Card',         $p['card_commission']],
                    ['⚡','Drive',        $p['drive_commission']],
                    ['📦','Manual Drive', $p['manual_drive_commission']??0],
                ];
                foreach($pComms as [$icon,$label,$val]): ?>
                <div style="background:<?= $isCurrent ? $p['color'].'22' : '#f8fafc' ?>;border-radius:8px;padding:6px;text-align:center">
                    <div style="font-size:13px;font-weight:700;color:<?= $isCurrent ? $p['color'] : '#333' ?>"><?= floatval($val) ?>%</div>
                    <div style="font-size:10px;color:#888;margin-top:1px"><?= $icon ?> <?= $label ?></div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div style="font-size:12px;color:#aaa">No commission</div>
            <?php endif; ?>
            <?php if(!$isCurrent): ?>
            <div style="margin-top:10px">
                <button onclick="event.stopPropagation();cardUpgrade(this.closest('[data-pkg-id]'))"
                    style="width:100%;padding:10px;background:<?= $p['color'] ?>;color:white;border:none;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer">
                    <?= $fee>0 ? '🔼 Upgrade for '.CURRENCY.number_format($fee,0) : '🔄 Switch to '.$p['name'] ?>
                </button>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Currency Settings -->
    <div class="section">
        <div class="sec-title"><i class="fas fa-coins" style="color:#f5a623"></i> Currency Preference</div>
        <p style="font-size:12px;color:#888;margin-bottom:12px">
            Your balance will show in BDT + your selected currency on the home screen.
        </p>

        <div class="cur-grid" id="curGrid">
            <?php foreach ($currencies as $c): ?>
            <div class="cur-item <?= $c['code']===$userCurrCode?'active':'' ?>"
                 data-code="<?= $c['code'] ?>"
                 onclick="selectCurrency(this, '<?= $c['code'] ?>')">
                <span class="cur-sym"><?= htmlspecialchars($c['symbol']) ?></span>
                <span class="cur-code"><?= $c['code'] ?></span>
                <span class="cur-name"><?= htmlspecialchars($c['name']) ?></span>
                <span class="cur-rate">1 BDT = <?= number_format($c['rate'],4) ?></span>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="note-box">
            <i class="fas fa-info-circle"></i>
            <span>Currently selected: <strong id="curSelected"><?= $userCurrCode ?></strong> — Your home screen will show balance in both BDT and this currency.</span>
        </div>

        <button class="save-btn" onclick="saveCurrency()">
            <i class="fas fa-save"></i> Save Currency Preference
        </button>
    </div>

    <!-- Telegram Notification -->
    <div class="section">
        <div class="sec-title"><i class="fab fa-telegram" style="color:#229ED9"></i> Telegram Notification</div>
        <div style="background:#f0f8ff;border-radius:12px;padding:14px;margin-bottom:12px;font-size:12px;color:#555;line-height:1.7">
            📲 আপনার Telegram ID দিন। Recharge/Drive success হলে Telegram এ notification পাবেন।<br>
            <b>কীভাবে পাবেন:</b> Telegram এ <a href="https://t.me/userinfobot" target="_blank" style="color:#229ED9">@userinfobot</a> তে message করুন, সে আপনার ID দেবে।
        </div>
        <div style="position:relative;margin-bottom:12px">
            <span style="position:absolute;left:13px;top:50%;transform:translateY(-50%);font-size:18px">📱</span>
            <input type="number" id="tgIdInput" placeholder="Your Telegram ID (e.g. 123456789)"
                value="<?= htmlspecialchars($user['telegram_id']??'') ?>"
                style="width:100%;padding:13px 13px 13px 42px;border:2px solid #e8ecf4;border-radius:12px;font-size:15px;outline:none"
                onfocus="this.style.borderColor='#229ED9'" onblur="this.style.borderColor='#e8ecf4'">
        </div>
        <button onclick="saveTelegram()" style="width:100%;padding:13px;background:linear-gradient(135deg,#229ED9,#1a7fb3);color:white;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">
            <i class="fab fa-telegram"></i> Save Telegram ID
        </button>
        <?php if($user['telegram_id']??''): ?>
        <div style="text-align:center;margin-top:8px;font-size:12px;color:#38a169;font-weight:600">✅ Connected: <?= htmlspecialchars($user['telegram_id']) ?></div>
        <?php endif; ?>
    </div>

    <!-- My Devices -->
    <div class="section">
        <div class="sec-title" style="margin-bottom:14px">
            <i class="fas fa-mobile-alt" style="color:#553c9a"></i> আমার ডিভাইস
            <span style="margin-left:auto;font-size:11px;color:#aaa;font-weight:400"><?= count($myDevices) ?>/<?= $maxDevices ?> used</span>
        </div>
        <?php if(empty($myDevices)): ?>
        <div style="text-align:center;padding:16px;color:#ccc;font-size:13px">কোনো ডিভাইস নেই</div>
        <?php else: foreach($myDevices as $d):
            $isCurrent = ($d['device_token'] === $currentToken);
            $isAndroid = strpos($d['os']??'','Android')!==false;
            $isIOS     = strpos($d['os']??'','iOS')!==false;
            $icon      = $isAndroid ? '📱' : ($isIOS ? '🍎' : '💻');
        ?>
        <div style="display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid #f5f5f5">
            <div style="width:42px;height:42px;border-radius:12px;background:<?= $d['is_blocked']?'#fff5f5':($isCurrent?'#f0f4ff':'#f8fafc') ?>;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0"><?= $icon ?></div>
            <div style="flex:1;min-width:0">
                <div style="font-size:13px;font-weight:700;display:flex;align-items:center;gap:6px">
                    <?= htmlspecialchars($d['device_name']??'Unknown') ?>
                    <?php if($isCurrent): ?><span style="font-size:10px;background:#f0f4ff;color:var(--primary);padding:2px 7px;border-radius:8px;font-weight:700">This Device</span><?php endif; ?>
                    <?php if($d['is_blocked']): ?><span style="font-size:10px;background:#fff5f5;color:#e53e3e;padding:2px 7px;border-radius:8px;font-weight:700">🚫 Blocked</span><?php endif; ?>
                </div>
                <div style="font-size:11px;color:#aaa;margin-top:3px">
                    <?php if($d['city']||$d['country']): ?>📍 <?= htmlspecialchars(trim($d['city'].', '.$d['country'],', ')) ?> · <?php endif; ?>
                    🕐 <?= date('d M, H:i',strtotime($d['last_seen'])) ?>
                </div>
                <div style="font-size:11px;color:#bbb;margin-top:1px">
                    <?= htmlspecialchars($d['browser']??'') ?> · <?= htmlspecialchars($d['os']??'') ?>
                </div>
            </div>
        </div>
        <?php endforeach; endif; ?>
        <div style="margin-top:14px;display:flex;gap:8px">
            <a href="device-reset.php" style="flex:1;padding:11px;background:#fff5f5;color:#e53e3e;border-radius:12px;font-size:13px;font-weight:700;text-decoration:none;text-align:center;display:flex;align-items:center;justify-content:center;gap:6px">
                <i class="fas fa-redo"></i> Device Reset
            </a>
        </div>
        <?php if(count($myDevices) >= $maxDevices): ?>
        <div style="margin-top:8px;background:#fffbeb;border-radius:10px;padding:10px 12px;font-size:12px;color:#744210;text-align:center">
            ⚠️ সর্বোচ্চ ডিভাইস সীমা পূর্ণ। নতুন ডিভাইসে login করতে Device Reset করুন।
        </div>
        <?php endif; ?>
    </div>

    <!-- Quick Links -->
    <div class="section">
        <div class="sec-title"><i class="fas fa-cog" style="color:#805ad5"></i> Settings</div>
        <a href="deposit.php" class="menu-item">
            <div class="menu-ic" style="background:#f0fff4;color:#38a169"><i class="fas fa-plus-circle"></i></div>
            <span class="menu-txt">Add Balance</span>
            <i class="fas fa-chevron-right menu-arrow"></i>
        </a>
        <a href="history.php" class="menu-item">
            <div class="menu-ic" style="background:#e8f0fe;color:var(--primary)"><i class="fas fa-history"></i></div>
            <span class="menu-txt">Transaction History</span>
            <i class="fas fa-chevron-right menu-arrow"></i>
        </a>
        <a href="#" class="menu-item" onclick="openPinSettings();return false">
            <div class="menu-ic" style="background:#faf5ff;color:#805ad5"><i class="fas fa-lock"></i></div>
            <span class="menu-txt">PIN Security</span>
            <i class="fas fa-chevron-right menu-arrow"></i>
        </a>
            <div class="menu-ic" style="background:#fff5f5;color:#e53e3e"><i class="fas fa-sign-out-alt"></i></div>
            <span class="menu-txt">Logout</span>
            <i class="fas fa-chevron-right menu-arrow"></i>
        </a>
    </div>

</div>

<div class="toast" id="toast"></div>

<!-- PIN Settings Modal -->
<div id="pinModal" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.5);align-items:flex-end;justify-content:center">
    <div style="background:white;border-radius:24px 24px 0 0;padding:24px;width:100%;max-width:480px;animation:slideUp 0.3s ease">
        <div style="font-size:16px;font-weight:800;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between">
            🔒 PIN Security
            <button onclick="closePinModal()" style="background:#f5f5f5;border:none;width:30px;height:30px;border-radius:50%;cursor:pointer">✕</button>
        </div>
        <div id="pinModalContent"></div>
    </div>
</div>
<style>
@keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}
.pm-input{width:100%;padding:12px 14px;border:2px solid #e8ecf4;border-radius:12px;font-size:18px;letter-spacing:8px;text-align:center;outline:none;font-family:monospace}
.pm-input:focus{border-color:var(--primary)}
.pm-btn{width:100%;padding:14px;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;margin-top:8px}
.pm-btn-primary{background:var(--primary);color:white}
.pm-btn-danger{background:#fff5f5;color:#e53e3e}
.pm-err{font-size:12px;color:#e53e3e;text-align:center;margin-top:6px;min-height:18px}
</style>

<?php include 'includes/bottom_nav.php'; ?>

<script>
let selectedCur = '<?= $userCurrCode ?>';

function selectCurrency(el, code) {
    document.querySelectorAll('.cur-item').forEach(i => i.classList.remove('active'));
    el.classList.add('active');
    selectedCur = code;
    document.getElementById('curSelected').textContent = code;
}

function cardUpgrade(el) {
    if (!el) return;
    const pkgId   = parseInt(el.dataset.pkgId);
    const pkgName = el.dataset.pkgName;
    const fee     = parseFloat(el.dataset.pkgFee) || 0;
    if (el.dataset.isCurrent === '1') return;
    upgradePkg(pkgId, pkgName, fee);
}
let _upgPkgId = 0;

function upgradePkg(pkgId, pkgName, fee) {
    _upgPkgId = pkgId;
    const color = document.querySelector('[data-pkg-id="'+pkgId+'"]')?.style.getPropertyValue('border-color') || '#1a3c8f';
    document.getElementById('upgIcon').textContent = fee > 0 ? '🔼' : '🔄';
    document.getElementById('upgIcon').style.background = fee > 0 ? '#fff5f5' : '#f0fff4';
    document.getElementById('upgTitle').textContent = fee > 0 ? 'Upgrade to ' + pkgName : 'Switch to ' + pkgName;
    document.getElementById('upgSub').textContent = fee > 0 ? 'Your account will be charged' : 'Free package switch';
    document.getElementById('upgCurPkg').textContent = document.querySelector('[data-is-current="1"] .pui-name-txt')?.textContent || 'Current';
    document.getElementById('upgNewPkg').textContent = pkgName;
    document.getElementById('upgBalance').textContent = '৳' + parseFloat('<?= number_format($user['balance'],2,'.','') ?>').toLocaleString();
    const feeBox = document.getElementById('upgFeeBox');
    feeBox.className = fee > 0 ? 'upg-fee-box' : 'upg-fee-box upg-fee-free';
    document.getElementById('upgFeeVal').textContent = fee > 0 ? '৳' + fee.toLocaleString() : 'FREE';
    const btn = document.getElementById('upgConfirmBtn');
    btn.style.background = fee > 0 ? '#e53e3e' : '#38a169';
    btn.textContent = fee > 0 ? '✅ Confirm & Pay' : '✅ Confirm';
    document.getElementById('upgModal').classList.add('show');
}

function closeUpgModal() {
    document.getElementById('upgModal').classList.remove('show');
}

function doUpgrade() {
    const btn = document.getElementById('upgConfirmBtn');
    btn.disabled = true;
    btn.textContent = '⏳ Processing...';
    fetch('api/upgrade_package.php', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({package_id: _upgPkgId})
    })
    .then(r=>r.json())
    .then(d=>{
        closeUpgModal();
        if(d.success){
            showToast('✅ ' + d.message, true);
            setTimeout(()=>location.reload(), 1500);
        } else {
            showToast('❌ ' + d.message, false);
            btn.disabled = false;
        }
    })
    .catch(()=>{
        closeUpgModal();
        showToast('❌ Connection error!', false);
    });
}

function saveCurrency() {
    fetch('api/update_currency.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({currency: selectedCur})
    })
    .then(r => r.json())
    .then(d => {
        showToast(d.success ? '✅ Currency saved! — ' + selectedCur : '❌ ' + d.message, d.success);
    })
    .catch(() => showToast('❌ Connection error!', false));
}

function showToast(msg, success=true) {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.style.background = success ? '#38a169' : '#e53e3e';
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 3000);
}

function saveTelegram() {
    const tgId = document.getElementById('tgIdInput').value.trim();
    fetch('api/update_telegram.php', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({telegram_id: tgId})
    }).then(r=>r.json()).then(d=>{
        showToast(d.success ? '✅ Telegram ID saved!' : '❌ '+d.message, d.success);
        if(d.success && tgId) {
            // Show connected status
            const el = document.querySelector('[style*="Connected"]');
            if(el) { el.textContent = '✅ Connected: '+tgId; }
        }
    }).catch(()=>showToast('❌ Error!', false));
}
// PIN Settings
function openPinSettings(){
    const modal = document.getElementById('pinModal');
    modal.style.display='flex';
    fetch('pin.php').then(r=>r.json()).then(d=>renderPinModal(d.has_pin));
}
function closePinModal(){
    document.getElementById('pinModal').style.display='none';
}
function renderPinModal(hasPin){
    const c = document.getElementById('pinModalContent');
    if(!hasPin){
        c.innerHTML=`
        <p style="font-size:13px;color:#888;margin-bottom:16px">Set a 4-digit PIN to protect your account.</p>
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;color:#888;text-transform:uppercase;display:block;margin-bottom:6px">New PIN</label>
        <input type="password" class="pm-input" id="pmPin1" maxlength="4" inputmode="numeric" placeholder="••••"></div>
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;color:#888;text-transform:uppercase;display:block;margin-bottom:6px">Confirm PIN</label>
        <input type="password" class="pm-input" id="pmPin2" maxlength="4" inputmode="numeric" placeholder="••••"></div>
        <div class="pm-err" id="pmErr"></div>
        <button class="pm-btn pm-btn-primary" onclick="setPin()"><i class="fas fa-lock"></i> Set PIN</button>`;
    } else {
        c.innerHTML=`
        <p style="font-size:13px;color:#276749;font-weight:700;margin-bottom:16px">✅ PIN is active</p>
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;color:#888;text-transform:uppercase;display:block;margin-bottom:6px">Current PIN</label>
        <input type="password" class="pm-input" id="pmOld" maxlength="4" inputmode="numeric" placeholder="••••"></div>
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;color:#888;text-transform:uppercase;display:block;margin-bottom:6px">New PIN</label>
        <input type="password" class="pm-input" id="pmNew" maxlength="4" inputmode="numeric" placeholder="••••"></div>
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;color:#888;text-transform:uppercase;display:block;margin-bottom:6px">Confirm New PIN</label>
        <input type="password" class="pm-input" id="pmConf" maxlength="4" inputmode="numeric" placeholder="••••"></div>
        <div class="pm-err" id="pmErr"></div>
        <button class="pm-btn pm-btn-primary" onclick="changePin()"><i class="fas fa-key"></i> Change PIN</button>
        <button class="pm-btn pm-btn-danger" onclick="disablePin()"><i class="fas fa-lock-open"></i> Disable PIN</button>`;
    }
}
function setPin(){
    const p1=document.getElementById('pmPin1').value;
    const p2=document.getElementById('pmPin2').value;
    const err=document.getElementById('pmErr');
    if(p1.length!==4){err.textContent='PIN must be 4 digits';return;}
    if(p1!==p2){err.textContent='PINs do not match';return;}
    const fd=new FormData(); fd.append('action','set'); fd.append('pin',p1); fd.append('confirm',p2);
    fetch('pin.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        if(d.ok){ closePinModal(); showToast('✅ PIN set!',true); location.reload(); }
        else err.textContent=d.message;
    });
}
function changePin(){
    const old=document.getElementById('pmOld').value;
    const nw=document.getElementById('pmNew').value;
    const cf=document.getElementById('pmConf').value;
    const err=document.getElementById('pmErr');
    const fd=new FormData(); fd.append('action','change'); fd.append('old',old); fd.append('new',nw); fd.append('confirm',cf);
    fetch('pin.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        if(d.ok){ closePinModal(); showToast('✅ PIN changed!',true); }
        else err.textContent=d.message;
    });
}
function disablePin(){
    if(!confirm('Disable PIN protection?')) return;
    const fd=new FormData(); fd.append('action','disable');
    fetch('pin.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        if(d.ok){ closePinModal(); showToast('PIN disabled.',true); location.reload(); }
    });
}
</script>

<!-- Package Upgrade Modal -->
<div class="upg-modal-bg" id="upgModal" onclick="if(event.target===this)closeUpgModal()">
    <div class="upg-modal">
        <div class="upg-icon" id="upgIcon" style="background:#f0f0f0">🎯</div>
        <div class="upg-title" id="upgTitle">Upgrade Package</div>
        <div class="upg-sub" id="upgSub">Switch to a better package</div>
        <div class="upg-info">
            <div class="upg-info-row"><span class="ul">Current Package</span><span class="uv" id="upgCurPkg">-</span></div>
            <div class="upg-info-row"><span class="ul">New Package</span><span class="uv" id="upgNewPkg">-</span></div>
            <div class="upg-info-row"><span class="ul">Your Balance</span><span class="uv" id="upgBalance">-</span></div>
        </div>
        <div class="upg-fee-box" id="upgFeeBox">
            <span class="uf-lbl">Upgrade Fee</span>
            <span class="uf-val" id="upgFeeVal">৳0</span>
        </div>
        <div class="upg-btns">
            <button class="upg-cancel" onclick="closeUpgModal()">Cancel</button>
            <button class="upg-confirm" id="upgConfirmBtn" onclick="doUpgrade()">Upgrade</button>
        </div>
    </div>
</div>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
