<?php
/**
 * actions/user-save.php — POST handler: create or update a user
 * Super admin only. POST 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_once __DIR__ . '/../includes/audit.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(base_url('pages/users.php'));
}

require_role('super_admin');
csrf_verify();

// ── Inputs ────────────────────────────────────────────────────────────────────

$id               = isset($_POST['id']) && ctype_digit($_POST['id']) ? (int)$_POST['id'] : null;
$name             = trim($_POST['name'] ?? '');
$username         = trim($_POST['username'] ?? '');
$email            = trim($_POST['email'] ?? '');
$role             = trim($_POST['role'] ?? '');
$agency_id        = isset($_POST['agency_id']) && ctype_digit($_POST['agency_id']) ? (int)$_POST['agency_id'] : null;
$password         = $_POST['password'] ?? '';
$password_confirm = $_POST['password_confirm'] ?? '';
$active           = isset($_POST['active']) ? 1 : 0;

$allowed_roles = ['super_admin', 'agency_user'];

// ── Validation ────────────────────────────────────────────────────────────────

$errors = [];

if ($name === '') $errors[] = 'Full name is required.';
if ($username === '') $errors[] = 'Username is required.';
if (!preg_match('/^[a-zA-Z0-9._-]+$/', $username)) $errors[] = 'Username may only contain letters, numbers, dots, underscores, and hyphens.';
if ($email === '') $errors[] = 'Email is required.';
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Email is not valid.';
if (!in_array($role, $allowed_roles, true)) $errors[] = 'Invalid role selected.';
if ($role === 'agency_user' && !$agency_id) $errors[] = 'Agency users must be assigned to an agency.';

// Password rules
if (!$id) {
    // Creating: password required
    if ($password === '') $errors[] = 'Password is required for new users.';
    elseif (strlen($password) < 8) $errors[] = 'Password must be at least 8 characters.';
    elseif ($password !== $password_confirm) $errors[] = 'Passwords do not match.';
} else {
    // Editing: password only validated if provided
    if ($password !== '') {
        if (strlen($password) < 8) $errors[] = 'New password must be at least 8 characters.';
        elseif ($password !== $password_confirm) $errors[] = 'Passwords do not match.';
    }
}

// Duplicate username check (exclude self on edit)
if ($username !== '') {
    $dup_sql  = 'SELECT id FROM users WHERE username = ?';
    $dup_args = [$username];
    if ($id) { $dup_sql .= ' AND id != ?'; $dup_args[] = $id; }
    $dup = db()->prepare($dup_sql);
    $dup->execute($dup_args);
    if ($dup->fetch()) $errors[] = 'That username is already taken.';
}

// Duplicate email check
if ($email !== '') {
    $dup_sql  = 'SELECT id FROM users WHERE email = ?';
    $dup_args = [$email];
    if ($id) { $dup_sql .= ' AND id != ?'; $dup_args[] = $id; }
    $dup = db()->prepare($dup_sql);
    $dup->execute($dup_args);
    if ($dup->fetch()) $errors[] = 'That email is already in use.';
}

if ($errors) {
    set_flash('error', implode(' ', $errors));
    redirect_back(base_url('pages/users.php'));
}

// ── Save ──────────────────────────────────────────────────────────────────────

if ($id) {
    // Prevent deactivating yourself
    if ($id === current_user_id()) $active = 1;

    if ($password !== '') {
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $stmt = db()->prepare(
            'UPDATE users SET name=?, email=?, role=?, agency_id=?, active=?, password_hash=? WHERE id=?'
        );
        $stmt->execute([$name, $email, $role, $role === 'super_admin' ? null : $agency_id, $active, $hash, $id]);
    } else {
        $stmt = db()->prepare(
            'UPDATE users SET name=?, email=?, role=?, agency_id=?, active=? WHERE id=?'
        );
        $stmt->execute([$name, $email, $role, $role === 'super_admin' ? null : $agency_id, $active, $id]);
    }
    audit_log('user.update', "Updated user: $name ($username)", $id, 'user');
    set_flash('success', 'User updated successfully.');
} else {
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $stmt = db()->prepare(
        'INSERT INTO users (name, username, email, password_hash, role, agency_id, active, created_at)
         VALUES (?, ?, ?, ?, ?, ?, 1, NOW())'
    );
    $stmt->execute([$name, $username, $email, $hash, $role, $role === 'super_admin' ? null : $agency_id]);
    $new_id = (int) db()->lastInsertId();
    audit_log('user.create', "Created user: $name ($username)", $new_id, 'user');
    set_flash('success', 'User created successfully.');
}

redirect(base_url('pages/users.php'));
