<?php

require_once __DIR__ . '/admin_tool_helper.php';

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$message = '';
$error = '';

$editable = [
    'name',
    'email',
    'telegram_chat_id',
    'trading_style',
    'subscription_status',
    'plan',
    'role',
    'is_active'
];

function user_column_exists($column)
{
    try {
        $stmt = db()->prepare("SHOW COLUMNS FROM users LIKE ?");
        $stmt->execute([$column]);
        return (bool)$stmt->fetch();
    } catch (Throwable $e) {
        return false;
    }
}

$availableColumns = [];

foreach ($editable as $column) {
    if (user_column_exists($column)) {
        $availableColumns[] = $column;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        foreach ($_POST['users'] ?? [] as $id => $user) {

            $sets = [];
            $params = [];

            foreach ($availableColumns as $column) {

                $value = $user[$column] ?? '';

                if ($column === 'is_active') {
                    $value = !empty($value) ? 1 : 0;
                }

                $sets[] = "`{$column}` = ?";
                $params[] = $value;
            }

            if ($sets) {

                $params[] = (int)$id;

                db()->prepare("
                    UPDATE users
                    SET " . implode(',', $sets) . "
                    WHERE id = ?
                ")->execute($params);
            }
        }

        $message = 'Users updated successfully.';

    } catch (Throwable $e) {

        $error = $e->getMessage();
    }
}

$users = db()->query("
    SELECT *
    FROM users
    ORDER BY id DESC
")->fetchAll(PDO::FETCH_ASSOC);

$totalUsers = count($users);

$activeUsers = 0;

foreach ($users as $user) {
    if (!isset($user['is_active']) || (int)$user['is_active'] === 1) {
        $activeUsers++;
    }
}

$disabledUsers = $totalUsers - $activeUsers;

admin_layout_header('User Management');

?>

<style>

body{
    overflow-x:hidden !important;
}

.users-wrapper{
    max-width:1380px;
    margin:0 auto;
}

.users-top{
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:20px;
    margin-bottom:24px;
}

.users-title{
    font-size:44px;
    font-weight:900;
    letter-spacing:-0.05em;
    color:#020617;
    line-height:1;
}

.users-subtitle{
    margin-top:10px;
    color:#64748b;
    font-size:15px;
}

.users-stats{
    display:flex;
    gap:14px;
}

.users-stat{
    min-width:110px;
    background:#fff;
    border:1px solid #e2e8f0;
    border-radius:24px;
    padding:16px 20px;
}

.users-stat span{
    display:block;
    font-size:11px;
    text-transform:uppercase;
    letter-spacing:.08em;
    font-weight:900;
    color:#94a3b8;
}

.users-stat strong{
    display:block;
    margin-top:8px;
    font-size:32px;
    font-weight:900;
    color:#020617;
}

.users-toolbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:16px;
    background:#fff;
    border:1px solid #e2e8f0;
    border-radius:28px;
    padding:16px;
    margin-bottom:22px;
}

.search-box{
    width:100%;
    max-width:430px;
    height:54px;
    border:1px solid #cbd5e1;
    border-radius:18px;
    padding:0 18px;
    font-size:15px;
    font-weight:700;
}

.save-btn{
    height:54px;
    border:0;
    border-radius:18px;
    padding:0 28px;
    background:#2563eb;
    color:#fff;
    font-weight:900;
    cursor:pointer;
}

.users-card{
    background:#fff;
    border:1px solid #e2e8f0;
    border-radius:32px;
    overflow:hidden;
    box-shadow:0 12px 30px rgba(15,23,42,.05);
}

.users-head{
    padding:24px 28px;
    border-bottom:1px solid #e2e8f0;
}

.users-head h2{
    margin:0;
    font-size:30px;
    font-weight:900;
    color:#020617;
}

.users-head p{
    margin-top:8px;
    color:#64748b;
    font-size:15px;
}

.table-wrap{
    overflow-x:auto;
}

.users-table{
    width:100%;
    border-collapse:collapse;
    min-width:980px;
}

.users-table thead{
    background:#f8fafc;
}

.users-table th{
    padding:16px;
    text-align:left;
    font-size:11px;
    text-transform:uppercase;
    letter-spacing:.08em;
    color:#64748b;
    font-weight:900;
}

.users-table td{
    padding:18px 16px;
    border-top:1px solid #e2e8f0;
    vertical-align:middle;
}

.user-name{
    font-size:15px;
    font-weight:900;
    color:#020617;
}

.user-email{
    font-size:14px;
    color:#64748b;
    font-weight:700;
}

.status-badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:32px;
    padding:0 14px;
    border-radius:999px;
    font-size:11px;
    text-transform:uppercase;
    font-weight:900;
}

.active-badge{
    background:#dcfce7;
    color:#166534;
}

.disabled-badge{
    background:#fee2e2;
    color:#991b1b;
}

.view-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    height:42px;
    padding:0 18px;
    border-radius:14px;
    border:1px solid #cbd5e1;
    background:#fff;
    color:#020617;
    font-weight:800;
    cursor:pointer;
    transition:.2s;
}

.view-btn:hover{
    background:#020617;
    color:#fff;
    border-color:#020617;
}

.popup{
    position:fixed;
    inset:0;
    background:rgba(15,23,42,.65);
    display:none;
    align-items:center;
    justify-content:center;
    padding:20px;
    z-index:9999;
}

.popup.show{
    display:flex;
}

.popup-card{
    width:100%;
    max-width:520px;
    background:#fff;
    border-radius:28px;
    overflow:hidden;
    box-shadow:0 30px 80px rgba(15,23,42,.35);
}

.popup-head{
    padding:22px 24px;
    border-bottom:1px solid #e2e8f0;
    background:linear-gradient(135deg, rgba(37,99,235,.06), rgba(15,23,42,.02));
}

.popup-head-flex{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:12px;
}

.popup-head h3{
    margin:0;
    font-size:28px;
    font-weight:900;
    color:#020617;
}

.popup-head p{
    margin-top:6px;
    font-size:13px;
    color:#64748b;
    font-weight:700;
}

.close-popup{
    width:42px;
    height:42px;
    border-radius:14px;
    border:0;
    background:#e2e8f0;
    font-size:18px;
    font-weight:900;
    cursor:pointer;
}

.popup-body{
    padding:22px 24px;
}

.popup-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:14px;
}

.popup-field label{
    display:block;
    margin-bottom:7px;
    font-size:11px;
    font-weight:900;
    text-transform:uppercase;
    letter-spacing:.08em;
    color:#64748b;
}

.popup-field input,
.popup-field select{
    width:100%;
    height:48px;
    border:1px solid #cbd5e1;
    border-radius:14px;
    padding:0 14px;
    font-size:14px;
    font-weight:700;
}

.popup-wide{
    grid-column:1 / -1;
}

.account-box{
    margin-top:18px;
    padding:18px;
    border-radius:22px;
    background:#f8fafc;
    border:1px solid #e2e8f0;
}

.account-flex{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:16px;
}

.account-flex h4{
    margin:0;
    font-size:18px;
    font-weight:900;
    color:#020617;
}

.account-flex p{
    margin-top:5px;
    font-size:13px;
    color:#64748b;
}

.switch{
    position:relative;
    width:60px;
    height:34px;
}

.switch input{
    opacity:0;
    width:0;
    height:0;
}

.slider{
    position:absolute;
    inset:0;
    border-radius:999px;
    background:#ef4444;
    transition:.2s;
}

.slider:before{
    content:"";
    position:absolute;
    width:26px;
    height:26px;
    left:4px;
    top:4px;
    background:#fff;
    border-radius:50%;
    transition:.2s;
}

.switch input:checked + .slider{
    background:#16a34a;
}

.switch input:checked + .slider:before{
    transform:translateX(26px);
}

.popup-actions{
    margin-top:20px;
    display:flex;
    gap:12px;
}

.popup-actions button{
    flex:1;
    height:50px;
    border-radius:16px;
    border:0;
    font-weight:900;
    cursor:pointer;
}

.cancel-btn{
    background:#e2e8f0;
    color:#020617;
}

.update-btn{
    background:#2563eb;
    color:#fff;
}

@media(max-width:900px){

    .users-top,
    .users-toolbar{
        flex-direction:column;
        align-items:stretch;
    }

    .popup-grid{
        grid-template-columns:1fr;
    }

    .popup-wide{
        grid-column:auto;
    }
}

</style>

<div class="users-wrapper">

    <div class="users-top">

        <div>

            <div class="users-title">
                User Management
            </div>

            <div class="users-subtitle">
                Manage subscriptions, plans, Telegram IDs and institutional access.
            </div>

        </div>

        <div class="users-stats">

            <div class="users-stat">
                <span>Total</span>
                <strong><?= e($totalUsers) ?></strong>
            </div>

            <div class="users-stat">
                <span>Active</span>
                <strong><?= e($activeUsers) ?></strong>
            </div>

            <div class="users-stat">
                <span>Disabled</span>
                <strong><?= e($disabledUsers) ?></strong>
            </div>

        </div>

    </div>

    <?php if ($message): ?>
        <div style="margin-bottom:18px;padding:14px 18px;border-radius:16px;background:#ecfdf5;border:1px solid #a7f3d0;color:#047857;font-weight:800;">
            <?= e($message) ?>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div style="margin-bottom:18px;padding:14px 18px;border-radius:16px;background:#fef2f2;border:1px solid #fecaca;color:#b91c1c;font-weight:800;">
            <?= e($error) ?>
        </div>
    <?php endif; ?>

    <form method="post">

        <div class="users-toolbar">

            <input
                type="search"
                id="searchUsers"
                class="search-box"
                placeholder="Search users..."
            >

            <button class="save-btn">
                Save All Changes
            </button>

        </div>

        <div class="users-card">

            <div class="users-head">

                <h2>Registered Users</h2>

                <p>
                    Click “Manage” to edit access, subscription and account permissions.
                </p>

            </div>

            <div class="table-wrap">

                <table class="users-table" id="usersTable">

                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Trading Style</th>
                            <th>Plan</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>

                        <?php foreach ($users as $user): ?>

                            <?php
                                $active = !isset($user['is_active']) || (int)$user['is_active'] === 1;
                                $json = htmlspecialchars(json_encode($user), ENT_QUOTES, 'UTF-8');
                            ?>

                            <tr
                                class="user-row"
                                data-search="<?= e(strtolower(($user['name'] ?? '') . ' ' . ($user['email'] ?? '') . ' ' . ($user['role'] ?? '') . ' ' . ($user['plan'] ?? ''))) ?>"
                            >

                                <td>
                                    <div class="user-name">
                                        <?= e($user['name'] ?? '') ?>
                                    </div>
                                </td>

                                <td>
                                    <div class="user-email">
                                        <?= e($user['email'] ?? '') ?>
                                    </div>
                                </td>

                                <td>
                                    <?= e(ucfirst($user['trading_style'] ?? '-')) ?>
                                </td>

                                <td>
                                    <?= e(ucfirst($user['plan'] ?? '-')) ?>
                                </td>

                                <td>
                                    <?= e(ucfirst($user['role'] ?? '-')) ?>
                                </td>

                                <td>
                                    <div class="status-badge <?= $active ? 'active-badge' : 'disabled-badge' ?>">
                                        <?= $active ? 'Active' : 'Disabled' ?>
                                    </div>
                                </td>

                                <td>

                                    <button
                                        type="button"
                                        class="view-btn open-user"
                                        data-user="<?= $json ?>"
                                    >
                                        ⚙ Manage
                                    </button>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    </tbody>

                </table>

            </div>

        </div>

        <div class="popup" id="popup">

            <div class="popup-card">

                <div class="popup-head">

                    <div class="popup-head-flex">

                        <div>

                            <h3>User Details</h3>

                            <p>
                                Edit user access, subscription and permissions.
                            </p>

                        </div>

                        <button
                            type="button"
                            class="close-popup"
                            id="closePopup"
                        >
                            ×
                        </button>

                    </div>

                </div>

                <div class="popup-body" id="popupBody"></div>

            </div>

        </div>

    </form>

</div>

<script>

const popup = document.getElementById('popup');
const popupBody = document.getElementById('popupBody');

document.querySelectorAll('.open-user').forEach(button => {

    button.addEventListener('click', function(){

        const user = JSON.parse(this.dataset.user);

        const activeChecked =
            parseInt(user.is_active || 0) === 1
            ? 'checked'
            : '';

        popupBody.innerHTML = `
            <div class="popup-grid">

                <div class="popup-field">
                    <label>Name</label>
                    <input
                        name="users[${user.id}][name]"
                        value="${user.name || ''}"
                    >
                </div>

                <div class="popup-field">
                    <label>Email</label>
                    <input
                        name="users[${user.id}][email]"
                        value="${user.email || ''}"
                    >
                </div>

                <div class="popup-field popup-wide">
                    <label>Telegram Chat ID</label>
                    <input
                        name="users[${user.id}][telegram_chat_id]"
                        value="${user.telegram_chat_id || ''}"
                    >
                </div>

                <div class="popup-field">
                    <label>Trading Style</label>

                    <select name="users[${user.id}][trading_style]">
                        <option value="scalping">Scalping</option>
                        <option value="intraday">Intraday</option>
                        <option value="swing">Swing</option>
                        <option value="auto">Auto</option>
                    </select>
                </div>

                <div class="popup-field">
                    <label>Subscription</label>

                    <select name="users[${user.id}][subscription_status]">
                        <option value="active">Active</option>
                        <option value="trial">Trial</option>
                        <option value="expired">Expired</option>
                        <option value="suspended">Suspended</option>
                    </select>
                </div>

                <div class="popup-field">
                    <label>Plan</label>

                    <select name="users[${user.id}][plan]">
                        <option value="free">Free</option>
                        <option value="basic">Basic</option>
                        <option value="pro">Pro</option>
                        <option value="premium">Premium</option>
                        <option value="institutional">Institutional</option>
                    </select>
                </div>

                <div class="popup-field">
                    <label>Role</label>

                    <select name="users[${user.id}][role]">
                        <option value="user">User</option>
                        <option value="moderator">Moderator</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>

            </div>

            <div class="account-box">

                <div class="account-flex">

                    <div>

                        <h4>Account Access</h4>

                        <p>
                            Disable this user from accessing the platform.
                        </p>

                    </div>

                    <label class="switch">

                        <input
                            type="checkbox"
                            name="users[${user.id}][is_active]"
                            value="1"
                            ${activeChecked}
                        >

                        <span class="slider"></span>

                    </label>

                </div>

            </div>

            <div class="popup-actions">

                <button
                    type="button"
                    class="cancel-btn"
                    id="cancelPopup"
                >
                    Close
                </button>

                <button class="update-btn">
                    Save User
                </button>

            </div>
        `;

        popup.classList.add('show');

        setTimeout(() => {

            popupBody.querySelector('[name="users[' + user.id + '][trading_style]"]').value =
                user.trading_style || 'intraday';

            popupBody.querySelector('[name="users[' + user.id + '][subscription_status]"]').value =
                user.subscription_status || 'active';

            popupBody.querySelector('[name="users[' + user.id + '][plan]"]').value =
                user.plan || 'free';

            popupBody.querySelector('[name="users[' + user.id + '][role]"]').value =
                user.role || 'user';

        }, 20);

        document.getElementById('cancelPopup').onclick = function(){
            popup.classList.remove('show');
        };

    });

});

document.getElementById('closePopup').addEventListener('click', function(){
    popup.classList.remove('show');
});

popup.addEventListener('click', function(e){

    if(e.target === popup){
        popup.classList.remove('show');
    }
});

document.getElementById('searchUsers').addEventListener('input', function(){

    const value = this.value.toLowerCase();

    document.querySelectorAll('.user-row').forEach(row => {

        row.style.display =
            row.dataset.search.includes(value)
            ? ''
            : 'none';
    });

});

</script>

<?php admin_layout_footer(); ?>
