<?php
function app_public_base_url(): string {
    static $base = null;
    if ($base !== null) return $base;
    $cfgPath = __DIR__.'/../config/config.php';
    $cfg = is_file($cfgPath) ? require $cfgPath : [];
    $base = rtrim((string)($cfg['base_url'] ?? ''), '/');
    if ($base === '') {
        $https = !empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off';
        $scheme = $https ? 'https' : 'http';
        $host = (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
        $base = $scheme.'://'.$host;
    }
    return $base;
}

function profile_photo_url($value): ?string {
    $value = trim((string)($value ?? ''));
    if ($value === '') return null;

    $parts = @parse_url($value);
    if (is_array($parts)) {
        $query = [];
        if (!empty($parts['query'])) parse_str((string)$parts['query'], $query);
        if (($query['route'] ?? '') === 'media/profile' && !empty($query['file'])) {
            $file = basename((string)$query['file']);
            if (preg_match('/^[A-Za-z0-9._-]+\.(?:jpe?g|png|webp)$/i', $file)) {
                return app_public_base_url().'/api/public/index.php?route=media%2Fprofile&file='.rawurlencode($file);
            }
        }

        $path = (string)($parts['path'] ?? '');
        if (preg_match('~/(?:api/public/)?uploads/profile/([^/?#]+)$~i', $path, $m)) {
            $file = basename(rawurldecode($m[1]));
            if (preg_match('/^[A-Za-z0-9._-]+\.(?:jpe?g|png|webp)$/i', $file)) {
                return app_public_base_url().'/api/public/index.php?route=media%2Fprofile&file='.rawurlencode($file);
            }
        }
    }

    $candidate = basename(rawurldecode($value));
    if (preg_match('/^[A-Za-z0-9._-]+\.(?:jpe?g|png|webp)$/i', $candidate) &&
        (strpos($value, 'uploads/profile') !== false || strpos($value, '/') === false)) {
        return app_public_base_url().'/api/public/index.php?route=media%2Fprofile&file='.rawurlencode($candidate);
    }

    return $value;
}

function normalize_photo_urls($data) {
    if (!is_array($data)) return $data;
    foreach ($data as $key => $value) {
        if ((string)$key === 'photo_url') {
            $data[$key] = profile_photo_url($value);
        } elseif (is_array($value)) {
            $data[$key] = normalize_photo_urls($value);
        }
    }
    return $data;
}

function json_response($data, int $status = 200): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    $data = normalize_photo_urls($data);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function input_json(): array {
    $raw = file_get_contents('php://input');
    if (!$raw) return [];
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function bearer_token(): ?string {
    $h = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if ($h === '' && function_exists('getallheaders')) {
        $headers = getallheaders();
        $h = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    }
    return preg_match('/Bearer\s+(\S+)/i', $h, $m) ? $m[1] : null;
}

function clean_string($v, int $max = 255): string {
    $value = trim((string)$v);
    return function_exists('mb_substr') ? mb_substr($value, 0, $max) : substr($value, 0, $max);
}

function bool_int($value): int {
    if (is_bool($value)) return $value ? 1 : 0;
    if (is_numeric($value)) return ((int)$value) ? 1 : 0;
    return in_array(strtolower(trim((string)$value)), ['1','true','yes','on'], true) ? 1 : 0;
}

function public_user(array $u): array {
    return [
        'id' => (int)$u['id'],
        'name' => (string)($u['name'] ?? ''),
        'email' => $u['email'] ?? null,
        'phone' => (string)($u['phone'] ?? ''),
        'blood_group' => $u['blood_group'] ?? null,
        'district' => $u['district'] ?? null,
        'photo_url' => profile_photo_url($u['photo_url'] ?? null),
        'status' => (string)($u['status'] ?? 'active'),
        'verified' => (int)($u['verified'] ?? 0),
        'created_at' => $u['created_at'] ?? null,
        'last_login_at' => $u['last_login_at'] ?? null,
    ];
}

function require_admin(): array {
    $token = bearer_token();
    if (!$token) json_response(['message'=>'Unauthorized'], 401);
    $s = db()->prepare('SELECT id,name,email FROM admins WHERE token=? LIMIT 1');
    $s->execute([$token]);
    $admin = $s->fetch();
    if (!$admin) json_response(['message'=>'Unauthorized'], 401);
    return $admin;
}

function optional_user(): ?array {
    $token = bearer_token();
    if (!$token) return null;
    $s = db()->prepare('SELECT * FROM users WHERE token=? LIMIT 1');
    $s->execute([$token]);
    $u = $s->fetch();
    if (!$u) return null;
    return $u;
}

function require_user(): array {
    $token = bearer_token();
    if (!$token) json_response(['message'=>'আগে লগইন করুন'], 401);
    $s = db()->prepare('SELECT * FROM users WHERE token=? LIMIT 1');
    $s->execute([$token]);
    $u = $s->fetch();
    if (!$u) json_response(['message'=>'সেশন শেষ হয়েছে, আবার লগইন করুন'], 401);
    if (($u['status'] ?? 'active') !== 'active') {
        json_response(['message'=>'আপনার একাউন্টটি অ্যাডমিন ব্লক করেছেন'], 403);
    }
    return $u;
}
