<?php
session_start();
include 'database.php';

if (!isset($_SESSION['username'])) {
    header('Location: ../adminx');
    exit;
}

$data = [];
$searchTerm = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['searchTerm'])) {
    $searchTerm = $_POST['searchTerm'];

    $sql = "SELECT * FROM users WHERE username LIKE ? OR apiKey LIKE ?";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        die('SQL prepare failed: ' . $conn->error);
    }

    $searchWildcard = "%$searchTerm%";
    $stmt->bind_param("ss", $searchWildcard, $searchWildcard);

    if (!$stmt->execute()) {
        die('Execute failed: ' . $stmt->error);
    }

    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Search - Key Management</title>
    <link href="style/search.css" rel="stylesheet">
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link href="dialog/ud-dialog.css" rel="stylesheet">
</head>
<body>
    <div class="search">
        <form method="POST" action="search.php" class="d-flex w-100">
            <i class="closeSearch bi bi-x-lg" onclick="window.location.href = 'dashboard.php'"></i>
            <input placeholder="Search by username or apiKey" class="search__input" type="search" id="searchInput" name="searchTerm" value="<?= htmlspecialchars($searchTerm) ?>">
            <button type="submit" class="btn btn-primary ms-2">Search</button>
        </form>
    </div>

    <div class="user-table-container" id="results">
        <div class="table-responsive d-table">
            <table class="rtable">
                <thead>
                    <tr>
                        <th class='rdh'>ID</th>
                        <th class='rdh'>Username</th>
                        <th class='rdh'>API Key</th>
                        <th class='rdh'>Limit</th>
                        <th class='rdh'>Expire Date</th>
                    </tr>
                </thead>
                <tbody id="resultsContainer">
                    <?php if (empty($data)): ?>
                    <tr><td colspan="5">No results found</td></tr>
                    <?php else : ?>
                    <?php foreach ($data as $index => $user): ?>
                    <?php $lmt = $user['limit'] == 99999999 ? 'UNLIMITED' : $user['limit']; ?>
                    <?php $bal = $user['balance'] == 99999999 ? 'UNLIMITED' : $user['balance']; ?>
                    <tr class='r'
                        data-username="<?= htmlspecialchars($user['username']) ?>"
                        data-apiKey="<?= htmlspecialchars($user['apiKey']) ?>"
                        data-type="<?= htmlspecialchars($user['type']) ?>"
                        data-status="<?= htmlspecialchars($user['status']) ?>"
                        data-createDate="<?= htmlspecialchars($user['createDate']) ?>"
                        data-expiryDate="<?= htmlspecialchars($user['expiryDate']) ?>"
                        data-limit="<?= htmlspecialchars($lmt) ?>"
                        data-balance="<?= htmlspecialchars($bal) ?>"
                        data-used="<?= htmlspecialchars($user['used']) ?>">

                        <td class='rd'><?= $index + 1 ?></td>
                        <td class='rd'><?= htmlspecialchars($user['username']) ?></td>
                        <td class='rd'><?= htmlspecialchars($user['apiKey']) ?></td>
                        <td class='rd'><?= htmlspecialchars($lmt) ?></td>
                        <td class='rd'><?= htmlspecialchars($user['expiryDate']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal-overlay" id="userDetailsModal">
        <div class="modal-content">
            <span class="close-button" id="closeModal">&times;</span>
            <div class="modal-header">
                User Details
            </div>
            <table class='udt'>
                <tbody>
                    <tr>
                        <th class='udh'>Username</th>
                        <td class='ud'><input type="text" id="username" readonly></td>
                        <td class="icon-cell" onclick="editUsername()"><i class="bi bi-pencil-square"></i></td>
                    </tr>
                    <tr>
                        <th class='udh'>API Key</th>
                        <td class='ud'><input type="text" id="apikey" readonly></td>
                        <td class="icon-cell" onclick="key()"><i class="bi bi-key"></i></td>
                    </tr>
                    <tr>
                        <th class="udh">Key type</th>
                        <td class="ud">
                            <select class="type" id="type" name="type" disabled>
                                <option id="type-option"></option>
                            </select>
                        </td>
                        <td class="icon-cell" onclick="editKeyType()"><i class="bi bi-pencil-square"></i></td>
                    </tr>
                    <tr>
                        <th class="udh">Key status</th>
                        <td class="ud">
                            <select class="status" id="status" name="status" disabled>
                                <option id="status-option"></option>
                            </select>
                        </td>
                        <td class="icon-cell" onclick="editKeyStatus()"><i class="bi bi-pencil-square"></i></td>
                    </tr>
                    <tr>
                        <th class='udh'>Create Date</th>
                        <td class='ud'><input type="text" id="credate" readonly></td>
                        <td class="icon-cell" onclick="creDate()"><i class="bi bi-calendar-event"></i></td>
                    </tr>
                    <tr>
                        <th class='udh'>Expire Date</th>
                        <td class='ud'><input type="text" id="expdate" readonly></td>
                        <td class="icon-cell" onclick="editExpDate()"><i class="bi bi-pencil-square"></i></td>
                    </tr>
                    <tr>
                        <th class='udh'>Limit</th>
                        <td class='ud'><input type="text" id="limit" readonly></td>
                        <td class="icon-cell" onclick="editLimit()"><i class="bi bi-pencil-square"></i></td>
                    </tr>
                    <tr>
                        <th class='udh'>Balance</th>
                        <td class='ud'><input type="text" id="balance" readonly></td>
                        <td class="icon-cell" onclick="balance()"><i class="bi bi-currency-dollar"></i></td>
                    </tr>
                    <tr>
                        <th class='udh'>Used</th>
                        <td class='ud'><input type="text" id="used" readonly></td>
                        <td class="icon-cell" onclick="used()"><i class="bi bi-bar-chart"></i></td>
                    </tr>
                </tbody>
            </table>
            <div style="display: flex; justify-content: space-between; margin-top: 15px;">
                <button class="btn-delete" id="dltKeyBtn">DELETE</button>
                <button class="btn-update" id="updtKeyBtn">UPDATE</button>
            </div>
        </div>
    </div>

    <script>
        function balance() {
            swal("Attention!", "You don't need to edit the balance. To increase the balance, simply edit the limit. The balance will update automatically.", "info");
        }


        const modal = document.getElementById('userDetailsModal');
        const closeModal = document.getElementById('closeModal');
        const rows = document.querySelectorAll(".user-table-container .rtable tbody tr");

        const select = document.getElementById('type');
        const select2 = document.getElementById('status');

        rows.forEach(row => {
            row.addEventListener("click", () => {
                document.getElementById('username').value = row.dataset.username;
                document.getElementById('apikey').value = row.dataset.apikey;
                document.getElementById('credate').value = row.dataset.createdate;
                document.getElementById('expdate').value = row.dataset.expirydate;
                document.getElementById('limit').value = row.dataset.limit;
                document.getElementById('balance').value = row.dataset.balance;
                document.getElementById('used').value = row.dataset.used;

                const typeValue = row.dataset.type;
                const statusValue = row.dataset.status;

                select.innerHTML = '';
                select2.innerHTML = '';

                const currentOption = document.createElement('option');
                currentOption.value = typeValue;
                currentOption.textContent = typeValue.toUpperCase();
                currentOption.selected = true;
                select.appendChild(currentOption);

                const currentOption2 = document.createElement('option');
                currentOption2.value = statusValue;
                currentOption2.textContent = statusValue.toUpperCase();
                currentOption2.selected = true;
                select2.appendChild(currentOption2);

                modal.classList.add('active');
            });
        });

        closeModal.addEventListener('click', () => {
            modal.classList.remove('active');
        });
    </script>

    <script src="js/model.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>