<?php
/**
 * pages/user-form.php — Add / Edit user (super_admin only)
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';

require_role('super_admin');

$is_edit = isset($_GET['id']) && ctype_digit($_GET['id']);
$u       = [];

if ($is_edit) {
    $stmt = db()->prepare('SELECT id, name, email, username, role, agency_id, active FROM users WHERE id = ?');
    $stmt->execute([(int)$_GET['id']]);
    $u = $stmt->fetch();
    if (!$u) {
        set_flash('error', 'User not found.');
        redirect(base_url('pages/users.php'));
    }
}

// Load agencies for dropdown
$agencies = db()->query('SELECT id, name FROM agencies WHERE active = 1 ORDER BY name')->fetchAll();

$page_title  = $is_edit ? 'Edit User' : 'Add User';
$active_page = 'users';
require_once __DIR__ . '/../templates/head.php';
?>

<?php require_once __DIR__ . '/../templates/header.php'; ?>
<?php require_once __DIR__ . '/../templates/sidebar.php'; ?>

<div class="nxl-everything">
    <div class="nxl-container">
        <div class="main-content" style="padding-top: 80px;">

            <nav aria-label="breadcrumb" class="mb-3">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?= base_url('pages/users.php') ?>">Users</a></li>
                    <li class="breadcrumb-item active"><?= $is_edit ? 'Edit' : 'Add' ?></li>
                </ol>
            </nav>

            <div class="page-header mb-4">
                <h4 class="fw-bold mb-0"><?= $is_edit ? 'Edit User' : 'Add New User' ?></h4>
            </div>

            <?php render_flash(); ?>

            <div class="card border-0 shadow-sm" style="max-width:720px;">
                <div class="card-body p-4">
                    <form method="POST" action="<?= base_url('actions/user-save.php') ?>" novalidate>
                        <?= csrf_field() ?>
                        <?php if ($is_edit): ?>
                        <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                        <?php endif; ?>

                        <div class="row g-3 mb-3">
                            <!-- Full Name -->
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Full Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control"
                                       value="<?= e($u['name'] ?? '') ?>"
                                       placeholder="Jane Doe" required maxlength="200">
                            </div>
                            <!-- Username -->
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Username <span class="text-danger">*</span></label>
                                <input type="text" name="username" class="form-control"
                                       value="<?= e($u['username'] ?? '') ?>"
                                       placeholder="jane.doe" required maxlength="80"
                                       pattern="[a-zA-Z0-9._-]+"
                                       title="Letters, numbers, dots, underscores and hyphens only">
                            </div>
                        </div>

                        <!-- Email -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Email Address <span class="text-danger">*</span></label>
                            <input type="email" name="email" class="form-control"
                                   value="<?= e($u['email'] ?? '') ?>"
                                   placeholder="jane@agency.org" required maxlength="200">
                        </div>

                        <div class="row g-3 mb-3">
                            <!-- Role -->
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Role <span class="text-danger">*</span></label>
                                <select name="role" id="roleSelect" class="form-control" required>
                                    <option value="">— Select role —</option>
                                    <option value="super_admin" <?= ($u['role'] ?? '') === 'super_admin' ? 'selected' : '' ?>>Super Admin</option>
                                    <option value="agency_user" <?= ($u['role'] ?? '') === 'agency_user' ? 'selected' : '' ?>>Agency User</option>
                                </select>
                            </div>
                            <!-- Agency (shown for agency_user) -->
                            <div class="col-md-6" id="agencyField">
                                <label class="form-label fw-semibold">Agency</label>
                                <select name="agency_id" class="form-control">
                                    <option value="">— No agency —</option>
                                    <?php foreach ($agencies as $ag): ?>
                                    <option value="<?= $ag['id'] ?>"
                                        <?= ($u['agency_id'] ?? null) == $ag['id'] ? 'selected' : '' ?>>
                                        <?= e($ag['name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-text">Required for Agency User role.</div>
                            </div>
                        </div>

                        <!-- Password -->
                        <div class="row g-3 mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">
                                    Password <?= !$is_edit ? '<span class="text-danger">*</span>' : '' ?>
                                </label>
                                <input type="password" name="password" class="form-control"
                                       placeholder="<?= $is_edit ? 'Leave blank to keep current' : 'Min. 8 characters' ?>"
                                       <?= !$is_edit ? 'required' : '' ?>
                                       minlength="8" autocomplete="new-password">
                                <?php if ($is_edit): ?>
                                <div class="form-text">Leave blank to keep the current password.</div>
                                <?php endif; ?>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Confirm Password</label>
                                <input type="password" name="password_confirm" class="form-control"
                                       placeholder="Repeat password" autocomplete="new-password">
                            </div>
                        </div>

                        <!-- Active toggle (edit only) -->
                        <?php if ($is_edit): ?>
                        <div class="mb-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="activeSwitch"
                                       name="active" value="1"
                                       <?= ($u['active'] ?? 1) ? 'checked' : '' ?>
                                       <?= ($u['id'] ?? 0) === current_user_id() ? 'disabled' : '' ?>>
                                <label class="form-check-label fw-semibold" for="activeSwitch">Account is Active</label>
                            </div>
                            <?php if (($u['id'] ?? 0) === current_user_id()): ?>
                            <div class="form-text text-warning">You cannot deactivate your own account.</div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <?= $is_edit ? 'Save Changes' : 'Create User' ?>
                            </button>
                            <a href="<?= base_url('pages/users.php') ?>" class="btn btn-outline-secondary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
<script>
// Show/hide agency field based on role selection
(function () {
    var roleSelect  = document.getElementById('roleSelect');
    var agencyField = document.getElementById('agencyField');

    function toggleAgency() {
        agencyField.style.display = roleSelect.value === 'agency_user' ? '' : 'none';
    }

    roleSelect.addEventListener('change', toggleAgency);
    toggleAgency(); // run on load
}());
</script>
