<?php
require_once 'config.php';
require_once 'Database.php';
include '../helper_functions/data_request.php';

if (!headers_sent()) {
    header('Content-Type: application/json');
}

class Profile {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    private function getUserFromToken() {
        $headers = getallheaders();
        $auth = isset($headers['Authorization']) ? $headers['Authorization'] : '';
    
        if (!preg_match('/Bearer\s+(.+)/', $auth, $matches)) {
            return null;
        }
    
        $sessionId = $matches[1];
    
        $sql = "
            SELECT user_id, user_type
            FROM mobile_sessions 
            WHERE session_id = :session_id 
            AND expires_at > NOW()
            LIMIT 1
        ";
    
        $session = fetchSingleDataWithJoins($sql, [':session_id' => $sessionId]);
    
        return $session ?: null;
    }

    private function buildAvatarPayload(?string $photoLocValue, ?string $profileLocation): array {
        $baseUrl = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];

        if (!empty($profileLocation)) {
            return [
                'avatarType' => 'image',
                'avatar'     => $baseUrl . "/shared/serve_image.php?path=" . $profileLocation . "&type=profile"
            ];
        }

        if (!empty($photoLocValue)) {
            if (preg_match('/^fa[srb]?\s+fa-/', $photoLocValue)) {
                return [
                    'avatarType' => 'icon',
                    'avatar'     => $photoLocValue
                ];
            }
            return [
                'avatarType' => 'image',
                'avatar'     => $baseUrl . "/shared/serve_image.php?path=" . $photoLocValue . "&type=profile"
            ];
        }

        return [
            'avatarType' => 'image',
            'avatar'     => $baseUrl . "/shared/serve_image.php?path=user-circle.png&type=profile"
        ];
    }

    public function get() {
        $session = $this->getUserFromToken();
        if (!$session) {
            http_response_code(401);
            echo json_encode(['error' => ['message' => 'Unauthorized']]);
            return;
        }

        $userId   = (int)$session['user_id'];
        $userType = $session['user_type'];
        $profile  = null;

        $isUsersTable = in_array($userType, [
            'super_admin','admin','dealer','property_admin','organization_admin','sub_dealer','user'
        ], true);

        if ($isUsersTable) {
            $sql = "
                SELECT 
                    u.id, u.email, u.created_at,
                    TRIM(CONCAT(COALESCE(u.firstname,''),' ',COALESCE(u.lastname,''))) AS full_name_fallback,
                    d.full_name AS full_name_from_data,
                    d.phone_number,
                    d.photo_loc AS data_photo_loc,
                    p.location  AS profile_location
                FROM users u
                LEFT JOIN users_data d ON d.user_id = u.id
                LEFT JOIN profile_photo p ON (
                    CASE 
                      WHEN d.photo_loc REGEXP '^[0-9]+$' THEN p.id = d.photo_loc 
                      ELSE 0
                    END
                )
                WHERE u.id = :id
                LIMIT 1
            ";
            $profile = fetchSingleDataWithJoins($sql, [':id' => $userId]);

            if (!$profile) {
                http_response_code(404);
                echo json_encode(['error' => ['message' => 'Profile not found']]);
                return;
            }

            $fullName = $profile['full_name_fallback'];
            if (!$fullName || trim($fullName) === '') {
                $fullName = $profile['full_name_from_data'];
            }

            $avatarPayload = $this->buildAvatarPayload($profile['data_photo_loc'] ?? null, $profile['profile_location'] ?? null);

            echo json_encode([
                'id'          => $profile['id'],
                'email'       => $profile['email'],
                'created_at'  => $profile['created_at'],
                'full_name'   => $fullName,
                'phone_number'=> $profile['phone_number'] ?? null,
                'avatarType'  => $avatarPayload['avatarType'],
                'avatar'      => $avatarPayload['avatar'],
            ]);
            return;
        }

        if ($userType === 'dealer_admin') {
            $sql = "
                SELECT 
                    u.id, u.email, u.created_at,
                    TRIM(CONCAT(COALESCE(u.firstname,''),' ',COALESCE(u.lastname,''))) AS full_name,
                    d.mobile_number AS phone_number,
                    d.photo_loc     AS data_photo_loc,
                    p.location      AS profile_location
                FROM dealer_admins u
                LEFT JOIN dealer_admins_data d ON d.dealer_admin_id = u.id
                LEFT JOIN profile_photo p ON (
                    CASE 
                      WHEN d.photo_loc REGEXP '^[0-9]+$' THEN p.id = d.photo_loc 
                      ELSE 0 
                    END
                )
                WHERE u.id = :id
                LIMIT 1
            ";
            $profile = fetchSingleDataWithJoins($sql, [':id' => $userId]);

            if (!$profile) {
                http_response_code(404);
                echo json_encode(['error' => ['message' => 'Profile not found']]);
                return;
            }

            $avatarPayload = $this->buildAvatarPayload($profile['data_photo_loc'] ?? null, $profile['profile_location'] ?? null);

            echo json_encode([
                'id'          => $profile['id'],
                'email'       => $profile['email'],
                'created_at'  => $profile['created_at'],
                'full_name'   => $profile['full_name'],
                'phone_number'=> $profile['phone_number'] ?? null,
                'avatarType'  => $avatarPayload['avatarType'],
                'avatar'      => $avatarPayload['avatar'],
            ]);
            return;
        }

        if ($userType === 'property_user' || $userType === 'multi_prop') {
            $sql = "
                SELECT 
                    u.id, u.email, u.created_at,
                    TRIM(CONCAT(COALESCE(d.firstname,''),' ',COALESCE(d.lastname,''))) AS full_name,
                    d.mobile_number AS phone_number,
                    d.photo_loc     AS data_photo_loc,
                    p.location      AS profile_location
                FROM property_users u
                LEFT JOIN property_users_data d ON d.property_user = u.id
                LEFT JOIN profile_photo p ON (
                    CASE 
                      WHEN d.photo_loc REGEXP '^[0-9]+$' THEN p.id = d.photo_loc 
                      ELSE 0 
                    END
                )
                WHERE u.id = :id
                LIMIT 1
            ";
            $profile = fetchSingleDataWithJoins($sql, [':id' => $userId]);

            if (!$profile) {
                http_response_code(404);
                echo json_encode(['error' => ['message' => 'Profile not found']]);
                return;
            }

            $avatarPayload = $this->buildAvatarPayload($profile['data_photo_loc'] ?? null, $profile['profile_location'] ?? null);

            echo json_encode([
                'id'          => $profile['id'],
                'email'       => $profile['email'],
                'created_at'  => $profile['created_at'],
                'full_name'   => $profile['full_name'],
                'phone_number'=> $profile['phone_number'] ?? null,
                'avatarType'  => $avatarPayload['avatarType'],
                'avatar'      => $avatarPayload['avatar'],
            ]);
            return;
        }

        http_response_code(400);
        echo json_encode(['error' => ['message' => 'Invalid user type']]);
    }

    public function update() {
        $session = $this->getUserFromToken();
        if (!$session) {
            http_response_code(401);
            echo json_encode(['error' => ['message' => 'Unauthorized']]);
            return;
        }

        $userId   = (int)$session['user_id'];
        $userType = $session['user_type'];

        $data = json_decode(file_get_contents('php://input'), true);
    
        if (!$data || !is_array($data)) {
            http_response_code(400);
            echo json_encode(['error' => ['message' => 'Invalid input']]);
            return;
        }

        if (in_array($userType, ['property_user','multi_prop'], true)) {
            $dataToUpdate = [];
            if (!empty($data['full_name'])) {
                $parts = explode(' ', $data['full_name'], 2);
                $dataToUpdate['firstname'] = $parts[0];
                $dataToUpdate['lastname']  = isset($parts[1]) ? $parts[1] : '';
            }
            if (!empty($data['phone_number'])) {
                $dataToUpdate['mobile_number'] = $data['phone_number'];
            }
            if (!empty($dataToUpdate)) {
                updateTable('property_users_data', $dataToUpdate, 'property_user = :id', ['id' => $userId]);
            }

            $this->get();
            return;
        }

        if ($userType === 'dealer_admin') {
            if (!empty($data['full_name'])) {
                $parts = explode(' ', $data['full_name'], 2);
                updateTable('dealer_admins', [
                    'firstname'  => $parts[0],
                    'lastname'   => $parts[1] ?? '',
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $userId]);
            }
            if (!empty($data['phone_number'])) {
                updateTable('dealer_admins_data', [
                    'mobile_number' => $data['phone_number'],
                    'updated_at'    => date('Y-m-d H:i:s')
                ], 'dealer_admin_id = :id', ['id' => $userId]);
            }
            $this->get();
            return;
        }

        if (in_array($userType, ['super_admin','admin','dealer','property_admin','organization_admin','sub_dealer','user'], true)) {
            $dataToUpdate = [];
            if (!empty($data['full_name'])) {
                $dataToUpdate['full_name'] = $data['full_name'];
            }
            if (!empty($data['phone_number'])) {
                $dataToUpdate['phone_number'] = $data['phone_number'];
            }
            if (!empty($dataToUpdate)) {
                $dataToUpdate['updated_at'] = date('Y-m-d H:i:s');
                updateTable('users_data', $dataToUpdate, 'user_id = :id', ['id' => $userId]);
            }
            $this->get();
            return;
        }

        http_response_code(400);
        echo json_encode(['error' => ['message' => 'Invalid user type']]);
    }

    public function updateAvatar() {
        $session = $this->getUserFromToken();
        if (!$session) {
            http_response_code(401);
            echo json_encode(['error' => ['message' => 'Unauthorized']]);
            return;
        }

        $userId   = (int)$session['user_id'];
        $userType = $session['user_type'];
        $conn     = $this->db->getConnection();

        $headers = getallheaders();
        $authHdr = $headers['Authorization'] ?? '';
        $sessionIdFromHeader = null;
        if (preg_match('/Bearer\s+(.+)/', $authHdr, $mm)) {
            $sessionIdFromHeader = $mm[1];
        }
        $propertyIdForPhoto = null;
        if ($sessionIdFromHeader) {
            $sessRow = fetchSingleDataWithJoins("
                SELECT current_property_id 
                FROM mobile_sessions 
                WHERE session_id = :sid AND expires_at > NOW()
                LIMIT 1
            ", [':sid' => $sessionIdFromHeader]);
            $propertyIdForPhoto = $sessRow['current_property_id'] ?? null;
        }

        $profilePayload = fn() => $this->buildProfileResponse($userId, $userType, $propertyIdForPhoto ?? null);

        $ct = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
        $rawImageBytes = null;
        $ext = null;
        $tmpPath = null;

        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['profile_image'];
            $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (!in_array($file['type'], $allowedMimeTypes)) {
                $this->jsonOut(
                $profilePayload() + ['error' => ['message' => 'Invalid image type. Only JPG, PNG, and GIF are allowed.']],
                400
            );
            }
            if ($file['size'] > 4 * 1024 * 1024) {
                $this->jsonOut(
                    $profilePayload() + ['error' => ['message' => 'File size exceeds the 4MB limit.']],
                    400
                );
            }
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $tmpPath = $file['tmp_name'];

        } else {
            $body = file_get_contents('php://input');

            if (!isset($_FILES['profile_image']) && ($body === '' || $body === null)) {
                $payload = $profilePayload();
                $payload['noop'] = true;
                $this->jsonOut($payload, 200);
            }

            if (stripos($ct, 'application/json') !== false) {
                $payload = json_decode($body, true);
                $img = $payload['image'] ?? $payload['dataUrl'] ?? null;
                if ($img === null || $img === '') {
                    $payload = $profilePayload();
                    $payload['noop'] = true;
                    $this->jsonOut($payload, 200);
                }
                if (preg_match('/^data:(image\/(png|jpe?g|gif));base64,(.+)$/i', $img, $m)) {
                    $mime   = strtolower($m[1]);
                    $base64 = $m[3];
                    $map = ['image/jpeg'=>'jpg','image/jpg'=>'jpg','image/png'=>'png','image/gif'=>'gif'];
                    $ext = $map[$mime] ?? 'jpg';
                    $rawImageBytes = base64_decode($base64, true);
                } else {
                    $rawImageBytes = base64_decode($img, true);
                    $ext = 'jpg';
                }
                if (!$rawImageBytes) {
                    $this->jsonOut(
                        $profilePayload() + ['error' => ['message' => 'Invalid base64 image data.']],
                        400
                    );
                }
                if (strlen($rawImageBytes) > 4 * 1024 * 1024) {
                    $this->jsonOut(
                        $profilePayload() + ['error' => ['message' => 'File size exceeds the 4MB limit.']],
                        400
                    );
                }
                if (@getimagesizefromstring($rawImageBytes) === false) {
                    $this->jsonOut(
                        $profilePayload() + ['error' => ['message' => 'Uploaded content is not a valid image.']],
                        400
                    );
                }

            } elseif (preg_match('/^image\/(png|jpe?g|gif)$/i', $ct, $m) || stripos($ct, 'application/octet-stream') !== false) {
                $rawImageBytes = $body;
                $sub = strtolower($m[1] ?? '');
                if ($sub === 'jpeg') $sub = 'jpg';
                $ext = $sub ?: 'jpg';
                if (strlen($rawImageBytes) > 4 * 1024 * 1024) {
                    $this->jsonOut(
                        $profilePayload() + ['error' => ['message' => 'File size exceeds the 4MB limit.']],
                        400
                    );
                }
                if (@getimagesizefromstring($rawImageBytes) === false) {
                    $this->jsonOut(
                        $profilePayload() + ['error' => ['message' => 'Uploaded content is not a valid image.']],
                        400
                    );
                }
            } else {
                $this->jsonOut(
                        $profilePayload() + ['error' => ['message' => 'Unsupported media type. Send multipart/form-data, raw image, or JSON base64.']],
                        400
                    );
            }
        }

        $uploadDir = '../../../../data/profile_images/';
        if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); }

        if (method_exists($this, 'removeUserProfileImagesFromDisk')) {
            $this->removeUserProfileImagesFromDisk($userId, $uploadDir);
        }

        $filename   = 'user_' . $userId . '_profile_' . time() . '.' . $ext;
        $uploadPath = $uploadDir . $filename;

        if ($tmpPath) {
            if (!move_uploaded_file($tmpPath, $uploadPath)) {
                http_response_code(500);
                echo json_encode(['error' => ['message' => 'Failed to upload image.']]);
                return;
            }
        } else {
            if (file_put_contents($uploadPath, $rawImageBytes) === false) {
                http_response_code(500);
                echo json_encode(['error' => ['message' => 'Failed to write image.']]);
                return;
            }
        }

        @chmod($uploadPath, 0666);
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            @shell_exec("icacls " . escapeshellarg($uploadPath) . " /grant Everyone:F");
        }

        $now = date('Y-m-d H:i:s');

        $ensureRow = function(string $table, string $idCol, int $id, array $payload) {
            $exists = fetchSingleDataWithJoins("SELECT {$idCol} FROM {$table} WHERE {$idCol} = :id LIMIT 1", [':id' => $id]);
            if ($exists) {
                updateTable($table, $payload, "{$idCol} = :id", ['id' => $id]);
            } else {
                $payload[$idCol] = $id;
                insertData($table, $payload);
            }
        };

        if (in_array($userType, ['super_admin','admin','dealer'], true)) {
            $ensureRow('users_data', 'user_id', $userId, [
                'photo_loc'  => $filename,
                'updated_at' => $now
            ]);

            echo json_encode([
                'avatar'     => "/shared/serve_image.php?path={$filename}&type=profile",
                'avatarType' => 'image'
            ]);
            return;
        }

        $ppUserType = match (true) {
            in_array($userType, ['dealer_admin','sub_dealer','organization_admin'], true) => 'dealer_admin',
            in_array($userType, ['property_admin','user'], true)                           => 'users',
            in_array($userType, ['property_user'], true)                                   => 'users',
            in_array($userType, ['multi_prop','multi_prop_user'], true)                    => 'multi_property_user',
            default                                                                        => 'users',
        };

        $params   = [':uid' => $userId, ':ut' => $ppUserType];
        $wherePid = 'property_id IS NULL';
        if ($propertyIdForPhoto !== null) {
            $wherePid = 'property_id = :pid';
            $params[':pid'] = (int)$propertyIdForPhoto;
        }

        $existingPhoto = fetchSingleDataWithJoins("
            SELECT id, location
            FROM profile_photo
            WHERE user_id = :uid
            AND user_type = :ut
            AND {$wherePid}
            ORDER BY id DESC
            LIMIT 1
        ", $params);

        if ($existingPhoto) {
            updateTable('profile_photo', [
                'location'   => $filename
            ], 'id = :id', ['id' => (int)$existingPhoto['id']]);
            $photoId = (int)$existingPhoto['id'];
        } else {
            insertData('profile_photo', [
                'user_id'     => $userId,
                'user_type'   => $ppUserType,
                'property_id' => $propertyIdForPhoto,
                'location'    => $filename,
                'created_by'  => $userId,
                'creator_type'=> $ppUserType,
                'created_at'  => $now
            ]);
            $photoId = function_exists('getLastInsertId') ? getLastInsertId() : $conn->lastInsertId();
        }

        if (in_array($userType, ['dealer_admin','sub_dealer','organization_admin'], true)) {
            $ensureRow('dealer_admins_data', 'dealer_admin_id', $userId, ['photo_loc' => $photoId, 'updated_at' => $now]);
        } elseif (in_array($userType, ['property_user','multi_prop','multi_prop_user'], true)) {
            $ensureRow('property_users_data', 'property_user', $userId, ['photo_loc' => $photoId]);
        } else {
            $ensureRow('users_data', 'user_id', $userId, ['photo_loc' => $photoId, 'updated_at' => $now]);
        }

        $this->jsonOut($profilePayload(), 200);
    }


    private function removeUserProfileImagesFromDisk(int $userId, string $uploadDir): void {

        $uploadDir = rtrim($uploadDir, '/\\') . DIRECTORY_SEPARATOR;

        $pattern = $uploadDir . 'user_' . $userId . '_profile_*.*';

        foreach (glob($pattern, GLOB_NOSORT) ?: [] as $path) {
            if (is_file($path)) {
                @unlink($path);
            }
        }
    }

    private function currentAvatarUrl(int $userId, string $userType, ?int $propertyIdForPhoto = null): string {
        $baseUrl  = ($_SERVER['REQUEST_SCHEME'] ?? 'https') . '://' . $_SERVER['HTTP_HOST'];
        $default  = $baseUrl . "/shared/serve_image.php?path=user-circle.png&type=profile";

        if (in_array($userType, ['super_admin','admin','dealer'], true)) {
            $row = fetchSingleDataWithJoins("SELECT photo_loc FROM users_data WHERE user_id = :id LIMIT 1", [':id' => $userId]);
            if (!empty($row['photo_loc'])) {
                return $baseUrl . "/shared/serve_image.php?path=" . $row['photo_loc'] . "&type=profile";
            }
            return $default;
        }

        if (in_array($userType, ['dealer_admin','sub_dealer','organization_admin'], true)) {
            $idRow = fetchSingleDataWithJoins("SELECT photo_loc FROM dealer_admins_data WHERE dealer_admin_id = :id LIMIT 1", [':id' => $userId]);
        } elseif (in_array($userType, ['property_user'], true)) {
            $idRow = fetchSingleDataWithJoins("SELECT photo_loc FROM property_users_data WHERE property_user = :id LIMIT 1", [':id' => $userId]);
        } elseif (in_array($userType, ['multi_prop','multi_prop_user'], true)) {
            $idRow = fetchSingleDataWithJoins("SELECT photo_loc FROM multi_prop_users WHERE property_user = :id LIMIT 1", [':id' => $userId]);
        } else {
            $idRow = fetchSingleDataWithJoins("SELECT photo_loc FROM users_data WHERE user_id = :id LIMIT 1", [':id' => $userId]);
        }

        $photoId = $idRow['photo_loc'] ?? null;
        if (!$photoId) return $default;

        $photo = fetchSingleDataWithJoins("SELECT location FROM profile_photo WHERE id = :pid LIMIT 1", [':pid' => (int)$photoId]);
        if (!empty($photo['location'])) {
            return $baseUrl . "/shared/serve_image.php?path=" . $photo['location'] . "&type=profile";
        }
        return $default;
    }

    private function jsonOut(array $payload, int $code = 200): void {
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }
        if (ob_get_length()) { @ob_clean(); }
        http_response_code($code);
        echo json_encode($payload, JSON_UNESCAPED_SLASHES);
        exit;
    }

    private function buildProfileResponse(int $userId, string $userType, ?int $propertyIdForPhoto = null): array {
        $baseUrl = ($_SERVER['REQUEST_SCHEME'] ?? 'https') . '://' . $_SERVER['HTTP_HOST'];
        $avatar  = $this->currentAvatarUrl($userId, $userType, $propertyIdForPhoto);
        $now     = date('Y-m-d H:i:s');

        $row = null;
        switch (true) {
            case in_array($userType, ['dealer_admin','sub_dealer','organization_admin'], true):
                $row = fetchSingleDataWithJoins("
                    SELECT da.id, da.email, CONCAT(da.firstname,' ',da.lastname) AS full_name,
                        dad.mobile_number AS phone, da.created_at, dad.updated_at
                    FROM dealer_admins da
                    LEFT JOIN dealer_admins_data dad ON dad.dealer_admin_id = da.id
                    WHERE da.id = :id
                    LIMIT 1
                ", [':id' => $userId]);
                break;

            case in_array($userType, ['property_user','multi_prop','multi_prop_user'], true):
                $row = fetchSingleDataWithJoins("
                    SELECT pu.id, pu.email, CONCAT(pud.firstname,' ',pud.lastname) AS full_name,
                        pud.mobile_number AS phone, pu.created_at, pud.updated_at
                    FROM property_users pu
                    LEFT JOIN property_users_data pud ON pud.property_user = pu.id
                    WHERE pu.id = :id
                    LIMIT 1
                ", [':id' => $userId]);
                break;

            default:
                $row = fetchSingleDataWithJoins("
                    SELECT u.id, u.email, COALESCE(ud.full_name, CONCAT(u.firstname,' ',u.lastname)) AS full_name,
                        ud.phone_number AS phone, u.created_at, ud.updated_at
                    FROM users u
                    LEFT JOIN users_data ud ON ud.user_id = u.id
                    WHERE u.id = :id
                    LIMIT 1
                ", [':id' => $userId]);
                break;
        }

        return [
            'id'        => (string)($row['id'] ?? $userId),
            'fullName'  => (string)($row['full_name'] ?? ''),
            'email'     => (string)($row['email'] ?? ''),
            'phone'     => (string)($row['phone'] ?? ''),
            'avatar'    => $avatar,
            'avatarType'=> 'image',
            'createdAt' => (string)($row['created_at'] ?? $now),
            'updatedAt' => (string)($row['updated_at'] ?? $now),
        ];
    }

}

$profile = new Profile();
$method = $_SERVER['REQUEST_METHOD'];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$segments = explode('/', trim($requestUri, '/'));
$lastSegment = end($segments);

if ($method === 'OPTIONS') {
    http_response_code(200);
    echo json_encode(['ok' => true]);
    exit;
}

switch ($lastSegment) {
    case 'profile':
        if ($method === 'GET') {
            $profile->get();
            exit;
        } elseif ($method === 'PUT' || $method === 'POST') {
            $profile->updateAvatar();
            exit;  
        } else {
            http_response_code(405);
            echo json_encode(['error' => ['message' => 'Method Not Allowed']]);
            exit;
        }

    case 'avatar':
        if ($method === 'POST') {
            $profile->updateAvatar();
            exit;
        } else {
            http_response_code(405);
            echo json_encode(['error' => ['message' => 'Method Not Allowed']]);
            exit;
        }

    case 'get':
        if ($method === 'GET') {
            $profile->get();
            exit;
        } else {
            http_response_code(405);
            echo json_encode(['error' => ['message' => 'Method Not Allowed']]);
            exit;
        }

    case 'update':
        http_response_code(405);
        echo json_encode(['error' => ['message' => 'Profile editing is disabled.']]);
        exit;

    default:
        http_response_code(404);
        echo json_encode(['error' => ['message' => 'Not Found']]);
        exit;
}
