<?php
require_once __DIR__ . '/../../classes/Database.php';
$db = Database::getInstance();

/* ============================================================
   1) AJAX HANDLER (Add / Remove Coins)
   ============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_wallet'])) {

    $user_id = $_POST['user_id'];
    $type    = $_POST['type'];
    $amount  = (float)$_POST['amount'];

    $wallet = $db->fetch("SELECT balance FROM wallets WHERE user_id = ?", [$user_id]);

    if (!$wallet) { echo "WALLET_NOT_FOUND"; exit; }

    $current_balance = $wallet['balance'];

    if ($type === "remove") {
        if ($amount > $current_balance) {
            echo "LOW_BALANCE"; exit;
        }
        $new_balance = $current_balance - $amount;
    } else {
        $new_balance = $current_balance + $amount;
    }

    $db->query("UPDATE wallets SET balance = ?, updated_at = NOW() WHERE user_id = ?", [$new_balance, $user_id]);

    echo "OK";
    exit;
}

/* ============================================================
   2) FETCH ALL USERS
   ============================================================ */
$users = $db->fetchAll("SELECT * FROM users ORDER BY id DESC");
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>

/* Simple Toggle */
.simple-toggle {
    width: 36px; height: 18px; appearance:none;
    background:#c4c4c4; border-radius:20px;
    position:relative; cursor:pointer; transition:0.2s;
}
.simple-toggle:checked { background:#28a745; }
.simple-toggle::before {
    content:""; width:14px; height:14px; background:white;
    position:absolute; top:2px; left:2px; border-radius:50%; transition:0.2s;
}
.simple-toggle:checked::before { transform:translateX(18px); }

/* RESPONSIVE TABLE FIX */
.table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

/* RESPONSIVE ACTION BUTTON STACK */
@media (max-width: 768px) {
    .action-btns {
        display: flex;
        flex-direction: column;
        gap: 6px;
    }
}

/* MODAL */
#coinsModal {
    display:none; position:fixed; inset:0;
    background:rgba(0,0,0,0.6);
    justify-content:center; align-items:center;
    z-index:9999;
}

#coinsModal .modal-box {
    background:#fff; 
    padding:20px; 
    width:90%; 
    max-width:350px; 
    border-radius:8px;
}

#passwordModal {
    display:none; position:fixed; inset:0;
    background:rgba(0,0,0,0.6);
    justify-content:center; align-items:center;
    z-index:9999;
}

#passwordModal .modal-box {
    background:#fff; 
    padding:20px; 
    width:90%; 
    max-width:350px; 
    border-radius:8px;
}

</style>


<div class="container-fluid">

    <h4 class="mb-3">👤 User Management</h4>

    <div class="card shadow-sm">
        <div class="card-body table-responsive">

            <table class="table table-bordered align-middle">
                <thead class="table-light text-center">
                    <tr>
                        <th>ID</th>
                        <th>User</th>
                        <th>Email</th>
                        <th>Balance</th>
                        <th>Active</th>
                        <th>Action</th>
                    </tr>
                </thead>

                <tbody>

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

                    <tr class="text-center">

                        <td><?= $u['id'] ?></td>

                        <td>
                            <?= htmlspecialchars($u['name']) ?><br>
                            
                            <?php if ($u['role'] === 'admin'): ?>
                                <span class="badge bg-warning text-dark mt-1">Admin</span>
                            <?php else: ?>
                                <span class="badge bg-success mt-1">User</span>
                            <?php endif; ?>
                        </td>

                        <td><?= htmlspecialchars($u['email']) ?></td>

                        <td>
                            <?php 
                                $wallet = $db->fetch("SELECT balance FROM wallets WHERE user_id = ?", [$u['id']]);
                                echo $wallet ? $wallet['balance'] : 0;
                            ?>
                        </td>

                        <td>
                            <input type="checkbox"
                                   class="simple-toggle toggle-control"
                                   data-id="<?= $u['id'] ?>"
                                   data-field="is_active"
                                   <?= $u['is_active'] ? "checked" : "" ?>>
                        </td>

                        <td>

                            <div class="action-btns">

                                <button class="btn btn-warning btn-sm"
                                    onclick="openCoinsModal(<?= $u['id'] ?>, '<?= htmlspecialchars($u['name']) ?>')">
                                    Add / Remove
                                </button>

                                <button class="btn btn-info btn-sm"
                                    onclick="openPasswordModal(<?= $u['id'] ?>, '<?= htmlspecialchars($u['name']) ?>')">
                                    Reset Password
                                </button>

                                <a href="dashboard.php?page=users&delete_user=<?= $u['id'] ?>"
                                   onclick="return confirm('Delete this user?')"
                                   class="btn btn-danger btn-sm">
                                   Delete
                                </a>

                            </div>

                        </td>

                    </tr>

                <?php endforeach; ?>

                </tbody>

            </table>

        </div>
    </div>
</div>


<!-- COINS MODAL -->
<div id="coinsModal">
    <div class="modal-box">
        <h5 id="modalTitle" class="text-center mb-3">Wallet Update</h5>

        <form id="coinsForm">

            <input type="hidden" name="user_id" id="modalUserId">

            <label>Transaction Type:</label>
            <select name="type" class="form-control">
                <option value="add">Add Coins</option>
                <option value="remove">Remove Coins</option>
            </select>

            <label class="mt-2">Amount:</label>
            <input type="number" name="amount" class="form-control" required min="1">

            <button class="btn btn-primary w-100 mt-3">Submit</button>

            <button type="button" class="btn btn-secondary w-100 mt-2"
                    onclick="closeCoinsModal()">Cancel</button>
        </form>
    </div>
</div>

<!-- PASSWORD MODAL -->
<div id="passwordModal">
    <div class="modal-box">
        <h5 id="passwordModalTitle" class="text-center mb-3">Reset Password</h5>

        <form id="passwordForm">

            <input type="hidden" name="user_id" id="passwordUserId">

            <label>New Password:</label>
            <input type="password" name="new_password" id="newPasswordInput" class="form-control" required min="6" placeholder="Min 6 characters">

            <label class="mt-2">Confirm Password:</label>
            <input type="password" name="confirm_password" id="confirmPasswordInput" class="form-control" required placeholder="Confirm password">

            <button class="btn btn-primary w-100 mt-3">Update Password</button>

            <button type="button" class="btn btn-secondary w-100 mt-2"
                    onclick="closePasswordModal()">Cancel</button>
        </form>
    </div>
</div>


<script>
// MODAL CONTROLS
function openCoinsModal(id, name) {
    document.getElementById("modalUserId").value = id;
    document.getElementById("modalTitle").innerText = "Wallet Update: " + name;
    document.getElementById("coinsModal").style.display = "flex";
}

function closeCoinsModal() {
    document.getElementById("coinsModal").style.display = "none";
}

function openPasswordModal(id, name) {
    document.getElementById("passwordUserId").value = id;
    document.getElementById("passwordModalTitle").innerText = "Reset Password: " + name;
    document.getElementById("passwordModal").style.display = "flex";
}

function closePasswordModal() {
    document.getElementById("passwordModal").style.display = "none";
}
</script>


<!-- AJAX WALLET UPDATE -->
<script>
document.getElementById("coinsForm").addEventListener("submit", function(e) {
    e.preventDefault();

    let formData = new FormData(this);
    formData.append("ajax_wallet", "1");

    fetch("partials/users.php", {
        method: "POST",
        body: formData
    })
    .then(res => res.text())
    .then(msg => {

        closeCoinsModal();

        setTimeout(() => {

            if (msg === "LOW_BALANCE") {
                Swal.fire({ icon:"error", title:"Low Balance", timer:1400, showConfirmButton:false });
                return;
            }

            if (msg === "WALLET_NOT_FOUND") {
                Swal.fire({ icon:"error", title:"Wallet Not Found", timer:1400, showConfirmButton:false });
                return;
            }

            if (msg === "OK") {
                Swal.fire({ icon:"success", title:"Wallet Updated", timer:1100, showConfirmButton:false });
                setTimeout(() => location.reload(), 1200);
                return;
            }

            Swal.fire({ icon:"error", title:"Unexpected Error", text:msg });

        }, 120);

    });
});
</script>

<!-- AJAX PASSWORD UPDATE -->
<script>
if (document.getElementById("passwordForm")) {
    document.getElementById("passwordForm").addEventListener("submit", function(e) {
        e.preventDefault();

        let newPass = document.getElementById("newPasswordInput").value.trim();
        let confirmPass = document.getElementById("confirmPasswordInput").value.trim();
        let userId = document.getElementById("passwordUserId").value;

        if (!newPass || !confirmPass) {
            Swal.fire({ icon:"warning", title:"All fields required", timer:1400, showConfirmButton:false });
            return;
        }

        if (newPass !== confirmPass) {
            Swal.fire({ icon:"warning", title:"Passwords do not match", timer:1400, showConfirmButton:false });
            return;
        }

        if (newPass.length < 6) {
            Swal.fire({ icon:"warning", title:"Password must be at least 6 characters", timer:1400, showConfirmButton:false });
            return;
        }

        let formData = new FormData();
        formData.append("ajax_password", "1");
        formData.append("user_id", userId);
        formData.append("new_password", newPass);

        fetch("/extract/admin/reset_password.php", {
            method: "POST",
            body: formData
        })
        .then(res => {
            if (!res.ok) throw new Error('HTTP ' + res.status);
            return res.text();
        })
        .then(msg => {
            console.log("Server response:", msg.trim());
            closePasswordModal();

            if (msg.trim() === "OK") {
                Swal.fire({ 
                    icon:"success", 
                    title:"✅ Password Updated!", 
                    text:"User password has been changed successfully",
                    timer:2000, 
                    showConfirmButton:false 
                });
                setTimeout(() => location.reload(), 2100);
            } else if (msg.includes("INVALID")) {
                Swal.fire({ icon:"error", title:"❌ Invalid Password", text:"Password must be at least 6 characters" });
            } else if (msg.includes("USER_NOT_FOUND")) {
                Swal.fire({ icon:"error", title:"❌ User Not Found", text:"This user does not exist" });
            } else if (msg.includes("ERROR")) {
                Swal.fire({ icon:"error", title:"❌ Error", text:msg });
            } else {
                Swal.fire({ icon:"error", title:"❌ Failed", text:"Failed to update password: " + msg });
            }
        })
        .catch(err => {
            console.error("Fetch error:", err);
            Swal.fire({ icon:"error", title:"Network Error", text:err.message });
        });
    });
}
</script>


<!-- ACTIVE TOGGLE AJAX -->
<script>
document.querySelectorAll(".toggle-control").forEach(el => {
    el.addEventListener("change", function () {

        fetch("ajax_update_user.php", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: `id=${this.dataset.id}&field=${this.dataset.field}&value=${this.checked ? 1 : 0}`
        });

    });
});
</script>
