<?php
require_once '../../config.php';
require_once '../../functions.php';

check_admin_auth();

$message = '';
$error = '';
$users = [];

// Handle Create User logic... (Keep existing logic)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_user'])) {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $balance = $_POST['balance'] ?? 0.00;

    if ($username && $password) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            $error = "Username already exists";
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
            if ($stmt->execute([$username, $hash])) {
                $message = "User created successfully";
            } else {
                $error = "Failed to create user";
            }
        }
    } else {
        $error = "Username and Password required";
    }
}

// Handle Edit User Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_user'])) {
    $id = $_POST['user_id'];
    $balance = $_POST['balance'] ?? 0;
    $status = $_POST['status'];
    $password = $_POST['password'];

    // Update Query
    $sql = "UPDATE users SET status = ?";
    $params = [$status];

    if (!empty($password)) {
        $sql .= ", password = ?";
        $params[] = password_hash($password, PASSWORD_DEFAULT);
    }

    $sql .= " WHERE id = ?";
    $params[] = $id;

    $stmt = $pdo->prepare($sql);
    if ($stmt->execute($params)) {
        $message = "User updated successfully";
    } else {
        $error = "Failed to update user";
    }
}

try {
    $stmt = $pdo->query("SELECT * FROM users ORDER BY created_at DESC");
    if ($stmt)
        $users = $stmt->fetchAll();
} catch (PDOException $e) {
}

$pageTitle = "Users - SMS Admin";
include '../includes/header.php';
?>

<?php include '../includes/sidebar.php'; ?>

<div id="layoutSidenav_content" class="content-wrapper">
    <main>
        <?php include '../includes/navbar.php'; ?>

        <div class="page-header">
            <h1 class="page-title">User Management</h1>
            <div>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0)">Home</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Users</li>
                </ol>
            </div>
        </div>

        <div class="container-xl px-4 mt-4">
            <?php if (!empty($message)): ?>
                <div class="alert alert-success alert-icon" role="alert">
                    <div class="alert-icon-aside"><i class="fe fe-check-circle"></i></div>
                    <div class="alert-icon-content"><?php echo htmlspecialchars($message); ?></div>
                </div>
            <?php endif; ?>
            <?php if (!empty($error)): ?>
                <div class="alert alert-danger alert-icon" role="alert">
                    <div class="alert-icon-aside"><i class="fe fe-alert-triangle"></i></div>
                    <div class="alert-icon-content"><?php echo htmlspecialchars($error); ?></div>
                </div>
            <?php endif; ?>

            <div class="row">
                <div class="col-xl-4">
                    <!-- Create User Card-->
                    <div class="card mb-4">
                        <div class="card-header">Create New User</div>
                        <div class="card-body">
                            <form method="POST">
                                <div class="mb-3">
                                    <label class="small mb-1">Username</label>
                                    <input type="text" name="username" class="form-control" required>
                                </div>
                                <div class="mb-3">
                                    <label class="small mb-1">Password</label>
                                    <input type="text" name="password" class="form-control" required>
                                </div>

                                <button type="submit" name="create_user" class="btn btn-primary w-100">Add User</button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-xl-8">
                    <!-- User List Card-->
                    <div class="card mb-4">
                        <div class="card-header">Registered Users</div>
                        <div class="card-body">
                            <table class="table table-striped table-hover" id="responsive-datatable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Username</th>
                                        <th>Status</th>
                                        <th>Created At</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (count($users) > 0): ?>
                                        <?php foreach ($users as $u): ?>
                                            <tr>
                                                <td><?php echo $u['id']; ?></td>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <div class="avatar me-2"><img class="avatar-img img-fluid"
                                                                src="https://ui-avatars.com/api/?name=<?php echo $u['username']; ?>&size=32"
                                                                alt /></div>
                                                        <?php echo htmlspecialchars($u['username']); ?>
                                                    </div>
                                                </td>
                                                <td><span
                                                        class="badge bg-<?php echo $u['status'] == 'active' ? 'green-soft text-green' : 'red-soft text-red'; ?>"><?php echo $u['status']; ?></span>
                                                </td>
                                                <td><?php echo $u['created_at']; ?></td>
                                                <td>
                                                    <button class="btn btn-primary btn-sm edit-user-btn"
                                                        data-id="<?php echo $u['id']; ?>"
                                                        data-username="<?php echo htmlspecialchars($u['username']); ?>"
                                                        data-status="<?php echo $u['status']; ?>">
                                                        <i class="fe fe-edit"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="5" class="text-center">No users found.</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit User</h5>
                <button class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="POST" id="editUserForm">
                    <input type="hidden" name="user_id" id="edit_user_id">
                    <input type="hidden" name="edit_user" value="1">

                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" class="form-control" id="edit_username" readonly>
                    </div>



                    <div class="mb-3">
                        <label class="form-label">New Password (Optional)</label>
                        <input type="text" name="password" class="form-control"
                            placeholder="Leave blank to keep current">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control" id="edit_status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary w-100">Update User</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
    <!-- DATA TABLE JS-->
    <script src="/assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
    <script src="/assets/plugins/datatable/js/dataTables.bootstrap5.js"></script>
    <script src="/assets/plugins/datatable/js/dataTables.buttons.min.js"></script>
    <script src="/assets/plugins/datatable/js/buttons.bootstrap5.min.js"></script>
    <script src="/assets/plugins/datatable/js/jszip.min.js"></script>
    <script src="/assets/plugins/datatable/pdfmake/pdfmake.min.js"></script>
    <script src="/assets/plugins/datatable/pdfmake/vfs_fonts.js"></script>
    <script src="/assets/plugins/datatable/js/buttons.html5.min.js"></script>
    <script src="/assets/plugins/datatable/js/buttons.print.min.js"></script>
    <script src="/assets/plugins/datatable/js/buttons.colVis.min.js"></script>
    <script src="/assets/plugins/datatable/dataTables.responsive.min.js"></script>
    <script src="/assets/plugins/datatable/responsive.bootstrap5.min.js"></script>
    <script src="/assets/js/table-data.js"></script>
    <script>
        $(document).ready(function() {
            // Handle Edit Click (Event Delegation for DataTables)
            $(document).on("click", ".edit-user-btn", function() {
                var id = $(this).data("id");
                var username = $(this).data("username");
                var balance = $(this).data("balance");
                var status = $(this).data("status");

                $("#edit_user_id").val(id);
                $("#edit_username").val(username);
                $("#edit_status").val(status);

                $("#editUserModal").modal("show");
            });
        });
    </script>
';
include '../includes/footer.php';
?>