<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

user_module_boot();

if (!is_post()) {
    redirect('app/modules/users/index.php');
}

require_valid_csrf();

$action = (string) ($_POST['action'] ?? '');

if ($action === 'create') {
    remember_old_input($_POST);

    $errors = [];
    $payload = validate_user_payload($_POST, $errors, null);
    validate_password_confirmation($_POST, 'password', 'password_confirmation', $errors);

    if ((string) ($_POST['password'] ?? '') === '') {
        $errors['password'] = 'Password is required.';
    }

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the user form errors.']);
        redirect('app/modules/users/create.php');
    }

    db_query(
        'INSERT INTO users (full_name, email, phone, password_hash, role_id, club_id, status, created_at, updated_at)
         VALUES (:full_name, :email, :phone, :password_hash, :role_id, :club_id, :status, NOW(), NOW())',
        [
            'full_name' => $payload['full_name'],
            'email' => $payload['email'],
            'phone' => $payload['phone'] !== '' ? $payload['phone'] : null,
            'password_hash' => password_hash((string) $_POST['password'], PASSWORD_DEFAULT),
            'role_id' => $payload['role_id'],
            'club_id' => $payload['club_id'],
            'status' => $payload['status'],
        ]
    );

    $newUserId = (int) db()->lastInsertId();
    audit_log('create_user', 'users', $newUserId, null, [
        'full_name' => $payload['full_name'],
        'email' => $payload['email'],
        'role_id' => $payload['role_id'],
        'club_id' => $payload['club_id'],
        'status' => $payload['status'],
    ]);

    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'User account created successfully.']);
    redirect('app/modules/users/view.php?id=' . $newUserId);
}

if ($action === 'update') {
    $userId = (int) ($_POST['id'] ?? 0);
    $existingUser = find_user_or_abort($userId);
    remember_old_input($_POST);

    $errors = [];
    $payload = validate_user_payload($_POST, $errors, $userId);

    $password = (string) ($_POST['password'] ?? '');
    if ($password !== '') {
        validate_password_confirmation($_POST, 'password', 'password_confirmation', $errors);
    }

    if (should_block_last_super_admin_change($existingUser, $payload['role_id'], $payload['status'])) {
        $errors['role_id'] = 'You cannot remove or deactivate the last active Super Admin.';
    }

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the user form errors.']);
        redirect('app/modules/users/edit.php?id=' . $userId);
    }

    $params = [
        'id' => $userId,
        'full_name' => $payload['full_name'],
        'email' => $payload['email'],
        'phone' => $payload['phone'] !== '' ? $payload['phone'] : null,
        'role_id' => $payload['role_id'],
        'club_id' => $payload['club_id'],
        'status' => $payload['status'],
    ];

    $sql = 'UPDATE users
            SET full_name = :full_name,
                email = :email,
                phone = :phone,
                role_id = :role_id,
                club_id = :club_id,
                status = :status,
                updated_at = NOW()';

    if ($password !== '') {
        $sql .= ', password_hash = :password_hash';
        $params['password_hash'] = password_hash($password, PASSWORD_DEFAULT);
    }

    $sql .= ' WHERE id = :id';

    db_query($sql, $params);

    audit_log('update_user', 'users', $userId, [
        'full_name' => $existingUser['full_name'],
        'email' => $existingUser['email'],
        'role_name' => $existingUser['role_name'],
        'club_id' => $existingUser['club_id'],
        'status' => $existingUser['status'],
    ], [
        'full_name' => $payload['full_name'],
        'email' => $payload['email'],
        'role_id' => $payload['role_id'],
        'club_id' => $payload['club_id'],
        'status' => $payload['status'],
        'password_reset' => $password !== '',
    ]);

    clear_old_input();
    unset($_SESSION['permissions'], $_SESSION['_permissions_loaded_for']);
    flash('success', ['type' => 'success', 'message' => $password !== '' ? 'User updated and password reset.' : 'User updated successfully.']);
    redirect('app/modules/users/view.php?id=' . $userId);
}

if ($action === 'delete') {
    $userId = (int) ($_POST['id'] ?? 0);
    $existingUser = find_user_or_abort($userId);

    if (($existingUser['role_name'] ?? '') === 'Super Admin' && active_super_admin_count($userId) === 0) {
        flash('error', ['type' => 'danger', 'message' => 'You cannot delete the last active Super Admin.']);
        redirect('app/modules/users/delete.php?id=' . $userId);
    }

    db_query('DELETE FROM users WHERE id = :id', ['id' => $userId]);
    audit_log('delete_user', 'users', $userId, $existingUser, null);

    flash('success', ['type' => 'success', 'message' => 'User deleted successfully.']);

    if ((int) ($_SESSION['user_id'] ?? 0) === $userId) {
        logout_user();
        flash('success', ['type' => 'success', 'message' => 'Your account was deleted and the session was closed.']);
        redirect('login.php');
    }

    redirect('app/modules/users/index.php');
}

redirect('app/modules/users/index.php');
