<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

date_default_timezone_set('Europe/Istanbul');

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Visitor-Hash');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

require_once __DIR__ . '/../src/Utils/Env.php';

\App\Utils\Env::load(__DIR__ . '/../../.env');

spl_autoload_register(function ($class) {
    $prefix = 'App\\';
    $baseDir = __DIR__ . '/../src/';
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relativeClass = substr($class, $len);
    $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
});

// Otomatik migration: frame/boost sütunlarını oluştur (yoksa)
\App\Utils\AutoMigrate::run();

$router = new \App\Core\Router();

$router->post('/api/auth/register', [\App\Controllers\AuthController::class, 'register']);
$router->post('/api/auth/login', [\App\Controllers\AuthController::class, 'login']);

$router->post('/api/anon/start', [\App\Controllers\AnonController::class, 'start']);

$router->post('/api/reports', [\App\Controllers\ReportController::class, 'create']);
$router->post('/reports', [\App\Controllers\ReportController::class, 'create']);

$router->post('/api/blocks/toggle', [\App\Controllers\BlockController::class, 'toggle']);
$router->post('/api/blocks/status', [\App\Controllers\BlockController::class, 'status']);
$router->post('/blocks/toggle', [\App\Controllers\BlockController::class, 'toggle']);
$router->post('/blocks/status', [\App\Controllers\BlockController::class, 'status']);

$router->post('/api/admin/auth/login', [\App\Controllers\AdminAuthController::class, 'login']);

$router->get('/api/admin/dashboard/stats', [\App\Controllers\AdminController::class, 'getDashboardStats']);

$router->get('/api/admin/users', [\App\Controllers\AdminController::class, 'getUsers']);
$router->get('/api/admin/users/{id}', [\App\Controllers\AdminController::class, 'getUserDetails']);
$router->get('/api/admin/users/{id}/conversations', [\App\Controllers\AdminController::class, 'getUserConversations']);
$router->post('/api/admin/users/{id}/ban', [\App\Controllers\AdminController::class, 'banUser']);
$router->post('/api/admin/users/{id}/unban', [\App\Controllers\AdminController::class, 'unbanUser']);
$router->post('/api/admin/users/{id}/subscription', [\App\Controllers\AdminController::class, 'updateSubscription']);
$router->post('/api/admin/users/{id}/boost', [\App\Controllers\AdminController::class, 'addBoost']);
$router->delete('/api/admin/users/{id}', [\App\Controllers\AdminController::class, 'deleteUser']);

$router->get('/api/admin/conversations', [\App\Controllers\AdminController::class, 'getAllConversations']);
$router->get('/api/admin/conversations/{id}/messages', [\App\Controllers\AdminController::class, 'getConversationMessages']);

$router->post('/api/admin/messages/send', [\App\Controllers\AdminController::class, 'sendMessageAsAdmin']);
$router->delete('/api/admin/messages/{id}', [\App\Controllers\AdminController::class, 'deleteMessage']);

$router->get('/api/admin/reports', [\App\Controllers\AdminController::class, 'getReports']);
$router->post('/api/admin/reports/{id}/close', [\App\Controllers\AdminController::class, 'closeReport']);

$router->get('/api/admin/stories', [\App\Controllers\AdminController::class, 'getStories']);
$router->delete('/api/admin/stories/{id}', [\App\Controllers\AdminController::class, 'deleteStory']);

$router->get('/api/admin/subscriptions', [\App\Controllers\AdminController::class, 'getSubscriptions']);
$router->post('/api/admin/broadcast', [\App\Controllers\AdminController::class, 'broadcast']);

$router->get('/api/admin/seed-users', [\App\Controllers\SeedUserController::class, 'index']);
$router->post('/api/admin/seed-users', [\App\Controllers\SeedUserController::class, 'create']);
$router->put('/api/admin/seed-users/{id}', [\App\Controllers\SeedUserController::class, 'update']);
$router->delete('/api/admin/seed-users/{id}', [\App\Controllers\SeedUserController::class, 'delete']);
$router->get('/api/admin/seed-users/{id}/inbox', [\App\Controllers\SeedUserController::class, 'getInbox']);
$router->get('/api/admin/seed-users/{id}/stats', [\App\Controllers\SeedUserController::class, 'getStats']);
$router->post('/api/admin/seed-users/{id}/message', [\App\Controllers\SeedUserController::class, 'message']);

$router->get('/seed_users', [\App\Controllers\SeedUserController::class, 'index']);
$router->post('/seed_users', [\App\Controllers\SeedUserController::class, 'create']);
$router->post('/seed_users/delete', [\App\Controllers\SeedUserController::class, 'delete']);
$router->post('/seed_users/mark_read', [\App\Controllers\SeedUserController::class, 'markRead']);
$router->get('/seed_users/{id}/inbox', [\App\Controllers\SeedUserController::class, 'inbox']);
$router->get('/seed_users/messages/{convId}', [\App\Controllers\SeedUserController::class, 'messages']);
$router->post('/seed_users/reply', [\App\Controllers\SeedUserController::class, 'reply']);

$router->get('/u/{slug}', [\App\Controllers\ProfileController::class, 'shareLanding']);

$router->get('/api/_version', function () {
    echo json_encode([
        'php' => PHP_VERSION,
        'time' => date('Y-m-d H:i:s'),
        'files' => [
            'index.php' => filemtime(__FILE__),
            'AnonController.php' => @filemtime(__DIR__ . '/../src/Controllers/AnonController.php'),
            'ConversationController.php' => @filemtime(__DIR__ . '/../src/Controllers/ConversationController.php'),
            'MessageController.php' => @filemtime(__DIR__ . '/../src/Controllers/MessageController.php'),
            'AuthMiddleware.php' => @filemtime(__DIR__ . '/../src/Middleware/AuthMiddleware.php'),
        ],
    ]);
});

$router->post('/api/billing/verify', [\App\Controllers\BillingController::class, 'verify']);
$router->post('/api/billing/boost', [\App\Controllers\BillingController::class, 'boost']);
$router->get('/api/billing/status', [\App\Controllers\BillingController::class, 'status']);
$router->post('/api/billing/restore', [\App\Controllers\BillingController::class, 'restore']);

$router->get('/api/shuffle', [\App\Controllers\DiscoveryController::class, 'shuffle']);

$router->get('/api/conversations', [\App\Controllers\ConversationController::class, 'index']);
$router->get('/api/conversations/{id}', [\App\Controllers\ConversationController::class, 'show']);
$router->post('/api/conversations/{id}/clear', [\App\Controllers\ConversationController::class, 'clear']);
$router->post('/api/conversations/clear_all', [\App\Controllers\ConversationController::class, 'clearAll']);
$router->get('/api/conversations/{conversationId}/messages', [\App\Controllers\MessageController::class, 'index']);

$router->post('/api/messages/send', [\App\Controllers\MessageController::class, 'send']);
$router->get('/api/messages/since', [\App\Controllers\MessageController::class, 'since']);
$router->post('/api/messages/read', [\App\Controllers\MessageController::class, 'read']);

$router->get('/api/me', [\App\Controllers\ProfileController::class, 'me']);
$router->post('/api/me/reward_messages', [\App\Controllers\ProfileController::class, 'rewardMessages']);
$router->put('/api/me', [\App\Controllers\ProfileController::class, 'update']);
$router->get('/api/users/{id}', [\App\Controllers\ProfileController::class, 'getUser']);
$router->get('/api/users/slug/{slug}', [\App\Controllers\ProfileController::class, 'getUserBySlug']);

$router->post('/api/profile/onboarding', [\App\Controllers\ProfileController::class, 'updateOnboarding']);

$router->get('/api/stories/feed', [\App\Controllers\StoryController::class, 'feed']);

$router->get('/api/stories/feed', [\App\Controllers\StoryController::class, 'feed']);
$router->post('/api/stories', [\App\Controllers\StoryController::class, 'create']);
$router->get('/api/users/{id}/stories', [\App\Controllers\StoryController::class, 'getUserStories']);
$router->post('/api/stories/{id}/comments', [\App\Controllers\StoryController::class, 'comment']);
$router->get('/api/stories/{id}/comments', [\App\Controllers\StoryController::class, 'getComments']);
$router->delete('/api/comments/{id}', [\App\Controllers\StoryController::class, 'deleteComment']);
$router->delete('/api/stories/{id}', [\App\Controllers\StoryController::class, 'delete']);

$router->post('/api/upload/avatar', [\App\Controllers\UploadController::class, 'avatar']);

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$startsWith = function ($haystack, $needle) {
    if ($needle === '') return true;
    return substr($haystack, 0, strlen($needle)) === $needle;
};

if ($scriptDir !== '/' && $scriptDir !== '.' && $startsWith($uri, $scriptDir)) {
    $uri = substr($uri, strlen($scriptDir));
    if ($uri === '') {
        $uri = '/';
    }
}

$router->dispatch($_SERVER['REQUEST_METHOD'], $uri);
