<?php
declare(strict_types=1);
// api/users.php
// Always emit clean JSON. PHP warnings/notices are logged by PHP instead of
// being mixed into API responses where they would break Flutter jsonDecode().
ini_set('display_errors', '0');
error_reporting(E_ALL);
ob_start();
header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$pathInfo = isset($_SERVER['PATH_INFO'])
    ? explode('/', trim($_SERVER['PATH_INFO'], '/'))
    : [];
$action = $pathInfo[0] ?? '';

$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
if (!is_array($input)) $input = [];

function usersRespond(int $code, $body = null): void {
    // Remove accidental BOM/whitespace/warning output from included files.
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($code);
    if ($body !== null) {
        $json = json_encode(
            $body,
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE
        );
        if ($json === false) {
            http_response_code(500);
            echo '{"detail":"The server could not encode the response as JSON."}';
        } else {
            echo $json;
        }
    }
    exit;
}

// If PHP encounters a fatal error, keep the API contract JSON-only.
register_shutdown_function(static function (): void {
    $error = error_get_last();
    if (!$error) return;
    $fatalTypes = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
    if (!in_array($error['type'] ?? 0, $fatalTypes, true)) return;

    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    if (!headers_sent()) {
        header('Content-Type: application/json; charset=UTF-8');
    }
    http_response_code(500);
    echo json_encode([
        'detail' => 'A fatal server error occurred in the users API.',
    ], JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
});

function safeUserProjection(): string {
    return 'id, full_name, email, phone, nrc, role, gender, country, campus, school, program, permissions, profile_picture, account_status, suspended_at, suspension_reason';
}

try {
    require_once __DIR__ . '/../config/database.php';
    require_once __DIR__ . '/session_auth.php';

    if (!isset($pdo) || !($pdo instanceof PDO)) {
        throw new RuntimeException('Database connection was not initialized.');
    }

    // Attribute user-list and user-management writes to the authenticated caller.
    rvu_audit_context_from_request($pdo);

    // 1. LOGIN
    if ($action === 'login' && $method === 'POST') {
        $email = trim((string)($input['email'] ?? ''));
        $password = (string)($input['password'] ?? '');
        if ($email === '' || $password === '') {
            usersRespond(400, ['detail' => 'Email and password are required.']);
        }

        rvu_ensure_account_status_columns($pdo);
        $stmt = $pdo->prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1');
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        $safePassword = substr($password, 0, 72);
        if (!$user || !password_verify($safePassword, (string)$user['password'])) {
            usersRespond(401, ['detail' => 'Invalid email or password.']);
        }
        if (strtolower((string)($user['account_status'] ?? 'active')) === 'suspended') {
            usersRespond(403, [
                'detail' => 'This account has been suspended. Contact Rockview University administration.',
                'account_status' => 'suspended',
                'reason' => $user['suspension_reason'] ?? null,
            ]);
        }

        $token = rvu_issue_session($pdo, (int)$user['id']);
        rvu_record_auth_audit($pdo, $user, 'login', 'Signed in successfully.');

        usersRespond(200, [
            'message' => 'Login successful',
            'token' => $token,
            'token_type' => 'bearer',
            'id' => $user['id'],
            'user_id' => $user['id'],
            'email' => $user['email'],
            'role' => $user['role'],
            'full_name' => $user['full_name'],
            'fullName' => $user['full_name'],
            'phone' => $user['phone'] ?? null,
            'campus' => $user['campus'] ?? null,
            'permissions' => $user['permissions'] ?? null,
            'profile_picture' => $user['profile_picture'] ?? null,
            'profilePicture' => $user['profile_picture'] ?? null,
            'user' => [
                'id' => $user['id'],
                'fullName' => $user['full_name'],
                'full_name' => $user['full_name'],
                'email' => $user['email'],
                'phone' => $user['phone'] ?? null,
                'role' => $user['role'],
                'campus' => $user['campus'] ?? null,
                'school' => $user['school'] ?? null,
                'program' => $user['program'] ?? null,
                'permissions' => $user['permissions'] ?? null,
                'profilePicture' => $user['profile_picture'] ?? null,
                'profile_picture' => $user['profile_picture'] ?? null,
            ],
        ]);
    }

    // 2. CURRENT SIGNED-IN ACCOUNT
    elseif ($action === 'me' && $method === 'GET') {
        $user = rvu_current_user($pdo);
        if (!$user) {
            usersRespond(401, ['detail' => 'The session is missing, expired, or invalid. Please sign in again.']);
        }
        usersRespond(200, $user);
    }

    // 3. LOGOUT CURRENT SESSION
    elseif ($action === 'logout' && $method === 'POST') {
        $user = rvu_current_user($pdo);
        if ($user) {
            rvu_record_auth_audit($pdo, $user, 'logout', 'Signed out successfully.');
        }
        rvu_revoke_current_session($pdo);
        usersRespond(200, ['message' => 'Logged out successfully.']);
    }

    // 4. SWITCH SESSION
    elseif ($action === 'switch-session' && $method === 'POST') {
        $email = trim((string)($input['email'] ?? ''));
        if ($email === '') usersRespond(400, ['detail' => 'Email is required.']);

        $stmt = $pdo->prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1');
        $stmt->execute([$email]);
        $targetUser = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$targetUser) {
            usersRespond(404, ['detail' => 'No corresponding student/staff account found for this email.']);
        }

        $token = rvu_issue_session($pdo, (int)$targetUser['id']);
        usersRespond(200, [
            'message' => 'Session switched successfully',
            'token' => $token,
            'token_type' => 'bearer',
            'user' => [
                'id' => $targetUser['id'],
                'fullName' => $targetUser['full_name'],
                'full_name' => $targetUser['full_name'],
                'email' => $targetUser['email'],
                'phone' => $targetUser['phone'] ?? null,
                'role' => $targetUser['role'],
                'campus' => $targetUser['campus'] ?? null,
                'school' => $targetUser['school'] ?? null,
                'program' => $targetUser['program'] ?? null,
                'permissions' => $targetUser['permissions'] ?? null,
                'profilePicture' => $targetUser['profile_picture'] ?? null,
                'profile_picture' => $targetUser['profile_picture'] ?? null,
            ],
        ]);
    }

    // 5. CREATE USER
    elseif ($method === 'POST' && $action === '') {
        $email = trim((string)($input['email'] ?? ''));
        $password = (string)($input['password'] ?? '');
        $fullName = trim((string)($input['full_name'] ?? ''));
        $role = trim((string)($input['role'] ?? ''));

        if ($email === '' || $password === '' || $fullName === '' || $role === '') {
            usersRespond(400, ['detail' => 'Full name, email, password, and role are required.']);
        }

        $check = $pdo->prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?)');
        $check->execute([$email]);
        if ($check->fetch()) {
            usersRespond(400, ['detail' => 'Email already registered']);
        }

        $hash = password_hash(substr($password, 0, 72), PASSWORD_BCRYPT);
        $sql = "INSERT INTO users (
                    full_name, email, password, phone, nrc, role, gender, country,
                    campus, school, program, permissions, profile_picture
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $fullName,
            $email,
            $hash,
            $input['phone'] ?? null,
            $input['nrc'] ?? null,
            $role,
            $input['gender'] ?? null,
            $input['country'] ?? null,
            $input['campus'] ?? null,
            $input['school'] ?? null,
            $input['program'] ?? null,
            json_encode($input['permissions'] ?? []),
            $input['profile_picture'] ?? null,
        ]);

        $newId = $stmt->fetchColumn();
        usersRespond(201, ['message' => 'User created successfully', 'id' => $newId]);
    }

    // 6. GET ALL USERS OR BY ID (never expose password hashes)
    elseif ($method === 'GET') {
        $columns = safeUserProjection();

        if (is_numeric($action)) {
            $stmt = $pdo->prepare("SELECT $columns FROM users WHERE id = ?");
            $stmt->execute([(int)$action]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$user) usersRespond(404, ['detail' => 'User not found']);
            usersRespond(200, $user);
        }

        if (isset($_GET['role']) && trim((string)$_GET['role']) !== '') {
            $stmt = $pdo->prepare("SELECT $columns FROM users WHERE role = ? ORDER BY full_name");
            $stmt->execute([trim((string)$_GET['role'])]);
        } else {
            $stmt = $pdo->query("SELECT $columns FROM users ORDER BY full_name");
        }
        usersRespond(200, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    // 7. UPDATE USER
    elseif ($method === 'PUT' && is_numeric($action)) {
        $allowedFields = [
            'full_name', 'email', 'phone', 'nrc', 'role', 'gender', 'country',
            'campus', 'school', 'program', 'permissions', 'profile_picture', 'password',
        ];

        $fields = [];
        $params = [];
        foreach ($input as $key => $value) {
            if (!in_array($key, $allowedFields, true)) continue;

            if ($key === 'password') {
                if (trim((string)$value) === '') continue;
                $value = password_hash(substr((string)$value, 0, 72), PASSWORD_BCRYPT);
            } elseif ($key === 'permissions' && is_array($value)) {
                $value = json_encode($value);
            }

            $fields[] = "$key = ?";
            $params[] = $value;
        }

        if (!$fields) usersRespond(200, ['message' => 'Nothing to update']);

        $params[] = (int)$action;
        $stmt = $pdo->prepare('UPDATE users SET ' . implode(', ', $fields) . ' WHERE id = ?');
        $stmt->execute($params);
        usersRespond(200, ['message' => 'User updated successfully']);
    }

    // 8. DELETE USER
    elseif ($method === 'DELETE' && is_numeric($action)) {
        // Remove sessions first so a deleted account cannot retain a valid token.
        rvu_ensure_session_table($pdo);
        $sessionDelete = $pdo->prepare('DELETE FROM user_sessions WHERE user_id = ?');
        $sessionDelete->execute([(int)$action]);

        $stmt = $pdo->prepare('DELETE FROM users WHERE id = ?');
        $stmt->execute([(int)$action]);
        usersRespond(204);
    }

    usersRespond(404, ['detail' => 'Unknown users API route.']);
} catch (PDOException $e) {
    usersRespond(500, ['detail' => 'Database error: ' . $e->getMessage()]);
} catch (Throwable $e) {
    usersRespond(500, ['detail' => 'Server error: ' . $e->getMessage()]);
}
