<?php
namespace App\Controllers;

use App\Core\{Auth, Response, Session};
use App\Models\User;
use Throwable;

class LanguageController extends BaseController
{
    public function set(): Response
    {
        $input = $this->input();
        $lang = strtolower(trim((string) ($input['lang'] ?? '')));
        $supported = $this->config['supported_languages'] ?? $this->config['supported_langs'] ?? ['tr'];

        if (!in_array($lang, $supported, true)) {
            return Response::json([
                'ok' => false,
                'message' => 'Unsupported language.',
                'supported' => $supported,
            ], 422);
        }

        Session::put('lang', $lang);
        $this->setLanguageCookie($lang);

        if (Auth::check()) {
            try {
                (new User())->updateLanguage((int) Auth::id(), $lang);
                Auth::setSessionLanguage($lang);
            } catch (Throwable) {
                return Response::json([
                    'ok' => false,
                    'message' => 'Language could not be saved.',
                ], 500);
            }
        }

        return Response::json(['ok' => true, 'lang' => $lang]);
    }

    private function input(): array
    {
        $raw = file_get_contents('php://input') ?: '';
        $json = json_decode($raw, true);

        return is_array($json) ? $json : $_POST;
    }

    private function setLanguageCookie(string $lang): void
    {
        $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

        setcookie('lang', $lang, [
            'expires' => time() + 31536000,
            'path' => '/',
            'secure' => $secure,
            'httponly' => false,
            'samesite' => 'Lax',
        ]);
    }
}
