<?php

require __DIR__ . '/../vendor/autoload.php';

use FrameworkX\App;
use Libs\ResponseLib;
use Middlewares\CorsMiddleware;
use Middlewares\JwtAuthMiddleware;
use Psr\Http\Message\ServerRequestInterface;

$requestUri = $_SERVER['REQUEST_URI'] ?? null;
$path = $requestUri !== null ? parse_url($requestUri, PHP_URL_PATH) : '/';
$file = __DIR__ . $path;
if (php_sapi_name() === 'cli-server' && is_file($file)) {
    return false;
}

if (class_exists(Dotenv\Dotenv::class) && file_exists(__DIR__ . '/../.env')) {
    Dotenv\Dotenv::createImmutable(
        dirname(__DIR__),
        null,
        true
    )->safeLoad();
}

error_reporting(E_ALL);

$dsn = $_ENV['DB_DSN'] ?? (function () {
    $host = $_ENV['DB_HOST'] ?? 'localhost';
    $port = $_ENV['DB_PORT'] ?? '5432';
    $name = $_ENV['DB_NAME'] ?? 'postgres';
    return "pgsql:host={$host};port={$port};dbname={$name}";
})();
$dbUser = $_ENV['DB_USER'] ?? 'postgres';
$dbPass = $_ENV['DB_PASSWORD'] ?? '';
$GLOBALS['pdo'] = new \PDO($dsn, $dbUser, $dbPass);
$GLOBALS['pdo']->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

$corsEnabled = filter_var($_ENV['CORS'] ?? 'false', FILTER_VALIDATE_BOOLEAN);
$globalMiddleware = $corsEnabled ? [CorsMiddleware::class] : [];

$app = new App(...$globalMiddleware);
$authJwt = new JwtAuthMiddleware();

$onlyCompany1Or2 = function (ServerRequestInterface $request, callable $next) {
    $companyId = (int)($request->getAttribute('api_company_id') ?? 0);
    if ($companyId !== 1 && $companyId !== 2) {
        return ResponseLib::sendFail('Forbidden', [], 'E_FORBIDDEN')->withStatus(403);
    }

    return $next($request);
};

$app->post('/verify/jwt', $authJwt,\Controllers\HelloController::class);

$app->post('/login', \Controllers\LoginController::class);
$app->post('/register', $authJwt, \Controllers\RegisterController::class);
$app->post('/auth/superadmin', $authJwt, \Controllers\SuperAdminGetController::class);
$app->post('/user/get', $authJwt, \Controllers\UserGetController::class);
$app->post('/user/info', $authJwt, \Controllers\UserInfoController::class);
$app->post('/user/delete', $authJwt, \Controllers\UserDeleteController::class);

// Public endpoint to create company, user, and wallet in a single transaction
$app->post('/company/user/create', \Controllers\CompanyWithUserController::class);
$app->post('/company/user/kyc/status', \Controllers\CompanyCheckStatus::class);
$app->post('/user/kyc/status', \Controllers\UserCheckStatus::class);

// Authenticated user profile updates
$app->post('/user/change-email', $authJwt, \Controllers\UserChangeEmailController::class);
$app->post('/user/change-password', $authJwt, \Controllers\UserChangePasswordController::class);

// Commodities (JWT-protected)
$app->post('/commodity/create', $authJwt, \Controllers\CommodityCreateController::class);
$app->post('/commodity/update', $authJwt, \Controllers\CommodityUpdateController::class);
$app->post('/commodity/delete', $authJwt, \Controllers\CommodityDeleteController::class);
$app->post('/commodities/get', $authJwt, \Controllers\CommoditiesGetController::class);

// CPR registration
$app->post('/cpr/create', $authJwt, \Controllers\RegisterCprController::class);

// CPR history
$app->post('/cpr/history', $authJwt, \Controllers\CprQueryController::class);

$app->post('/wallet/tokens', $authJwt, \Controllers\WalletTokensController::class);
$app->post('/company/summary', $authJwt, \Controllers\CompanySummaryController::class);
$app->post('/token/get', $authJwt, \Controllers\TokenGetController::class);
$app->post('/token/orderbook', $authJwt, \Controllers\TokenOrderbookController::class);
$app->post('/orderbook/filter', $authJwt, \Controllers\OrderbookFilterController::class);
$app->post('/orderbook/payment', $authJwt, \Controllers\OrderbookPaymentController::class);
$app->post('/orderbook/cancel', $authJwt, \Controllers\OrderbookUpdateStatusController::class);
$app->post('/orderbook/transfer', $authJwt, \Controllers\OrderbookTransferController::class);
$app->post('/harvest/list', $authJwt, \Controllers\HarvestListController::class);

// Documents (JWT-protected)
$app->post('/documents/list', $authJwt, \Controllers\DocumentListController::class);
$app->post('/documents/upload', $authJwt, \Controllers\DocumentUploadController::class);
$app->post('/documents/download', $authJwt, \Controllers\DocumentDownloadController::class);

$app->post('/discount/get', $authJwt, $onlyCompany1Or2, \Controllers\DiscountGetController::class);
$app->post('/discount/create', $authJwt, $onlyCompany1Or2, \Controllers\DiscountCreateController::class);
$app->post('/discount/delete', $authJwt, $onlyCompany1Or2, \Controllers\DiscountDeleteController::class);

$app->post('/b3/token', \Controllers\B3TokenController::class);
$app->post('/b3/cpr/register', $authJwt, $onlyCompany1Or2, \Controllers\B3CprRegisterController::class);
$app->post('/b3/payment/confirm', $authJwt, \Controllers\PaymentConfirmController::class);
$app->post('/cpr/fast-track', \Controllers\CprFastTrackController::class);

// CPR monitoring
$app->post('/cpr/monitoring/create', $authJwt, \Controllers\CprMonitoringCreateController::class);
$app->post('/cpr/monitoring/get', $authJwt, \Controllers\CprMonitoringGetController::class);
$app->post('/cpr/monitoring/list', $authJwt, \Controllers\CprMonitoringListController::class);
$app->post('/cpr/monitoring/update', $authJwt, \Controllers\CprMonitoringUpdateController::class);
$app->post('/cpr/monitoring/delete', $authJwt, \Controllers\CprMonitoringDeleteController::class);

$app->run();