<?php
/**
 * GymFuel Titan - Secure Athlete Customer Portal (My Licenses)
 * Accessible at: https://gethire.proportal.php
 * Requires secure Password authentication to access bought license keys and manage devices.
 */

session_start();
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

$pdo = getDatabaseConnection();

$errorMessage = '';
$successMessage = '';
$activeTab = $_GET['tab'] ?? 'login'; // 'login' or 'register'

// Handle Logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    unset($_SESSION['athlete_user_id']);
    unset($_SESSION['athlete_email']);
    unset($_SESSION['athlete_phone']);
    unset($_SESSION['athlete_name']);
    header("Location: portal.php");
    exit();
}

$redirect = trim($_GET['redirect'] ?? ($_POST['redirect'] ?? 'portal.php'));
if ($redirect !== 'buy.php' && $redirect !== 'portal.php') {
    $redirect = 'portal.php';
}

// -------------------------------------------------------------
// 1. ATHLETE LOGIN HANDLER (Email/Phone + Password)
// -------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['athlete_login'])) {
    $identifier = trim($_POST['identifier'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($identifier) || empty($password)) {
        $errorMessage = "Please enter both your Email/Phone and your Account Password.";
    } else {
        // Query user from users table
        $stmt = $pdo->prepare("
            SELECT * FROM users 
            WHERE email = ? OR phone = ? 
            LIMIT 1
        ");
        $stmt->execute([$identifier, $identifier]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password_hash'])) {
            // Password verified!
            $_SESSION['athlete_user_id'] = $user['id'];
            $_SESSION['athlete_email'] = $user['email'];
            $_SESSION['athlete_phone'] = $user['phone'];
            $_SESSION['athlete_name'] = $user['name'];
            header("Location: " . $redirect);
            exit();
        } else {
            $errorMessage = "Invalid credentials. Please check your Email/Phone and Password.";
        }
    }
}

// -------------------------------------------------------------
// 2. ATHLETE REGISTRATION HANDLER
// -------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['athlete_register'])) {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($name) || empty($email) || empty($phone) || empty($password)) {
        $errorMessage = "Please fill in all registration fields.";
        $activeTab = 'register';
    } elseif (strlen($password) < 6) {
        $errorMessage = "Password must be at least 6 characters long.";
        $activeTab = 'register';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errorMessage = "Please provide a valid email address.";
        $activeTab = 'register';
    } else {
        // Check if email exists
        $chk = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $chk->execute([$email]);
        if ($chk->fetch()) {
            $errorMessage = "An account with this email already exists. Please log in instead.";
            $activeTab = 'login';
        } else {
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $ins = $pdo->prepare("INSERT INTO users (name, email, phone, password_hash) VALUES (?, ?, ?, ?)");
            $ins->execute([$name, $email, $phone, $hash]);
            $newUserId = (int)$pdo->lastInsertId();

            $_SESSION['athlete_user_id'] = $newUserId;
            $_SESSION['athlete_email'] = $email;
            $_SESSION['athlete_phone'] = $phone;
            $_SESSION['athlete_name'] = $name;
            header("Location: portal.php?msg=account_created");
            exit();
        }
    }
}

// -------------------------------------------------------------
// 3. SELF-SERVICE DEVICE UNBIND / RESET
// -------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['unbind_license_id'])) {
    $licenseId = (int)$_POST['unbind_license_id'];
    $athleteEmail = $_SESSION['athlete_email'] ?? '';
    $athletePhone = $_SESSION['athlete_phone'] ?? '';

    if (!empty($athleteEmail) || !empty($athletePhone)) {
        // Verify ownership
        $verify = $pdo->prepare("SELECT id, license_key FROM licenses WHERE id = ? AND (customer_email = ? OR customer_phone = ?)");
        $verify->execute([$licenseId, $athleteEmail, $athletePhone]);
        $lic = $verify->fetch(PDO::FETCH_ASSOC);

        if ($lic) {
            $del = $pdo->prepare("DELETE FROM activations WHERE license_id = ?");
            $del->execute([$licenseId]);

            // Log
            $log = $pdo->prepare("INSERT INTO audit_logs (action, license_key, details, ip_address) VALUES ('SELF_DEVICE_RESET', ?, 'Customer unbind via Portal', ?)");
            $log->execute([$lic['license_key'], $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1']);

            $successMessage = "Successfully unbound device for key: " . htmlspecialchars($lic['license_key']) . ". You can now activate your new phone in GymFuel!";
        }
    }
}

$isCustomerLoggedIn = !empty($_SESSION['athlete_user_id']);
$customerLicenses = [];
$customerOrders = [];

if ($isCustomerLoggedIn) {
    $email = $_SESSION['athlete_email'] ?? '___';
    $phone = $_SESSION['athlete_phone'] ?? '___';

    // Fetch Licenses
    $stmtLic = $pdo->prepare("
        SELECT l.*, 
               (SELECT COUNT(*) FROM activations a WHERE a.license_id = l.id) as bound_devices_count
        FROM licenses l
        WHERE l.customer_email = ? OR l.customer_phone = ?
        ORDER BY l.created_at DESC
    ");
    $stmtLic->execute([$email, $phone]);
    $customerLicenses = $stmtLic->fetchAll(PDO::FETCH_ASSOC);

    // Fetch Activations Details for each license
    foreach ($customerLicenses as &$cl) {
        $stmtAct = $pdo->prepare("SELECT device_model, activated_at, last_check_at FROM activations WHERE license_id = ?");
        $stmtAct->execute([$cl['id']]);
        $cl['activations_list'] = $stmtAct->fetchAll(PDO::FETCH_ASSOC);
    }
    unset($cl);

    // Fetch Orders
    $stmtOrd = $pdo->prepare("SELECT * FROM orders WHERE customer_email = ? OR customer_phone = ? ORDER BY created_at DESC");
    $stmtOrd->execute([$email, $phone]);
    $customerOrders = $stmtOrd->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Athlete Portal • My GymFuel Licenses</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --bg-dark: #07090E;
            --card-bg: #0E131F;
            --card-elevated: #151C2C;
            --border: rgba(255, 255, 255, 0.08);
            --primary: #FF5E00;
            --primary-gradient: linear-gradient(135deg, #FF5E00 0%, #FF8533 100%);
            --primary-glow: rgba(255, 94, 0, 0.4);
            --gold: #FFB300;
            --gold-gradient: linear-gradient(135deg, #FFB300 0%, #FFE082 100%);
            --cyan: #00E5FF;
            --green: #00E676;
            --red: #FF3D71;
            --text-primary: #F4F7FB;
            --text-muted: #8A97AC;
        }

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

        body {
            font-family: 'Plus Jakarta Sans', -apple-system, sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-primary);
            min-height: 100vh;
            line-height: 1.5;
            overflow-x: hidden;
            background-image: 
                radial-gradient(circle at 50% 0%, rgba(255, 94, 0, 0.14) 0%, transparent 60%),
                radial-gradient(circle at 90% 80%, rgba(0, 229, 255, 0.06) 0%, transparent 50%);
            background-attachment: fixed;
        }

        .mono { font-family: 'JetBrains Mono', monospace; }

        /* Navigation */
        .navbar {
            background: rgba(14, 19, 31, 0.85);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border);
            padding: 14px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .logo-row {
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            color: inherit;
        }

        .logo-badge {
            background: var(--primary-gradient);
            color: #000;
            font-weight: 900;
            font-size: 15px;
            width: 34px;
            height: 34px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            box-shadow: 0 4px 14px var(--primary-glow);
        }

        .logo-title {
            font-size: 16px;
            font-weight: 900;
            letter-spacing: -0.4px;
        }

        .logo-sub {
            font-size: 10.5px;
            color: var(--cyan);
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.8px;
        }

        .container {
            max-width: 960px;
            margin: 0 auto;
            padding: 32px 18px 80px;
        }

        /* Auth Card */
        .auth-card {
            background: var(--card-bg);
            border: 1px solid rgba(255, 94, 0, 0.35);
            border-radius: 26px;
            padding: clamp(24px, 5vw, 36px);
            max-width: 460px;
            margin: 30px auto 0;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.7);
            text-align: center;
        }

        .auth-tabs {
            display: flex;
            background: var(--bg-dark);
            border-radius: 14px;
            padding: 4px;
            margin-bottom: 22px;
            border: 1px solid var(--border);
        }

        .auth-tab {
            flex: 1;
            padding: 10px;
            text-align: center;
            font-size: 13px;
            font-weight: 700;
            color: var(--text-muted);
            text-decoration: none;
            border-radius: 10px;
            transition: all 0.2s ease;
        }

        .auth-tab.active {
            background: var(--card-elevated);
            color: var(--text-primary);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
        }

        .form-group {
            margin-bottom: 16px;
            text-align: left;
        }

        .form-label {
            display: block;
            font-size: 11.5px;
            font-weight: 800;
            color: var(--text-muted);
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-input {
            width: 100%;
            background: var(--bg-dark);
            border: 1.5px solid var(--border);
            padding: 14px 16px;
            border-radius: 14px;
            color: var(--text-primary);
            font-size: 14.5px;
            font-family: inherit;
            outline: none;
            transition: all 0.2s ease;
        }

        .form-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-glow);
            background: #0B0F19;
        }

        .btn-primary {
            width: 100%;
            background: var(--primary-gradient);
            color: #000;
            font-weight: 900;
            font-size: 15px;
            padding: 15px 20px;
            border-radius: 14px;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            box-shadow: 0 4px 16px var(--primary-glow);
            transition: transform 0.15s ease;
        }

        .btn-primary:hover { transform: translateY(-2px); }

        /* License Card */
        .license-card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 22px;
            padding: clamp(18px, 4vw, 26px);
            margin-bottom: 20px;
            position: relative;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
        }

        .license-card.active-card {
            border-color: rgba(255, 179, 0, 0.4);
        }

        .license-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 16px;
        }

        .key-row {
            background: #090C14;
            border: 1.5px dashed var(--gold);
            border-radius: 14px;
            padding: 14px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 16px;
        }

        .key-text {
            font-size: clamp(16px, 4vw, 21px);
            font-weight: 900;
            color: #FFFFFF;
            letter-spacing: 1.5px;
            word-break: break-all;
        }

        .btn-copy {
            background: var(--gold-gradient);
            color: #000;
            font-weight: 800;
            font-size: 12.5px;
            padding: 9px 16px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            transition: transform 0.15s;
        }

        .btn-copy:hover { transform: scale(1.03); }

        .btn-unbind {
            background: rgba(255, 61, 113, 0.15);
            border: 1px solid var(--red);
            color: #FF708F;
            font-weight: 800;
            font-size: 12px;
            padding: 7px 14px;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-unbind:hover {
            background: var(--red);
            color: #000;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 10px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
        }

        .badge-active { background: rgba(0, 230, 118, 0.15); color: var(--green); border: 1px solid rgba(0, 230, 118, 0.3); }
        .badge-vip { background: rgba(255, 179, 0, 0.15); color: var(--gold); border: 1px solid rgba(255, 179, 0, 0.3); }

        .device-box {
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid var(--border);
            border-radius: 14px;
            padding: 12px 14px;
            font-size: 12px;
            color: var(--text-muted);
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 10px;
            flex-wrap: wrap;
            gap: 8px;
        }

        @media (max-width: 600px) {
            .navbar { padding: 12px 16px; }
            .key-row { flex-direction: column; align-items: stretch; text-align: center; }
            .btn-copy { width: 100%; margin-top: 6px; }
        }
    </style>
</head>
<body>

<!-- NAVBAR -->
<div class="navbar">
    <a href="portal.php" class="logo-row">
        <div class="logo-badge">⚡</div>
        <div>
            <div class="logo-title">GymFuel Titan</div>
            <div class="logo-sub">Secure Athlete Portal</div>
        </div>
    </a>

    <div style="display: flex; align-items: center; gap: 10px;">
        <a href="buy.php" style="color: var(--primary); text-decoration: none; font-weight: 800; font-size: 12.5px;">🛍️ Buy Key</a>
        <?php if ($isCustomerLoggedIn): ?>
            <a href="portal.php?action=logout" style="color: var(--text-muted); text-decoration: none; font-size: 12.5px;">Logout</a>
        <?php endif; ?>
    </div>
</div>

<div class="container">

    <?php if (!$isCustomerLoggedIn): ?>

        <!-- AUTHENTICATION CARD -->
        <div class="auth-card">
            <div style="font-size: 32px; margin-bottom: 8px;">🔒</div>
            <h1 style="font-size: 22px; font-weight: 900; margin-bottom: 4px;">Athlete Account Access</h1>
            <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 20px;">Log in with your password to view your bought license keys & manage devices.</p>

            <div class="auth-tabs">
                <a href="portal.php?tab=login" class="auth-tab <?= $activeTab === 'login' ? 'active' : '' ?>">Login to Account</a>
                <a href="portal.php?tab=register" class="auth-tab <?= $activeTab === 'register' ? 'active' : '' ?>">Create Account</a>
            </div>

            <?php if (!empty($errorMessage)): ?>
                <div style="background: rgba(255, 61, 113, 0.15); border: 1px solid var(--red); color: #FF708F; padding: 12px; border-radius: 12px; font-size: 13px; margin-bottom: 16px; text-align: left;">
                    <?= htmlspecialchars($errorMessage) ?>
                </div>
            <?php endif; ?>

            <?php if ($activeTab === 'login'): ?>
                <!-- LOGIN FORM -->
                <form method="POST">
                    <input type="hidden" name="athlete_login" value="1">

                    <div class="form-group">
                        <label class="form-label">Email or Phone Number</label>
                        <input type="text" name="identifier" class="form-input" placeholder="e.g. athlete@gmail.com" required autofocus>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Account Password</label>
                        <div style="position: relative;">
                            <input type="password" id="login_password" name="password" class="form-input" placeholder="••••••••" required style="padding-right: 44px;">
                            <button type="button" onclick="togglePassVisibility('login_password', this)" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-muted); cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 6px;" title="Show/Hide Password">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                            </button>
                        </div>
                    </div>

                    <button type="submit" class="btn-primary">
                        ⚡ Secure Login & View Keys
                    </button>
                </form>
            <?php else: ?>
                <!-- REGISTER FORM -->
                <form method="POST">
                    <input type="hidden" name="athlete_register" value="1">

                    <div class="form-group">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="name" class="form-input" placeholder="e.g. Vikram Malhotra" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Email Address</label>
                        <input type="email" name="email" class="form-input" placeholder="e.g. athlete@gmail.com" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">WhatsApp / Phone</label>
                        <input type="tel" name="phone" class="form-input" placeholder="e.g. 9876543210" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Create Password (min 6 characters)</label>
                        <div style="position: relative;">
                            <input type="password" id="register_password" name="password" class="form-input" placeholder="••••••••" minlength="6" required style="padding-right: 44px;">
                            <button type="button" onclick="togglePassVisibility('register_password', this)" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-muted); cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 6px;" title="Show/Hide Password">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                            </button>
                        </div>
                    </div>

                    <button type="submit" class="btn-primary">
                        ✨ Create Account
                    </button>
                </form>
            <?php endif; ?>

            <p style="font-size: 12px; color: var(--text-muted); margin-top: 20px;">
                Don't have a license key yet? <a href="buy.php" style="color: var(--primary); font-weight: 700;">Buy Instant Access Here</a>
            </p>
        </div>

    <?php else: ?>

        <!-- LOGGED IN ATHLETE DASHBOARD -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 12px;">
            <div>
                <h1 style="font-size: clamp(20px, 4vw, 26px); font-weight: 900;">Welcome, <?= htmlspecialchars($_SESSION['athlete_name'] ?: 'Athlete') ?>!</h1>
                <p style="font-size: 13px; color: var(--text-muted);">Email: <strong><?= htmlspecialchars($_SESSION['athlete_email']) ?></strong> • Phone: <strong><?= htmlspecialchars($_SESSION['athlete_phone']) ?></strong></p>
            </div>
            <a href="buy.php" class="btn-primary" style="width: auto; padding: 10px 18px; font-size: 13px;">➕ Buy Another Key</a>
        </div>

        <?php if (!empty($successMessage)): ?>
            <div style="background: rgba(0, 230, 118, 0.15); border: 1px solid var(--green); color: var(--green); padding: 14px; border-radius: 14px; font-size: 13px; font-weight: 700; margin-bottom: 20px;">
                ✅ <?= htmlspecialchars($successMessage) ?>
            </div>
        <?php endif; ?>

        <!-- LICENSES LIST -->
        <?php if (empty($customerLicenses)): ?>
            <div class="license-card" style="text-align: center; padding: 40px;">
                <div style="font-size: 36px; margin-bottom: 12px;">🏋️</div>
                <h3 style="font-size: 18px; font-weight: 800; margin-bottom: 6px;">No Licenses Found</h3>
                <p style="color: var(--text-muted); font-size: 13px; margin-bottom: 18px;">You don't have any active license keys linked to this email/phone yet.</p>
                <a href="buy.php" class="btn-primary" style="width: auto; display: inline-flex;">🛍️ Purchase Access Key</a>
            </div>
        <?php else: ?>
            <?php foreach ($customerLicenses as $lic): ?>
                <div class="license-card active-card">
                    <div class="license-header">
                        <div>
                            <span class="badge badge-active">ACTIVE</span>
                            <span class="badge badge-vip" style="margin-left: 6px;"><?= htmlspecialchars($lic['tier']) ?></span>
                        </div>
                        <div style="font-size: 12px; color: var(--text-muted);">
                            Access: <strong><?= !empty($lic['expires_at']) ? 'Expires ' . date('d M Y', strtotime($lic['expires_at'])) : 'Lifetime VIP (Never Expires)' ?></strong>
                        </div>
                    </div>

                    <!-- KEY BOX -->
                    <div class="key-row">
                        <div>
                            <div style="font-size: 10px; font-weight: 800; color: var(--gold); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px;">License Key</div>
                            <div class="key-text mono" id="key_<?= $lic['id'] ?>"><?= htmlspecialchars($lic['license_key']) ?></div>
                        </div>
                        <button class="btn-copy" onclick="copyKey('<?= htmlspecialchars($lic['license_key']) ?>')">📋 Copy Key</button>
                    </div>

                    <!-- BOUND DEVICES & UNBIND -->
                    <div style="margin-top: 16px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                            <span style="font-size: 12px; font-weight: 800; text-transform: uppercase; color: var(--text-muted);">
                                📱 Bound Devices (<?= (int)$lic['bound_devices_count'] ?> / <?= (int)$lic['max_devices'] ?>)
                            </span>

                            <?php if ($lic['bound_devices_count'] > 0): ?>
                                <form method="POST" onsubmit="return confirm('Unbind all devices for this key? You will be able to activate your new phone immediately in GymFuel.')">
                                    <input type="hidden" name="unbind_license_id" value="<?= $lic['id'] ?>">
                                    <button type="submit" class="btn-unbind">🔄 Transfer / Unbind Phone</button>
                                </form>
                            <?php endif; ?>
                        </div>

                        <?php if (empty($lic['activations_list'])): ?>
                            <div class="device-box" style="justify-content: center; color: var(--text-muted);">
                                ℹ️ No device registered yet. Paste this key into the GymFuel app on your phone!
                            </div>
                        <?php else: ?>
                            <?php foreach ($lic['activations_list'] as $act): ?>
                                <div class="device-box">
                                    <div>
                                        <strong style="color: #fff;"><?= htmlspecialchars($act['device_model'] ?: 'Android Phone') ?></strong>
                                        <div style="font-size: 11px;">Activated: <?= date('d M Y', strtotime($act['activated_at'])) ?></div>
                                    </div>
                                    <span style="color: var(--green); font-weight: 700; font-size: 11px;">● Connected</span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

    <?php endif; ?>

</div>

<script>
    function togglePassVisibility(inputId, btn) {
        const inp = document.getElementById(inputId);
        if (inp.type === 'password') {
            inp.type = 'text';
            btn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF5E00" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>';
        } else {
            inp.type = 'password';
            btn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>';
        }
    }

    function copyKey(key) {
        navigator.clipboard.writeText(key).then(() => {
            alert('✅ License Key copied to clipboard:\n\n' + key);
        }).catch(() => {
            prompt('Copy your key:', key);
        });
    }
</script>

</body>
</html>
