<?php

require_once __DIR__ . "/db.php";

/**
 * =========================================
 * DEMOBANK USER STATUS HELPER
 * =========================================
 * Handles account state validation across system
 */

/**
 * Get user status from database
 */
function getUserStatus($user_id) {
    $conn = db();

    $stmt = $conn->prepare("SELECT status FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();

    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    return $user['status'] ?? null;
}

/**
 * Check if user account is ACTIVE
 */
function isUserActive($user_id) {
    return getUserStatus($user_id) === 'active';
}

/**
 * Check if user is suspended
 */
function isUserSuspended($user_id) {
    return getUserStatus($user_id) === 'suspended';
}

/**
 * Check if user is deactivated
 */
function isUserDeactivated($user_id) {
    return getUserStatus($user_id) === 'deactivated';
}

/**
 * Check if user is deleted (soft delete)
 */
function isUserDeleted($user_id) {
    return getUserStatus($user_id) === 'deleted';
}

/**
 * BLOCK ACCESS IF USER IS NOT ACTIVE
 */
function require_active_user($user_id) {

    $status = getUserStatus($user_id);

    if (!$status) {
        header("Location: /auth/login.php?error=nouser");
        exit;
    }

    if ($status === 'suspended') {
        header("Location: /auth/login.php?error=suspended");
        exit;
    }

    if ($status === 'deactivated') {
        header("Location: /auth/login.php?error=deactivated");
        exit;
    }

    if ($status === 'deleted') {
        header("Location: /auth/login.php?error=deleted");
        exit;
    }

    if ($status !== 'active') {
        header("Location: /auth/login.php?error=inactive");
        exit;
    }

    return true;
}

/**
 * ADMIN ACTION: UPDATE USER STATUS
 */
function updateUserStatus($user_id, $status) {
    $conn = db();

    $allowed = ['active', 'suspended', 'deactivated', 'deleted'];

    if (!in_array($status, $allowed)) {
        return false;
    }

    $stmt = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $user_id);

    return $stmt->execute();
}

/**
 * ACTIVATE USER
 */
function activateUser($user_id) {
    return updateUserStatus($user_id, 'active');
}

/**
 * SUSPEND USER
 */
function suspendUser($user_id) {
    return updateUserStatus($user_id, 'suspended');
}

/**
 * DEACTIVATE USER
 */
function deactivateUser($user_id) {
    return updateUserStatus($user_id, 'deactivated');
}

/**
 * SOFT DELETE USER
 */
function deleteUser($user_id) {
    return updateUserStatus($user_id, 'deleted');
}