<?php
declare(strict_types=1);

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

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

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

$userId = trim((string) ($_GET['id'] ?? ''));
if ($userId === '') {
    http_response_code(404);
    exit('User not specified.');
}

$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',
    'locked' => 'Locked',
];

$errors = [];
$profileSaved = false;
$passwordResetDone = false;

$hasUsernameCol = iscms_column_exists($conn, 'users', 'username');
$hasMustChange = iscms_column_exists($conn, 'users', 'must_change_password');

$stLoad = $conn->prepare(
    'SELECT u.* FROM users u WHERE u.id = ? LIMIT 1'
);
$urow = null;
if ($stLoad) {
    $stLoad->bind_param('s', $userId);
    $stLoad->execute();
    $urow = $stLoad->get_result()->fetch_assoc();
    $stLoad->close();
}

if (!$urow) {
    http_response_code(404);
    exit('User not found.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid security token. Reload and try again.';
    } else {
        $action = (string) ($_POST['form_action'] ?? '');

        if ($action === 'admin_reset_password') {
            $p1 = (string) ($_POST['new_password'] ?? '');
            $p2 = (string) ($_POST['new_password_confirm'] ?? '');
            $mc = !empty($_POST['must_change_password']);
            if (strlen($p1) < 8) {
                $errors[] = 'New password must be at least 8 characters.';
            } elseif (!hash_equals($p1, $p2)) {
                $errors[] = 'Password confirmation does not match.';
            } else {
                $hash = password_hash($p1, PASSWORD_DEFAULT);
                $passwordResetDone = false;
                if ($hasMustChange) {
                    $mcv = $mc ? 1 : 0;
                    $up = $conn->prepare(
                        'UPDATE users SET password_hash = ?, must_change_password = ?,
                         failed_logins = 0, locked_until = NULL, password_changed_at = NOW() WHERE id = ?'
                    );
                    if ($up) {
                        $up->bind_param('sis', $hash, $mcv, $userId);
                        $passwordResetDone = $up->execute();
                        if (!$passwordResetDone) {
                            $errors[] = 'Could not update password: ' . $up->error;
                        }
                        $up->close();
                    }
                } else {
                    $up = $conn->prepare(
                        'UPDATE users SET password_hash = ?, failed_logins = 0, locked_until = NULL WHERE id = ?'
                    );
                    if ($up) {
                        $up->bind_param('ss', $hash, $userId);
                        $passwordResetDone = $up->execute();
                        if (!$passwordResetDone) {
                            $errors[] = 'Could not update password: ' . $up->error;
                        }
                        $up->close();
                    }
                }
                if (!$passwordResetDone) {
                    // errors already set
                } else {
                $ip = iscms_client_ip();
                $ua = substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500);
                $payload = json_encode(['event' => 'ADMIN_PASSWORD_RESET', 'target_user' => $userId], JSON_UNESCAPED_UNICODE);
                $actor = (string) $_SESSION['user_id'];
                $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(), ?, ?, \'ADMIN_PASSWORD_RESET\', \'administration\', \'user\', ?, ?, ?, ?, \'POST\', \'/edit_user.php\')'
                    );
                    if ($log) {
                        $log->bind_param('ssssss', $actor, $sessId, $userId, $payload, $ip, $ua);
                        $log->execute();
                        $log->close();
                    }
                }
                }
            }
        } elseif ($action === 'update_profile') {
            $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'] ?? ''));
            $email_verified = !empty($_POST['email_verified']) ? 1 : 0;

            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 ($hasUsernameCol && $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 ($errors === []) {
                $chk = $conn->prepare('SELECT id FROM users WHERE email = ? AND id != ? LIMIT 1');
                if ($chk) {
                    $chk->bind_param('ss', $email, $userId);
                    $chk->execute();
                    if ($chk->get_result()->num_rows > 0) {
                        $errors[] = 'Another account already uses that email.';
                    }
                    $chk->close();
                }
            }

            if ($errors === [] && $hasUsernameCol && $username !== '') {
                $chk2 = $conn->prepare('SELECT id FROM users WHERE username = ? AND id != ? LIMIT 1');
                if ($chk2) {
                    $chk2->bind_param('ss', $username, $userId);
                    $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;
                $phone_bind = $phone !== '' ? $phone : null;
                $nid_bind = $national_id !== '' ? $national_id : null;
                $des_bind = $designation !== '' ? $designation : null;

                if ($hasUsernameCol) {
                    $user_bind = $username !== '' ? $username : null;
                    $sql = 'UPDATE users SET org_id=?, role_id=?, dept_id=?, employee_number=?, username=?,
                            first_name=?, last_name=?, email=?, phone=?, national_id=?,
                            user_type=?, designation=?, status=?, email_verified=?
                            WHERE id=?';
                    $up = $conn->prepare($sql);
                    if ($up) {
                        $types = str_repeat('s', 13) . 'is';
                        $up->bind_param(
                            $types,
                            $org_bind,
                            $role_id,
                            $dept_bind,
                            $emp_bind,
                            $user_bind,
                            $first_name,
                            $last_name,
                            $email,
                            $phone_bind,
                            $nid_bind,
                            $user_type,
                            $des_bind,
                            $status,
                            $email_verified,
                            $userId
                        );
                        if (!$up->execute()) {
                            $errors[] = 'Could not save: ' . $up->error;
                        } else {
                            $profileSaved = true;
                        }
                        $up->close();
                    }
                } else {
                    $sql = 'UPDATE users SET org_id=?, role_id=?, dept_id=?, employee_number=?,
                            first_name=?, last_name=?, email=?, phone=?, national_id=?,
                            user_type=?, designation=?, status=?, email_verified=?
                            WHERE id=?';
                    $up = $conn->prepare($sql);
                    if ($up) {
                        $types = str_repeat('s', 12) . 'is';
                        $up->bind_param(
                            $types,
                            $org_bind,
                            $role_id,
                            $dept_bind,
                            $emp_bind,
                            $first_name,
                            $last_name,
                            $email,
                            $phone_bind,
                            $nid_bind,
                            $user_type,
                            $des_bind,
                            $status,
                            $email_verified,
                            $userId
                        );
                        if (!$up->execute()) {
                            $errors[] = 'Could not save: ' . $up->error;
                        } else {
                            $profileSaved = true;
                        }
                        $up->close();
                    }
                }

                if ($profileSaved) {
                    $ip = iscms_client_ip();
                    $ua = substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500);
                    $payload = json_encode(['event' => 'USER_UPDATE', 'email' => $email], JSON_UNESCAPED_UNICODE);
                    $actor = (string) $_SESSION['user_id'];
                    $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_UPDATE\', \'administration\', \'user\', ?, ?, ?, ?, \'POST\', \'/edit_user.php\')'
                        );
                        if ($log) {
                            $log->bind_param('ssssss', $actor, $sessId, $userId, $payload, $ip, $ua);
                            $log->execute();
                            $log->close();
                        }
                    }
                }
            }
        }
    }

    if ($errors === [] && ($profileSaved || $passwordResetDone)) {
        $stLoad = $conn->prepare('SELECT u.* FROM users u WHERE u.id = ? LIMIT 1');
        if ($stLoad) {
            $stLoad->bind_param('s', $userId);
            $stLoad->execute();
            $urow = $stLoad->get_result()->fetch_assoc();
            $stLoad->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>Edit user</h1>
        <p>Update profile, role, and organisation linkage, or set a new 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="add_user.php"><i class="ri-user-add-line"></i> Add user</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; ?>

    <?php if ($profileSaved): ?>
    <div class="alert alert-success mb-4" style="font-size:.88rem"><i class="ri-checkbox-circle-line me-1"></i> Profile saved.</div>
    <?php endif; ?>
    <?php if ($passwordResetDone): ?>
    <div class="alert alert-success mb-4" style="font-size:.88rem"><i class="ri-checkbox-circle-line me-1"></i> Password was updated for this user.</div>
    <?php endif; ?>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-user-settings-line"></i> Profile</h2>
        </div>
        <div class="p-3">
            <form method="post" action="edit_user.php?id=<?= iscms_h($userId) ?>" class="row g-3" style="max-width:48rem">
                <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">
                <input type="hidden" name="form_action" value="update_profile">

                <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) ($urow['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) ($urow['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) ($urow['email'] ?? '')) ?>">
                </div>
                <?php if ($hasUsernameCol): ?>
                <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) ($urow['username'] ?? '')) ?>">
                </div>
                <?php endif; ?>
                <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) ($urow['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) ($urow['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) ($urow['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) ($urow['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>
                        <?php foreach ($roles as $ro): ?>
                        <option value="<?= iscms_h($ro['id']) ?>" <?= ((string) ($urow['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) ($urow['user_type'] ?? '') === $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) ($urow['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) ($urow['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">Status</label>
                    <select name="status" class="form-select form-select-sm">
                        <?php foreach ($statuses as $k => $label): ?>
                        <option value="<?= iscms_h($k) ?>" <?= ((string) ($urow['status'] ?? '') === $k) ? 'selected' : '' ?>><?= iscms_h($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-12">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="email_verified" value="1" id="ev"
                            <?= !empty($urow['email_verified']) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="ev">Email verified</label>
                    </div>
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary btn-sm"><i class="ri-save-line me-1"></i>Save profile</button>
                </div>
            </form>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-lock-password-line"></i> Administrator password reset</h2>
        </div>
        <div class="p-3">
            <p class="text-muted small mb-3">Set a new password for this user. They will need the temporary password you communicate out of band.</p>
            <form method="post" action="edit_user.php?id=<?= iscms_h($userId) ?>" class="row g-3" style="max-width:28rem">
                <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">
                <input type="hidden" name="form_action" value="admin_reset_password">
                <div class="col-12">
                    <label class="form-label">New password</label>
                    <input type="password" name="new_password" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
                </div>
                <div class="col-12">
                    <label class="form-label">Confirm password</label>
                    <input type="password" name="new_password_confirm" class="form-control form-control-sm" required minlength="8" autocomplete="new-password">
                </div>
                <?php if ($hasMustChange): ?>
                <div class="col-12">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="must_change_password" value="1" id="mcp" checked>
                        <label class="form-check-label" for="mcp">Require password change on next login</label>
                    </div>
                </div>
                <?php endif; ?>
                <div class="col-12">
                    <button type="submit" class="btn btn-outline-danger btn-sm"><i class="ri-key-2-line me-1"></i>Set password</button>
                </div>
            </form>
        </div>
    </div>
<?php
iscms_render_footer();
