<?php
$message = '';
include_once 'site-parts/functions.php';
enqueue_file('style/admin.css', 'css', 'header');
enqueue_file(
    'script/admin.js',
    'js',
    'footer',
    $option = [
        'async' => true
    ]
);
page_title('Welcome admin');
if (!isAdmin($conn)) {
    header('Location: login.php');
    exit;
}

// Fetch all users for display
$result = mysqli_query($conn, query: "SELECT id, username, email, reg_date, role FROM users");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // DELETE USER
    if (isset($_POST['delete_user'], $_POST['user_id'])) {
        $user_id = (int) $_POST['user_id'];
        mysqli_query($conn, "DELETE FROM users WHERE id = $user_id");
        header('Location: ' . $_SERVER[' PHP_SELF']);
        exit;
    }

    // EDIT USER
    if (isset($_POST['edit_user'], $_POST['user_id'], $_POST['username'], $_POST['email'], $_POST['role'])) {
        $user_id = (int) $_POST['user_id'];
        $username = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['username'])));
        $email = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['email'])));
        $role = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['role'])));

        // Check for duplicate username (excluding current user)
        $sqlUserCheck = "SELECT id FROM users WHERE username = '$username' AND id != $user_id LIMIT 1";
        $resUserCheck = mysqli_query($conn, $sqlUserCheck);

        // Check for duplicate email (excluding current user)
        $sqlEmailCheck = "SELECT id FROM users WHERE email = '$email' AND id != $user_id LIMIT 1";
        $resEmailCheck = mysqli_query($conn, $sqlEmailCheck);

        if (mysqli_num_rows($resUserCheck) > 0) {
            $message = '<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
                        <path fill="#D60000" d="M11 90c-2.815 0-5.63-1.074-7.778-3.222-4.295-4.296-4.295-11.261 0-15.557l68-68c4.297-4.296 11.26-4.296 15.557 0 4.296 4.296 4.296 11.261 0 15.557l-68 68C16.63 88.926 13.815 90 11 90z" />
                        <path fill="#D60000" d="M79 90c-2.815 0-5.63-1.074-7.778-3.222l-68-68c-4.295-4.296-4.295-11.261 0-15.557 4.296-4.296 11.261-4.296 15.557 0l68 68c4.296 4.296 4.296 11.261 0 15.557C84.63 88.926 81.815 90 79 90z" />
                        </svg>' . 'Username already exists';
            echo "<script>
                  document.addEventListener('DOMContentLoaded', function() {
                  messagePopup();
                  });
                  </script>";
        } elseif (mysqli_num_rows($resEmailCheck) > 0) {
            $message = '<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
        <path fill="#D60000" d="M11 90c-2.815 0-5.63-1.074-7.778-3.222-4.295-4.296-4.295-11.261 0-15.557l68-68c4.297-4.296 11.26-4.296 15.557 0 4.296 4.296 4.296 11.261 0 15.557l-68 68C16.63 88.926 13.815 90 11 90z" />
        <path fill="#D60000" d="M79 90c-2.815 0-5.63-1.074-7.778-3.222l-68-68c-4.295-4.296-4.295-11.261 0-15.557 4.296-4.296 11.261-4.296 15.557 0l68 68c4.296 4.296 4.296 11.261 0 15.557C84.63 88.926 81.815 90 79 90z" />
    </svg>' . 'Email already exists';
            echo "<script>
        document.addEventListener('DOMContentLoaded', function() {
            messagePopup();
        });
    </script>";
        } else {
            // No duplicates, perform update
            $updateSQL = "UPDATE users
    SET username = '$username',
    email = '$email',
    role = '$role'
    WHERE id = $user_id";
            mysqli_query($conn, $updateSQL);
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        }

        // Trigger popup if there was an error
        if ($message != '') {
            echo '<script>
        document.addEventListener("DOMContentLoaded", function() {
            messagePopup();
        });
    </script>';
        }
    }
    if (isset($_POST['new_username'], $_POST['new_password'])) {
        $new_name = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['new_name'])));
        $new_username = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['new_username'])));
        $new_email = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['new_email'])));
        $new_role = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['new_role'])));
        $new_password = mysqli_real_escape_string($conn, htmlspecialchars(trim($_POST['new_password'])));

        // Check if username already exists
        $sql_new_user = "SELECT id FROM users WHERE username = '$new_username' LIMIT 1";
        $new_user_check = mysqli_query($conn, $sql_new_user);

        // Check if email already exists
        $sql_new_email = "SELECT id FROM users WHERE email = '$new_email' LIMIT 1";
        $new_email_check = mysqli_query($conn, $sql_new_email);

        if (mysqli_num_rows($new_user_check) > 0) {
            $message = 'Username already exists';
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    messagePopup();
                });
            </script>";
            exit;
        } elseif (mysqli_num_rows($new_email_check) > 0) {
            $message = 'Email already exists';
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    messagePopup();
                });
            </script>";
        } else {
            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $result = "INSERT INTO `users` (`username`, `password`, `email`, `full_name`, `role`) 
                       VALUES ('$new_username','$password_hash','$new_email','$new_name','$new_role')";
            $add_user = mysqli_query($conn, $result);

            if ($add_user) {
                $message = '✅ User registered successfully.';
                echo "<script>
                    document.addEventListener('DOMContentLoaded', function() {
                        messagePopup();
                    });
                </script>";
                header('Location: admin.php');
            }
        }
    }
}
include 'site-parts/head.php';
?>
<h1>Manage Users</h1>
<div class="container">
    <table class="user-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Role</th>
                <th>Registration Date</th>
                <th>Email</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($user = mysqli_fetch_assoc($result)): ?>
                <tr>
                    <form method="POST" onsubmit="return confirm('Are you sure?');">
                        <td>
                            <?php echo htmlspecialchars($user['id']); ?>
                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                        </td>
                        <td><input type="text" name="username" value="<?php echo htmlspecialchars($user['username']); ?>"></td>
                        <td>
                            <select name="role">
                                <option value="admin" <?php echo $user['role'] === 'admin' ? 'selected' : ''; ?>>Admin</option>
                                <option value="user" <?php echo $user['role'] === 'user' ? 'selected' : ''; ?>>User</option>
                            </select>
                        </td>
                        <td><?php echo full_month_date($user['reg_date']); ?></td>
                        <td><input type="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>"></td>
                        <td>
                            <button type="submit" name="edit_user" class="edit">Edit</button>
                    </form>
                    <form method="POST" style="display:inline;" onsubmit="return confirm('Are you sure?');">
                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                        <button type="submit" name="delete_user" class="delete">Delete</button>
                    </form>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>
<div class="new-users-div">
    <button class="btn margin-top10" id="new-user-popup">Create A New User</button>
</div>
<div class="error-popup popup hidden" id="new_user_popup">
    <form method="POST" class="new_user_form">
        <label for="new_name">Full Name</label>
        <input type="text" name="new_name">

        <label for="new_username">Username</label>
        <input type="text" name="new_username">

        <label for="new_email">Email</label>
        <input type="email" name="new_email">

        <label for="new_password">Password</label>
        <input type="password" name="new_password">

        <label for="role">Choose role:</label>
        <select id="role" name="new_role">
            <option value="admin">Admin</option>
            <option value="user" selected>User</option>
        </select>

        <input type="submit" class="btn form-btn">
    </form>
    <button class="btn2" id="close-popup2">Okay</button>
</div>
<div class="error-popup popup hidden">
    <?php echo $message; ?>
    <button class="btn2" id="close-popup">Okay</button>
</div>
<?php include_once 'site-parts/footer.php'; ?>