<?php
require_once __DIR__ . '/../../app/includes/auth.php';
require_auth(); require_admin(); verify_csrf();

$id = (int)($_GET['id'] ?? 0);
$stmt = db()->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$target = $stmt->fetch();
if (!$target) { flash('error', 'User not found.'); redirect('/users/index.php'); }

$action = (string)post('action');
if ($action === 'update_user') {
    $name = trim((string)post('name'));
    $email = strtolower(trim((string)post('email')));
    $role = (string)post('role');
    $status = (string)post('status');
    if ($name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL) || !allowed_role($role) || !allowed_user_status($status)) {
        flash('error', 'Please provide valid user details.');
        redirect('/users/edit.php?id=' . $id);
    }
    if ($id === (int)current_user()['id'] && $status === 'inactive') {
        flash('error', 'You cannot deactivate your own account.');
        redirect('/users/edit.php?id=' . $id);
    }
    if ($target['role'] === 'admin' && $role !== 'admin') {
        $count = (int)db()->query("SELECT COUNT(*) FROM users WHERE role='admin' AND status='active'")->fetchColumn();
        if ($count <= 1) {
            flash('error', 'You cannot remove the last active admin.');
            redirect('/users/edit.php?id=' . $id);
        }
    }
    $stmt = db()->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1');
    $stmt->execute([$email, $id]);
    if ($stmt->fetch()) {
        flash('error', 'Email address already exists.');
        redirect('/users/edit.php?id=' . $id);
    }
    $stmt = db()->prepare('UPDATE users SET name=?, email=?, role=?, status=?, updated_at=? WHERE id=?');
    $stmt->execute([$name, $email, $role, $status, now(), $id]);
    log_activity('user.updated', 'Updated user ' . $email);
    if ($id === (int)current_user()['id']) {
        refresh_current_user();
    }
    flash('success', 'User updated successfully.');
    redirect('/users/index.php');
}

if ($action === 'reset_password') {
    $password = (string)post('password');
    $confirm = (string)post('confirm_password');
    if ($password !== $confirm) {
        flash('error', 'Password confirmation must match.');
        redirect('/users/edit.php?id=' . $id);
    }
    if ($errors = validate_strong_password($password)) {
        flash('error', implode(' ', $errors));
        redirect('/users/edit.php?id=' . $id);
    }
    $stmt = db()->prepare('UPDATE users SET password_hash=?, must_change_password=1, updated_at=? WHERE id=?');
    $stmt->execute([password_hash($password, PASSWORD_DEFAULT), now(), $id]);
    log_activity('user.password_reset', 'Reset password for user ' . $target['email']);
    flash('success', 'User password reset successfully.');
    redirect('/users/edit.php?id=' . $id);
}

flash('error', 'Unknown user management action.');
redirect('/users/index.php');
