<?php
require __DIR__ . '/../includes/bootstrap.php';
require_login();
require_admin();

$pdo = db();
$errors = [];

if (is_post()) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid session token.';
    } else {
        $action = $_POST['action'] ?? 'create';

        if ($action === 'create') {
            $payload = [
                'username' => strtolower(trim($_POST['username'] ?? '')),
                'full_name' => trim($_POST['full_name'] ?? ''),
                'email' => trim($_POST['email'] ?? ''),
                'role' => $_POST['role'] ?? 'admin',
                'password' => $_POST['password'] ?? '',
            ];

            if ($payload['username'] === '' || $payload['password'] === '' || $payload['full_name'] === '') {
                $errors[] = 'Username, full name, and password are required.';
            } else {
                $stmt = $pdo->prepare(
                    'INSERT INTO users (username, password, role, full_name, email, status)
                     VALUES (:username, :password, :role, :full_name, :email, 1)'
                );
                $stmt->execute([
                    'username' => $payload['username'],
                    'password' => password_hash($payload['password'], PASSWORD_BCRYPT),
                    'role' => $payload['role'],
                    'full_name' => $payload['full_name'],
                    'email' => $payload['email'],
                ]);
                add_flash('success', 'User account created.');
                redirect('admin/users.php');
            }
        }

        if ($action === 'toggle') {
            $id = (int) ($_POST['id'] ?? 0);
            $stmt = $pdo->prepare('UPDATE users SET status = IF(status = 1, 0, 1) WHERE id = :id');
            $stmt->execute(['id' => $id]);
            add_flash('success', 'User status updated.');
            redirect('admin/users.php');
        }

        if ($action === 'reset_password') {
            $id = (int) ($_POST['id'] ?? 0);
            $newPassword = trim($_POST['new_password'] ?? '');
            if ($newPassword === '') {
                $errors[] = 'New password is required.';
            } else {
                $stmt = $pdo->prepare('UPDATE users SET password = :password WHERE id = :id');
                $stmt->execute([
                    'password' => password_hash($newPassword, PASSWORD_BCRYPT),
                    'id' => $id,
                ]);
                add_flash('success', 'Password updated.');
                redirect('admin/users.php');
            }
        }
    }
}

$users = $pdo->query(
    'SELECT id, username, full_name, email, role, status, created_at
     FROM users ORDER BY created_at DESC'
)->fetchAll();

render_header('Users', ['active' => 'users']);
?>
<div class="card shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0">Users</h5>
            <small class="text-muted"><?= count($users) ?> accounts</small>
        </div>
        <div class="d-flex gap-2 align-items-center">
            <?php if ($errors): ?>
                <span class="text-danger small"><?= sanitize(implode(' ', $errors)) ?></span>
            <?php endif; ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal">
                Create User
            </button>
        </div>
    </div>
    <div class="card-body">
        <?php if (!$users): ?>
            <p class="text-muted text-center mb-0">No users found.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th>User</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th class="text-end">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($users as $user): ?>
                        <?php
                        $statusLabel = $user['status'] ? 'Active' : 'Disabled';
                        $toggleAction = $user['status'] ? 'Disable' : 'Enable';
                        $toggleConfirm = $user['status'] ? 'Disable this user?' : 'Enable this user?';
                        ?>
                        <tr>
                            <td>
                                <strong><?= sanitize($user['full_name']) ?></strong><br>
                                <span class="text-muted-sm"><?= sanitize($user['username']) ?> · <?= sanitize($user['email']) ?></span>
                            </td>
                            <td><?= strtoupper(sanitize($user['role'])) ?></td>
                            <td>
                                <span class="badge <?= $user['status'] ? 'bg-success-subtle text-success' : 'bg-secondary' ?>">
                                    <?= $statusLabel ?>
                                </span>
                            </td>
                            <td><?= format_datetime($user['created_at']) ?></td>
                            <td class="text-end">
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-secondary"
                                            data-bs-toggle="modal"
                                            data-bs-target="#toggleUserModal"
                                            data-id="<?= (int) $user['id'] ?>"
                                            data-record-name="<?= sanitize($user['full_name']) ?>"
                                            data-record-ref="<?= sanitize($user['username']) ?>"
                                            data-confirm-text="<?= sanitize($toggleConfirm) ?>"
                                            data-confirm-label="<?= sanitize($toggleAction) ?>">
                                        <?= $toggleAction ?>
                                    </button>
                                    <button class="btn btn-sm btn-outline-primary"
                                            data-bs-toggle="modal"
                                            data-bs-target="#resetPasswordModal"
                                            data-id="<?= (int) $user['id'] ?>"
                                            data-record-name="<?= sanitize($user['full_name']) ?>"
                                            data-record-ref="<?= sanitize($user['username']) ?>">
                                        Reset Password
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Create user modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-hidden="true"
     data-create-title="Create User" data-edit-title="Create User"
     data-create-submit="Create Account" data-edit-submit="Create Account">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <form method="post" class="needs-validation" novalidate>
                <div class="modal-header">
                    <h5 class="modal-title" data-modal-title>Create User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="create">
                    <input type="hidden" name="id" value="">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Username</label>
                            <input type="text" name="username" class="form-control text-lowercase" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Full Name</label>
                            <input type="text" name="full_name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Role</label>
                            <select name="role" class="form-select">
                                <option value="admin">Admin</option>
                                <option value="staff">Staff</option>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Password</label>
                            <input type="password" name="password" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Account</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Toggle status modal -->
<div class="modal fade" id="toggleUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Update Status</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="id" value="">
                    <p class="mb-1" data-delete-message>Update user status?</p>
                    <p class="fw-semibold mb-0" data-delete-name>User Name</p>
                    <small class="text-muted" data-delete-id data-label="Username">Username: —</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning" data-delete-confirm>Confirm</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reset password modal -->
<div class="modal fade" id="resetPasswordModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" class="needs-validation" novalidate>
                <div class="modal-header">
                    <h5 class="modal-title">Reset Password</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="reset_password">
                    <input type="hidden" name="id" value="">
                    <p class="mb-1">Reset password for:</p>
                    <p class="fw-semibold mb-0" data-delete-name>User Name</p>
                    <small class="text-muted" data-delete-id data-label="Username">Username: —</small>
                    <div class="mt-3">
                        <label class="form-label">New Password</label>
                        <input type="password" name="new_password" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" data-delete-confirm>Update Password</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php
render_footer();
