<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Config;
use App\Core\Controller;
use App\Core\Database;
use App\Core\MobileLicenseManager;
use App\Core\TOTP;
use PDO;

class UsersController extends Controller
{
    private const TECHNICIAN_TYPES = ['etude_raccordement', 'raccordement', 'backbones', 'maintenance_ftth', 'etude'];
    private const TYPED_USER_ROLES = ['technicien', 'technician', 'agent', 'superviseur', 'supervisor'];
    private const TECHNICIAN_TYPE_OPTIONS_BY_ROLE = [
        'technicien' => ['etude', 'raccordement', 'backbones', 'maintenance_ftth'],
        'technician' => ['etude', 'raccordement', 'backbones', 'maintenance_ftth'],
        'agent' => ['etude_raccordement', 'backbones', 'maintenance_ftth'],
        'superviseur' => ['etude_raccordement', 'backbones', 'maintenance_ftth'],
        'supervisor' => ['etude_raccordement', 'backbones', 'maintenance_ftth'],
    ];

    public function index(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);
        $pdo = Database::pdo();
        $this->ensureUserPhotoColumn($pdo);
        $this->ensureTechnicianTypeColumn($pdo);
        $this->ensureAssignedCityColumn($pdo);
        MobileLicenseManager::ensureSchema($pdo);

        $hasLastLogin = $this->tableHasColumn($pdo, 'users', 'last_login');
        $lastLoginSelect = $hasLastLogin ? 'last_login' : 'NULL AS last_login';

        $users = $pdo->query("SELECT id,name,email,role_key,technician_type,assigned_city,active,photo_path, {$lastLoginSelect} FROM users ORDER BY id DESC")->fetchAll();

        $deviceActivityByUser = [];
        if ($this->tableExists($pdo, 'user_devices') && $this->tableHasColumn($pdo, 'user_devices', 'last_seen_at')) {
            $rows = $pdo->query('SELECT user_id, MAX(last_seen_at) AS last_seen_at FROM user_devices GROUP BY user_id')->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $row) {
                $deviceActivityByUser[(int)($row['user_id'] ?? 0)] = (string)($row['last_seen_at'] ?? '');
            }
        }

        $licenseActivityByUser = [];
        foreach (MobileLicenseManager::listLicenses($pdo) as $licenseRow) {
            $licenseActivityByUser[(int)($licenseRow['user_id'] ?? 0)] = [
                'mobile_last_login_at' => (string)($licenseRow['mobile_last_login_at'] ?? ''),
                'device_last_seen_at' => (string)($licenseRow['device_last_seen_at'] ?? ''),
            ];
        }

        foreach ($users as &$user) {
            $user['technician_type'] = $this->normalizeStoredTechnicianTypeForRole($user['technician_type'] ?? null, (string)($user['role_key'] ?? ''));
            $user['assigned_city'] = $this->normalizeAssignedCity($user['assigned_city'] ?? null);
            $user['photo_url'] = $this->resolveUserPhotoUrl($user['photo_path'] ?? null);
            $userId = (int)($user['id'] ?? 0);
            $webLastLogin = (string)($user['last_login'] ?? '');
            $mobileLastLogin = (string)($licenseActivityByUser[$userId]['mobile_last_login_at'] ?? '');
            $deviceLastSeen = (string)($deviceActivityByUser[$userId] ?? ($licenseActivityByUser[$userId]['device_last_seen_at'] ?? ''));

            $user['last_activity_at'] = $webLastLogin;
            $user['last_activity_source'] = $webLastLogin !== '' ? 'web' : null;

            foreach ([
                ['value' => $mobileLastLogin, 'source' => 'mobile'],
                ['value' => $deviceLastSeen, 'source' => 'device'],
            ] as $candidate) {
                if ($candidate['value'] === '') {
                    continue;
                }
                if (($user['last_activity_at'] ?? '') === '' || strtotime($candidate['value']) > strtotime((string)$user['last_activity_at'])) {
                    $user['last_activity_at'] = $candidate['value'];
                    $user['last_activity_source'] = $candidate['source'];
                }
            }
        }
        unset($user);

        $this->view('settings/users', [
            'users' => $users,
            'technicianTypeOptions' => self::TECHNICIAN_TYPES,
            'technicianTypeOptionsByRole' => self::TECHNICIAN_TYPE_OPTIONS_BY_ROLE,
        ]);
    }

    public function create(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name = trim($_POST['name'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $role = trim($_POST['role_key'] ?? 'agent');
            $pass = $_POST['password'] ?? '';
            if ($name && $email && $pass) {
                $pdo = Database::pdo();
                $this->ensureUserPhotoColumn($pdo);
                $this->ensureTechnicianTypeColumn($pdo);
                $this->ensureAssignedCityColumn($pdo);
                $technicianType = $this->normalizeTechnicianType($_POST['technician_type'] ?? null, $role);
                $assignedCity = $this->normalizeAssignedCity($_POST['assigned_city'] ?? null);
                $username = strtolower(str_replace('@', '_', explode('@', $email)[0]));
                $stmt = $pdo->prepare('INSERT INTO users(username,name,email,password,role_key,technician_type,assigned_city,active) VALUES(?,?,?,?,?,?,?,1)');
                $stmt->execute([$username, $name, $email, password_hash($pass, PASSWORD_DEFAULT), $role, $technicianType, $assignedCity]);
                $userId = (int)$pdo->lastInsertId();
                $photoPath = $this->storeUserPhoto($userId, $_FILES['photo'] ?? null, null);
                if ($photoPath !== null) {
                    $pdo->prepare('UPDATE users SET photo_path = ? WHERE id = ?')->execute([$photoPath, $userId]);
                }
            }
            $this->redirect('/users');
            return;
        }
        $this->view('settings/placeholder', ['title' => 'Créer utilisateur', 'message' => 'Formulaire minimal à implémenter']);
    }

    public function toggle2fa(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);
        $id = (int)($_GET['id'] ?? 0);
        $pdo = Database::pdo();
        $u = $pdo->prepare('SELECT * FROM users WHERE id=?');
        $u->execute([$id]);
        $user = $u->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $new = empty($user['totp_secret']) ? TOTP::generateSecret() : null;
            $stmt = $pdo->prepare('UPDATE users SET totp_secret = :s WHERE id=:id');
            $stmt->execute([':s' => $new, ':id' => $id]);
        }
        $this->redirect('/users');
    }

    public function profile(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        $pdo = Database::pdo();
        $current = Auth::user();
        $this->ensureTakeoverColumn($pdo);
        $this->ensureAssignedCityColumn($pdo);
        $stmt = $pdo->prepare('SELECT id,name,email,role_key,technician_type,assigned_city,active, takeover_at FROM users WHERE id=?');
        $stmt->execute([(int)$current['id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $user['technician_type'] = $this->normalizeStoredTechnicianTypeForRole($user['technician_type'] ?? null, (string)($user['role_key'] ?? ''));
            $user['assigned_city'] = $this->normalizeAssignedCity($user['assigned_city'] ?? null);
        }
        $this->view('users/profile', ['user' => $user]);
    }

    public function takeover(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        $u = Auth::user();
        if (!in_array($u['role_key'] ?? '', ['technicien', 'admin'])) { $this->redirect('/users/profile'); }
        $pdo = Database::pdo();
        $this->ensureTakeoverColumn($pdo);
        $this->ensureTakeoverEventsTable($pdo);
        $this->ensureTakeoverEventColumns($pdo);
        $isAjax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') || (isset($_POST['ajax']) && $_POST['ajax'] == '1');
        try {
            $sel = $pdo->prepare('SELECT takeover_at FROM users WHERE id=?');
            $sel->execute([(int)$u['id']]);
            $existing = $sel->fetchColumn();
            if (!empty($existing)) {
                if ($isAjax) {
                    http_response_code(409);
                    $this->respondJson(['status' => 'already', 'takeover_at' => $existing]);
                }
                $back = $_SERVER['HTTP_REFERER'] ?? null;
                if ($back) { header('Location: ' . $back); exit; }
                $this->redirect('/users/profile');
            }

            $upd = $pdo->prepare('UPDATE users SET takeover_at = NOW() WHERE id=?');
            $upd->execute([(int)$u['id']]);

            $ip = $this->getClientIp();
            $ua = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 1024);
            $lat = isset($_POST['lat']) ? (float)$_POST['lat'] : null;
            $lng = isset($_POST['lng']) ? (float)$_POST['lng'] : null;

            $ins = $pdo->prepare('INSERT INTO user_takeover_events (user_id, taken_at, ip_address, user_agent, lat, lng) VALUES (?, NOW(), ?, ?, ?, ?)');
            $ins->execute([(int)$u['id'], $ip, $ua, $lat, $lng]);

            try {
                $rec = $pdo->query("SELECT id FROM users WHERE active=1 AND role_key IN ('superviseur','supervisor','manager','admin')")->fetchAll(PDO::FETCH_COLUMN);
                if (!empty($rec)) {
                    $who = ($u['name'] ?? 'Un technicien');
                    $titleN = 'Prise en charge technicien';
                    $bodyN = $who . " s'est mis en prise en charge à " . date('H:i');
                    $url = \route_url('/cartographie');
                    \App\Core\Notifier::notifyUsers($pdo, array_map('intval', $rec), $titleN, $bodyN, $url);
                    \App\Core\Notifier::emailUsers($pdo, array_map('intval', $rec), $titleN, nl2br(htmlentities($bodyN)) . '<br><a href="' . $url . '">Ouvrir</a>');
                }
            } catch (\Throwable $ne) {
            }

            if ($isAjax) {
                $ts = $pdo->prepare('SELECT takeover_at FROM users WHERE id=?');
                $ts->execute([(int)$u['id']]);
                $take = $ts->fetchColumn();
                $this->respondJson(['status' => 'ok', 'takeover_at' => $take ?: date('Y-m-d H:i:s')]);
                return;
            }
        } catch (\Throwable $e) {
        }
        $back = $_SERVER['HTTP_REFERER'] ?? null;
        if ($back) { header('Location: ' . $back); exit; }
        $this->redirect('/users/profile');
    }

    private function ensureTakeoverColumn(PDO $pdo): void
    {
        try {
            $db = $pdo->query('SELECT DATABASE()')->fetchColumn();
            if ($db) {
                $chk = $pdo->prepare('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME="users" AND COLUMN_NAME="takeover_at"');
                $chk->execute([$db]);
                if ((int)$chk->fetchColumn() === 0) {
                    $pdo->exec('ALTER TABLE `users` ADD COLUMN `takeover_at` DATETIME NULL');
                }
            }
        } catch (\Throwable $e) {
        }
    }

    private function ensureTakeoverEventsTable(PDO $pdo): void
    {
        $pdo->exec("CREATE TABLE IF NOT EXISTS user_takeover_events (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            taken_at DATETIME NOT NULL,
            ip_address VARCHAR(64) NULL,
            user_agent TEXT NULL,
            lat DECIMAL(10,7) NULL,
            lng DECIMAL(10,7) NULL,
            INDEX (user_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    }

    private function ensureTakeoverEventColumns(PDO $pdo): void
    {
        try {
            $db = $pdo->query('SELECT DATABASE()')->fetchColumn();
            if (!$db) return;
            $need = [
                'ip_address' => 'ADD COLUMN `ip_address` VARCHAR(64) NULL',
                'user_agent' => 'ADD COLUMN `user_agent` TEXT NULL',
                'lat' => 'ADD COLUMN `lat` DECIMAL(10,7) NULL',
                'lng' => 'ADD COLUMN `lng` DECIMAL(10,7) NULL',
            ];
            foreach ($need as $col => $ddl) {
                $q = $pdo->prepare('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME="user_takeover_events" AND COLUMN_NAME=?');
                $q->execute([$db, $col]);
                if ((int)$q->fetchColumn() === 0) {
                    $pdo->exec('ALTER TABLE `user_takeover_events` ' . $ddl);
                }
            }
        } catch (\Throwable $e) {
        }
    }

    private function getClientIp(): string
    {
        $h = $_SERVER;
        $candidates = [
            'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'
        ];
        foreach ($candidates as $key) {
            if (!empty($h[$key])) {
                $ips = explode(',', (string)$h[$key]);
                foreach ($ips as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP)) { return $ip; }
                }
            }
        }
        return $_SERVER['REMOTE_ADDR'] ?? '';
    }

    private function respondJson(array $data): void
    {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    public function update(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $this->redirect('/users'); }

        $userId = (int)($_POST['user_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $roleKey = trim($_POST['role_key'] ?? '');
        $technicianType = $this->normalizeTechnicianType($_POST['technician_type'] ?? null, $roleKey);
        $assignedCity = $this->normalizeAssignedCity($_POST['assigned_city'] ?? null);
        $active = isset($_POST['active']) ? 1 : 0;
        $password = trim($_POST['password'] ?? '');

        if (!$userId || !$name || !$email || !$roleKey) {
            $this->redirect('/users?error=invalid_data');
            return;
        }

        $pdo = Database::pdo();
        $this->ensureUserPhotoColumn($pdo);
        $this->ensureTechnicianTypeColumn($pdo);
        $this->ensureAssignedCityColumn($pdo);

        try {
            $checkStmt = $pdo->prepare('SELECT id, photo_path FROM users WHERE id = ?');
            $checkStmt->execute([$userId]);
            $existingUser = $checkStmt->fetch(PDO::FETCH_ASSOC);
            if (!$existingUser) {
                $this->redirect('/users?error=user_not_found');
                return;
            }

            $emailStmt = $pdo->prepare('SELECT id FROM users WHERE email = ? AND id != ?');
            $emailStmt->execute([$email, $userId]);
            if ($emailStmt->fetch()) {
                $this->redirect('/users?error=email_exists');
                return;
            }

            $photoPath = $this->storeUserPhoto($userId, $_FILES['photo'] ?? null, $existingUser['photo_path'] ?? null);

            if (!empty($password)) {
                $stmt = $pdo->prepare('UPDATE users SET name = ?, email = ?, role_key = ?, technician_type = ?, assigned_city = ?, active = ?, password = ?, photo_path = ? WHERE id = ?');
                $stmt->execute([$name, $email, $roleKey, $technicianType, $assignedCity, $active, password_hash($password, PASSWORD_DEFAULT), $photoPath, $userId]);
            } else {
                $stmt = $pdo->prepare('UPDATE users SET name = ?, email = ?, role_key = ?, technician_type = ?, assigned_city = ?, active = ?, photo_path = ? WHERE id = ?');
                $stmt->execute([$name, $email, $roleKey, $technicianType, $assignedCity, $active, $photoPath, $userId]);
            }

            $this->redirect('/users?success=user_updated');
        } catch (\Throwable $e) {
            $this->redirect('/users?error=update_failed');
        }
    }

    public function delete(): void
    {
        if (!Auth::check()) { $this->redirect('/login'); }
        Auth::requireRole(['admin']);

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $this->redirect('/users'); }

        $userId = (int)($_POST['user_id'] ?? 0);
        $currentUser = Auth::user();

        if (!$userId) {
            $this->redirect('/users?error=invalid_data');
            return;
        }

        if ($userId === (int)$currentUser['id']) {
            $this->redirect('/users?error=cannot_delete_self');
            return;
        }

        $pdo = Database::pdo();

        try {
            $checkStmt = $pdo->prepare('SELECT id, name FROM users WHERE id = ?');
            $checkStmt->execute([$userId]);
            $user = $checkStmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                $this->redirect('/users?error=user_not_found');
                return;
            }

            $pdo->beginTransaction();
            $this->cleanupUserDependencies($pdo, $userId);
            $deleteStmt = $pdo->prepare('DELETE FROM users WHERE id = ?');
            $deleteStmt->execute([$userId]);
            $pdo->commit();

            $this->redirect('/users?success=user_deleted');
        } catch (\Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $this->redirect('/users?error=delete_failed');
        }
    }

    private function cleanupUserDependencies(PDO $pdo, int $userId): void
    {
        $tableDeletes = [
            'notifications',
            'api_tokens',
            'user_devices',
            'mobile_user_license_events',
            'mobile_user_licenses',
            'password_resets',
            'user_takeover_events',
            'technician_location_history',
            'technician_locations',
            'incident_comments',
            'incident_intervention_events',
        ];

        foreach ($tableDeletes as $tableName) {
            if ($this->tableHasColumn($pdo, $tableName, 'user_id')) {
                $stmt = $pdo->prepare("DELETE FROM `{$tableName}` WHERE user_id = ?");
                $stmt->execute([$userId]);
            }
        }

        if ($this->tableExists($pdo, 'incident_assignments')) {
            if ($this->tableHasColumn($pdo, 'incident_assignments', 'assigned_by')) {
                $stmt = $pdo->prepare('UPDATE incident_assignments SET assigned_by = NULL WHERE assigned_by = ?');
                $stmt->execute([$userId]);
            }

            if ($this->tableHasColumn($pdo, 'incident_assignments', 'user_id')) {
                $stmt = $pdo->prepare('DELETE FROM incident_assignments WHERE user_id = ?');
                $stmt->execute([$userId]);
            }
        }

        if ($this->tableHasColumn($pdo, 'planning_tasks', 'technician_id')) {
            $stmt = $pdo->prepare('UPDATE planning_tasks SET technician_id = NULL WHERE technician_id = ?');
            $stmt->execute([$userId]);
        }
    }

    private function tableExists(PDO $pdo, string $tableName): bool
    {
        $dbName = $pdo->query('SELECT DATABASE()')->fetchColumn();
        if (!$dbName) {
            return false;
        }

        $stmt = $pdo->prepare('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?');
        $stmt->execute([$dbName, $tableName]);

        return (int)$stmt->fetchColumn() > 0;
    }

    private function tableHasColumn(PDO $pdo, string $tableName, string $columnName): bool
    {
        $dbName = $pdo->query('SELECT DATABASE()')->fetchColumn();
        if (!$dbName) {
            return false;
        }

        $stmt = $pdo->prepare('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?');
        $stmt->execute([$dbName, $tableName, $columnName]);

        return (int)$stmt->fetchColumn() > 0;
    }

    private function ensureUserPhotoColumn(PDO $pdo): void
    {
        if (!$this->tableHasColumn($pdo, 'users', 'photo_path')) {
            $pdo->exec('ALTER TABLE users ADD COLUMN photo_path VARCHAR(255) NULL AFTER active');
        }
    }

    private function ensureTechnicianTypeColumn(PDO $pdo): void
    {
        if (!$this->tableHasColumn($pdo, 'users', 'technician_type')) {
            $pdo->exec('ALTER TABLE users ADD COLUMN technician_type VARCHAR(50) NULL AFTER role_key');
        }
    }

    private function ensureAssignedCityColumn(PDO $pdo): void
    {
        if (!$this->tableHasColumn($pdo, 'users', 'assigned_city')) {
            $pdo->exec('ALTER TABLE users ADD COLUMN assigned_city VARCHAR(120) NULL AFTER technician_type');
        }
    }

    private function normalizeTechnicianType(mixed $rawValue, string $roleKey): ?string
    {
        if (!in_array($roleKey, self::TYPED_USER_ROLES, true)) {
            return null;
        }

        $value = strtolower(trim((string)$rawValue));
        if (in_array($roleKey, ['agent', 'superviseur', 'supervisor'], true) && in_array($value, ['etude', 'raccordement'], true)) {
            $value = 'etude_raccordement';
        }

        $allowedTypes = self::TECHNICIAN_TYPE_OPTIONS_BY_ROLE[$roleKey] ?? [];
        if ($value === '' || !in_array($value, $allowedTypes, true)) {
            return null;
        }

        return $value;
    }

    private function normalizeStoredTechnicianTypeForRole(mixed $rawValue, string $roleKey): ?string
    {
        $value = strtolower(trim((string)$rawValue));
        if ($value === '') {
            return null;
        }

        if (in_array($roleKey, ['agent', 'superviseur', 'supervisor'], true) && in_array($value, ['etude', 'raccordement'], true)) {
            return 'etude_raccordement';
        }

        return $value;
    }

    private function normalizeAssignedCity(mixed $rawValue): ?string
    {
        $value = trim((string)$rawValue);
        return $value === '' ? null : $value;
    }

    private function storeUserPhoto(int $userId, ?array $file, ?string $currentPath): ?string
    {
        if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
            return $currentPath;
        }

        $ext = strtolower(pathinfo((string)($file['name'] ?? ''), PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp'], true)) {
            return $currentPath;
        }

        $baseDir = Config::publicPath() . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'users' . DIRECTORY_SEPARATOR . $userId;
        if (!is_dir($baseDir)) {
            @mkdir($baseDir, 0777, true);
        }

        $fileName = 'avatar-' . bin2hex(random_bytes(4)) . '.' . $ext;
        $destination = $baseDir . DIRECTORY_SEPARATOR . $fileName;
        if (!@move_uploaded_file($file['tmp_name'], $destination)) {
            return $currentPath;
        }

        if (!empty($currentPath)) {
            $oldFile = Config::publicPath() . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . ltrim(str_replace('/', DIRECTORY_SEPARATOR, $currentPath), DIRECTORY_SEPARATOR);
            if (is_file($oldFile)) {
                @unlink($oldFile);
            }
        }

        return 'uploads/users/' . $userId . '/' . $fileName;
    }

    private function resolveUserPhotoUrl(?string $rawPath): ?string
    {
        $normalized = trim((string)$rawPath);
        if ($normalized === '') {
            return null;
        }

        if (preg_match('~^https?://~i', $normalized)) {
            return $normalized;
        }

        if (str_starts_with($normalized, 'storage/uploads/')) {
            $normalized = substr($normalized, strlen('storage/uploads/'));
        } elseif (str_starts_with($normalized, 'uploads/')) {
            $normalized = substr($normalized, strlen('uploads/'));
        }

        return upload_url($normalized);
    }
}
