<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();
iscms_require_roles(['SUPER_ADMIN', 'ADMIN']);

$pageTitle = 'Add user';
$activeNav = 'users';

$errors = [];

$userTypes = [
    'staff' => 'Staff',
    'client' => 'Client',
    'inspector' => 'Inspector',
    'lab_officer' => 'Lab officer',
    'certifier' => 'Certifier',
    'admin' => 'Admin',
    'super_admin' => 'Super admin',
];

$statuses = [
    'pending_verification' => 'Pending verification',
    'active' => 'Active',
    'inactive' => 'Inactive',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid security token. Reload the page and try again.';
    } else {
        $first_name = trim((string) ($_POST['first_name'] ?? ''));
        $last_name = trim((string) ($_POST['last_name'] ?? ''));
        $email = trim((string) ($_POST['email'] ?? ''));
        $username = trim((string) ($_POST['username'] ?? ''));
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $national_id = trim((string) ($_POST['national_id'] ?? ''));
        $employee_number = trim((string) ($_POST['employee_number'] ?? ''));
        $designation = trim((string) ($_POST['designation'] ?? ''));
        $role_id = trim((string) ($_POST['role_id'] ?? ''));
        $org_id = trim((string) ($_POST['org_id'] ?? ''));
        $dept_id = trim((string) ($_POST['dept_id'] ?? ''));
        $user_type = trim((string) ($_POST['user_type'] ?? ''));
        $status = trim((string) ($_POST['status'] ?? 'pending_verification'));
        $password = (string) ($_POST['password'] ?? '');
        $password2 = (string) ($_POST['password_confirm'] ?? '');
        $email_verified = !empty($_POST['email_verified']);
        $must_change_password = !empty($_POST['must_change_password']);

        if ($first_name === '' || mb_strlen($first_name) > 100) {
            $errors[] = 'First name is required (max 100 characters).';
        }
        if ($last_name === '' || mb_strlen($last_name) > 100) {
            $errors[] = 'Last name is required (max 100 characters).';
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'A valid email address is required.';
        }
        if ($username !== '' && !preg_match('/^[a-zA-Z0-9._-]{1,100}$/', $username)) {
            $errors[] = 'Username may only contain letters, digits, dot, underscore, hyphen.';
        }
        if ($role_id === '') {
            $errors[] = 'Select a role.';
        }
        if (!isset($userTypes[$user_type])) {
            $errors[] = 'Select a valid user type.';
        }
        if (!isset($statuses[$status])) {
            $errors[] = 'Select a valid account status.';
        }
        if (strlen($password) < 8) {
            $errors[] = 'Password must be at least 8 characters.';
        }
        if (!hash_equals($password, $password2)) {
            $errors[] = 'Password confirmation does not match.';
        }

        if ($errors === []) {
            $chk = $conn->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
            if ($chk) {
                $chk->bind_param('s', $email);
                $chk->execute();
                if ($chk->get_result()->num_rows > 0) {
                    $errors[] = 'That email is already registered.';
                }
                $chk->close();
            }
        }

        if ($errors === [] && $username !== '') {
            $chk2 = $conn->prepare('SELECT id FROM users WHERE username = ? LIMIT 1');
            if ($chk2) {
                $chk2->bind_param('s', $username);
                $chk2->execute();
                if ($chk2->get_result()->num_rows > 0) {
                    $errors[] = 'That username is already taken.';
                }
                $chk2->close();
            }
        }

        if ($errors === []) {
            $org_bind = $org_id !== '' ? $org_id : null;
            $dept_bind = $dept_id !== '' ? $dept_id : null;
            $emp_bind = $employee_number !== '' ? $employee_number : null;
            $user_bind = $username !== '' ? $username : null;
            $phone_bind = $phone !== '' ? $phone : null;
            $nid_bind = $national_id !== '' ? $national_id : null;
            $des_bind = $designation !== '' ? $designation : null;

            $hash = password_hash($password, PASSWORD_DEFAULT);
            $created_by = (string) $_SESSION['user_id'];
            $ev = $email_verified ? 1 : 0;
            $mc = $must_change_password ? 1 : 0;

            $sql = 'INSERT INTO users (
                org_id, role_id, dept_id, employee_number, username,
                first_name, last_name, email, password_hash, phone, national_id,
                user_type, designation, status, email_verified,
                must_change_password, created_by
            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                $errors[] = 'Database error: ' . $conn->error;
            } else {
                $paramTypes = str_repeat('s', 14) . 'iis';
                $stmt->bind_param(
                    $paramTypes,
                    $org_bind,
                    $role_id,
                    $dept_bind,
                    $emp_bind,
                    $user_bind,
                    $first_name,
                    $last_name,
                    $email,
                    $hash,
                    $phone_bind,
                    $nid_bind,
                    $user_type,
                    $des_bind,
                    $status,
                    $ev,
                    $mc,
                    $created_by
                );

                if (!$stmt->execute()) {
                    $errors[] = 'Could not save user: ' . $stmt->error;
                } else {
                    $gid = $conn->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
                    $newUserId = '';
                    if ($gid) {
                        $gid->bind_param('s', $email);
                        $gid->execute();
                        $row = $gid->get_result()->fetch_assoc();
                        $newUserId = (string) ($row['id'] ?? '');
                        $gid->close();
                    }

                    $ip = iscms_client_ip();
                    $ua = substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500);
                    $payload = json_encode([
                        'email' => $email,
                        'role_id' => $role_id,
                        'user_type' => $user_type,
                        'status' => $status,
                    ], JSON_UNESCAPED_UNICODE);

                    $sessId = (string) ($_SESSION['session_db_id'] ?? '');
                    if ($sessId !== '') {
                        $log = $conn->prepare(
                            'INSERT INTO audit_logs
                               (id, user_id, session_id, action, module, entity_type, entity_id, new_values, ip_address, user_agent, request_method, request_path)
                             VALUES (UUID(), ?, ?, \'USER_CREATE\', \'administration\', \'user\', ?, ?, ?, ?, \'POST\', \'/add_user.php\')'
                        );
                        if ($log) {
                            $log->bind_param(
                                'ssssss',
                                $created_by,
                                $sessId,
                                $newUserId,
                                $payload,
                                $ip,
                                $ua
                            );
                            $log->execute();
                            $log->close();
                        }
                    } else {
                        $log = $conn->prepare(
                            'INSERT INTO audit_logs
                               (id, user_id, action, module, entity_type, entity_id, new_values, ip_address, user_agent, request_method, request_path)
                             VALUES (UUID(), ?, \'USER_CREATE\', \'administration\', \'user\', ?, ?, ?, ?, \'POST\', \'/add_user.php\')'
                        );
                        if ($log) {
                            $log->bind_param(
                                'sssss',
                                $created_by,
                                $newUserId,
                                $payload,
                                $ip,
                                $ua
                            );
                            $log->execute();
                            $log->close();
                        }
                    }

                    $stmt->close();
                    header('Location: list_users.php?created=1');
                    exit;
                }
                $stmt->close();
            }
        }
    }
}

$roles = [];
$rres = $conn->query("SELECT id, role_name, role_code FROM roles WHERE is_active = 1 ORDER BY role_name ASC");
if ($rres) {
    $roles = $rres->fetch_all(MYSQLI_ASSOC);
}

$orgs = [];
$ores = $conn->query("SELECT id, org_name FROM organizations ORDER BY org_name ASC LIMIT 500");
if ($ores) {
    $orgs = $ores->fetch_all(MYSQLI_ASSOC);
}

$depts = [];
$dres = $conn->query("SELECT id, dept_name FROM departments ORDER BY dept_name ASC LIMIT 300");
if ($dres) {
    $depts = $dres->fetch_all(MYSQLI_ASSOC);
}

$csrf = iscms_csrf_token();

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Add user</h1>
        <p>Create an account with role, optional organisation, and a secure initial password.</p>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Navigation</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="list_users.php"><i class="ri-team-line"></i> User directory</a>
            <a class="qa-btn" href="user_roles.php"><i class="ri-shield-user-line"></i> Roles</a>
        </div>
    </div>

    <?php if ($errors !== []): ?>
    <div class="alert alert-danger mb-4" style="font-size:.88rem">
        <ul class="mb-0 ps-3"><?php foreach ($errors as $e): ?><li><?= iscms_h($e) ?></li><?php endforeach; ?></ul>
    </div>
    <?php endif; ?>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-user-add-line"></i> New account</h2>
        </div>
        <div class="p-3">
            <form method="post" action="add_user.php" class="row g-3" style="max-width:48rem" autocomplete="off">
                <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">

                <div class="col-md-6">
                    <label class="form-label">First name <span class="text-danger">*</span></label>
                    <input type="text" name="first_name" class="form-control form-control-sm" required maxlength="100"
                           value="<?= iscms_h((string) ($_POST['first_name'] ?? '')) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Last name <span class="text-danger">*</span></label>
                    <input type="text" name="last_name" class="form-control form-control-sm" required maxlength="100"
                           value="<?= iscms_h((string) ($_POST['last_name'] ?? '')) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Email <span class="text-danger">*</span></label>
                    <input type="email" name="email" class="form-control form-control-sm" required maxlength="255"
                           value="<?= iscms_h((string) ($_POST['email'] ?? '')) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Username</label>
                    <input type="text" name="username" class="form-control form-control-sm" maxlength="100"
                           value="<?= iscms_h((string) ($_POST['username'] ?? '')) ?>"
                           placeholder="Optional; login can use email instead">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Phone</label>
                    <input type="text" name="phone" class="form-control form-control-sm" maxlength="30"
                           value="<?= iscms_h((string) ($_POST['phone'] ?? '')) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">National ID</label>
                    <input type="text" name="national_id" class="form-control form-control-sm" maxlength="50"
                           value="<?= iscms_h((string) ($_POST['national_id'] ?? '')) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Employee number</label>
                    <input type="text" name="employee_number" class="form-control form-control-sm" maxlength="50"
                           value="<?= iscms_h((string) ($_POST['employee_number'] ?? '')) ?>">
                </div>
                <div class="col-12">
                    <label class="form-label">Designation</label>
                    <input type="text" name="designation" class="form-control form-control-sm" maxlength="150"
                           value="<?= iscms_h((string) ($_POST['designation'] ?? '')) ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Role <span class="text-danger">*</span></label>
                    <select name="role_id" class="form-select form-select-sm" required>
                        <option value="">Select role</option>
                        <?php foreach ($roles as $ro): ?>
                        <option value="<?= iscms_h($ro['id']) ?>" <?= ((string) ($_POST['role_id'] ?? '') === (string) $ro['id']) ? 'selected' : '' ?>>
                            <?= iscms_h($ro['role_name']) ?> (<?= iscms_h($ro['role_code']) ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">User type <span class="text-danger">*</span></label>
                    <select name="user_type" class="form-select form-select-sm" required>
                        <?php foreach ($userTypes as $k => $label): ?>
                        <option value="<?= iscms_h($k) ?>" <?= ((string) ($_POST['user_type'] ?? 'staff') === $k) ? 'selected' : '' ?>><?= iscms_h($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Organisation</label>
                    <select name="org_id" class="form-select form-select-sm">
                        <option value="">None</option>
                        <?php foreach ($orgs as $o): ?>
                        <option value="<?= iscms_h($o['id']) ?>" <?= ((string) ($_POST['org_id'] ?? '') === (string) $o['id']) ? 'selected' : '' ?>><?= iscms_h($o['org_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Department</label>
                    <select name="dept_id" class="form-select form-select-sm">
                        <option value="">None</option>
                        <?php foreach ($depts as $d): ?>
                        <option value="<?= iscms_h($d['id']) ?>" <?= ((string) ($_POST['dept_id'] ?? '') === (string) $d['id']) ? 'selected' : '' ?>><?= iscms_h($d['dept_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Initial status</label>
                    <select name="status" class="form-select form-select-sm">
                        <?php foreach ($statuses as $k => $label): ?>
                        <option value="<?= iscms_h($k) ?>" <?= ((string) ($_POST['status'] ?? 'pending_verification') === $k) ? 'selected' : '' ?>><?= iscms_h($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Password <span class="text-danger">*</span></label>
                    <input type="password" name="password" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Confirm password <span class="text-danger">*</span></label>
                    <input type="password" name="password_confirm" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
                </div>

                <div class="col-12">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="email_verified" value="1" id="ev" <?= !empty($_POST['email_verified']) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="ev">Mark email as verified</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="must_change_password" value="1" id="mc" <?= isset($_POST['must_change_password']) ? (!empty($_POST['must_change_password']) ? 'checked' : '') : 'checked' ?>>
                        <label class="form-check-label" for="mc">Require password change on first login</label>
                    </div>
                </div>

                <div class="col-12">
                    <button type="submit" class="btn btn-primary btn-sm"><i class="ri-save-line me-1"></i>Create user</button>
                </div>
            </form>
        </div>
    </div>
<?php
iscms_render_footer();
