<?php

// Set charset and encoding for proper Turkish character support
header('Content-Type: text/html; charset=UTF-8');
mb_internal_encoding('UTF-8');
ini_set('default_charset', 'UTF-8');

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Define paths
define('ROOT_PATH', dirname(__DIR__));
define('APP_PATH', ROOT_PATH . '/app');

// Include autoloader
require_once APP_PATH . '/core/Autoloader.php';
spl_autoload_register(['App\Core\Autoloader', 'autoload']);

// Include required files
require_once APP_PATH . '/controllers/AuthController.php';
require_once APP_PATH . '/models/User.php';

// Simple router
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$requestMethod = $_SERVER['REQUEST_METHOD'];

// Remove trailing slash except for root
if ($requestUri !== '/' && substr($requestUri, -1) === '/') {
    $requestUri = substr($requestUri, 0, -1);
}

// Start session first
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Handle theme assets (static files) - must be before any other routing
if (preg_match('/^\/themes\/([^\/]+)\/(.+)$/', $requestUri, $matches)) {
    $themeName = $matches[1];
    $assetPath = $matches[2];
    $fullPath = ROOT_PATH . "/themes/{$themeName}/{$assetPath}";
    
    if (file_exists($fullPath) && !is_dir($fullPath)) {
        // Get file extension for proper MIME type
        $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
        $mimeTypes = [
            'css' => 'text/css',
            'js' => 'application/javascript',
            'png' => 'image/png',
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'gif' => 'image/gif',
            'svg' => 'image/svg+xml',
            'ico' => 'image/x-icon',
            'woff' => 'font/woff',
            'woff2' => 'font/woff2',
            'ttf' => 'font/ttf',
            'eot' => 'application/vnd.ms-fontobject'
        ];
        
        $mimeType = $mimeTypes[$ext] ?? 'application/octet-stream';
        
        header("Content-Type: {$mimeType}");
        header('Cache-Control: public, max-age=31536000'); // 1 year cache
        readfile($fullPath);
        exit;
    } else {
        http_response_code(404);
        echo "Asset not found: {$assetPath}";
        exit;
    }
}

// Determine if this is an admin request
$isAdminRequest = (strpos($requestUri, '/admin') === 0);
$isApiRequest = (strpos($requestUri, '/api') === 0);
$isAuthRequest = (strpos($requestUri, '/auth') === 0 || $requestUri === '/login');

// Public API routes (no auth required)
if (strpos($requestUri, '/api/analytics/') === 0) {
    $analyticsRoute = substr($requestUri, 15); // Remove '/api/analytics/'
    
    // Parse query parameters for routes like 'chart-data?period=7days'
    $routeParts = explode('?', $analyticsRoute);
    $routeName = $routeParts[0];
    
    require_once APP_PATH . '/core/Database.php';
    require_once APP_PATH . '/core/AuthHelper.php';
    require_once APP_PATH . '/models/Analytics.php';
    
    switch ($routeName) {
        case 'track':
        case 'update-time':
            require_once APP_PATH . '/controllers/AnalyticsController.php';
            $controller = new \App\Controllers\AnalyticsController();
            if ($routeName === 'track') {
                $controller->track();
            } else {
                $controller->updateTimeOnPage();
            }
            break;
        case 'realtime':
        case 'chart-data':
        case 'device-stats':
        case 'hourly-visitors':
        case 'referrer-stats':
        case 'detailed-page-analytics':
            require_once APP_PATH . '/controllers/AnalyticsController.php';
            $controller = new \App\Controllers\AnalyticsController();
            switch ($routeName) {
                case 'realtime':
                    $controller->realtime();
                    break;
                case 'chart-data':
                    $controller->chartData();
                    break;
                case 'device-stats':
                    $controller->deviceStats();
                    break;
                case 'hourly-visitors':
                    $controller->hourlyVisitors();
                    break;
                case 'referrer-stats':
                    $controller->referrerStats();
                    break;
                case 'detailed-page-analytics':
                    $controller->detailedPageAnalytics();
                    break;
            }
            break;
        default:
            http_response_code(404);
            echo json_encode(['error' => 'Analytics endpoint not found: ' . $routeName]);
    }
    exit;
}

// Authentication routes (no auth required)
if ($isAuthRequest) {
    if ($requestUri === '/auth/login' || $requestUri === '/login') {
        require_once APP_PATH . '/controllers/AuthController.php';
        $authController = new AuthController();
        $authController->login();
        exit;
    }
    
    if ($requestUri === '/auth/logout') {
        require_once APP_PATH . '/controllers/AuthController.php';
        $authController = new AuthController();
        $authController->logout();
        exit;
    }
}

// Admin panel routes (require authentication)
if ($isAdminRequest || $requestUri === '/admin') {
    
    // Check if user is logged in for admin routes
    if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
        header('Location: /login');
        exit;
    }
    
    // Remove /admin prefix for routing
    $adminUri = $requestUri === '/admin' ? '/' : substr($requestUri, 6); // Remove '/admin'
    
    switch ($adminUri) {
        case '/':
        case '/dashboard':
            require_once APP_PATH . '/controllers/DashboardController.php';
            $controller = new DashboardController();
            $controller->index();
            break;
            
        case '/activities':
            require_once APP_PATH . '/controllers/DashboardController.php';
            $controller = new DashboardController();
            $controller->activities();
            break;
            
        case '/users':
            include APP_PATH . '/views/admin/user/index.php';
            break;
            
        case '/users/create':
            include APP_PATH . '/views/admin/user/create.php';
            break;
            
        case '/users/edit':
            include APP_PATH . '/views/admin/user/edit.php';
            break;
            
        case '/settings':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->index();
            break;
            
        case '/settings/update':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->update();
            break;
            
        case '/settings/update-single':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->updateSingle();
            break;
            
        case '/settings/delete':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->delete();
            break;
            
        case '/settings/toggle-maintenance':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->toggleMaintenance();
            break;
            
        case '/settings/export':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->export();
            break;
            
        case '/settings/clear-cache':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->clearCache();
            break;
            
        case '/settings/test-mail':
            require_once APP_PATH . '/controllers/SettingsController.php';
            $controller = new SettingsController();
            $controller->testMail();
            break;
            
        case '/languages':
            require_once APP_PATH . '/controllers/LanguageController.php';
            $controller = new LanguageController();
            $controller->index();
            break;
            
        case '/media':
            require_once APP_PATH . '/controllers/MediaController.php';
            $controller = new MediaController();
            $controller->index();
            break;
            
        case '/blueprints':
            require_once APP_PATH . '/controllers/BlueprintController.php';
            $controller = new BlueprintController();
            $controller->index();
            break;
            
        case '/blueprints/create':
            require_once APP_PATH . '/controllers/BlueprintController.php';
            $controller = new BlueprintController();
            $controller->create();
            break;
            
        case '/blueprints/docs':
            require_once APP_PATH . '/controllers/BlueprintController.php';
            $controller = new BlueprintController();
            $controller->docs();
            break;
            
        case '/theme-editor':
            require_once APP_PATH . '/controllers/ThemeEditorController.php';
            $controller = new ThemeEditorController();
            $controller->index();
            break;
            
        case '/analytics':
            require_once APP_PATH . '/core/Database.php';
            require_once APP_PATH . '/models/Analytics.php';
            require_once APP_PATH . '/controllers/AnalyticsController.php';
            $controller = new \App\Controllers\AnalyticsController();
            $controller->index();
            break;
            
        case '/analytics/settings':
            require_once APP_PATH . '/core/Database.php';
            require_once APP_PATH . '/models/Analytics.php';
            require_once APP_PATH . '/controllers/AnalyticsController.php';
            $controller = new \App\Controllers\AnalyticsController();
            $controller->settings();
            break;
            
        case '/login':
            require_once APP_PATH . '/controllers/AuthController.php';
            $authController = new AuthController();
            $authController->login();
            break;
            
        case '/get-relation-options':
            require_once APP_PATH . '/controllers/DynamicContentController.php';
            // Handle blueprint'i al (ilk parameter blueprint olmalı ama genel endpoint olduğu için pages-page default kullan)
            $targetBlueprint = $_GET['target'] ?? 'pages-page';
            $controller = new DynamicContentController($targetBlueprint);
            $controller->getRelationOptions();
            break;
            
        case '/api/pagefinder-content':
            require_once APP_PATH . '/controllers/ApiController.php';
            $controller = new ApiController();
            $controller->pagefinderContent();
            break;
            

            
        case '/api/available-blueprints':
            require_once APP_PATH . '/controllers/ApiController.php';
            $controller = new ApiController();
            $controller->availableBlueprints();
            break;
            
        case '/api/recordfinder-content':
            require_once APP_PATH . '/controllers/ApiController.php';
            $controller = new ApiController();
            $controller->recordfinderContent();
            break;
            
        case '/api/analytics/pages':
            // Check authentication for admin-only endpoints
            if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
                http_response_code(401);
                echo json_encode(['error' => 'Unauthorized']);
                break;
            }
            require_once APP_PATH . '/core/Database.php';
            require_once APP_PATH . '/models/Analytics.php';
            require_once APP_PATH . '/controllers/AnalyticsController.php';
            $controller = new \App\Controllers\AnalyticsController();
            $controller->pages();
            break;
            
        case '/users':
            if ($requestMethod === 'POST') {
                // Handle AJAX delete request
                require_once APP_PATH . '/views/admin/user/index.php';
            } else {
                // Show users index page
                require_once APP_PATH . '/views/admin/user/index.php';
            }
            break;
            
        case '/users/create':
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                require_once APP_PATH . '/models/User.php';
                $userModel = new User();
                $data = [];
                
                // Collect form data
                if (isset($_POST['first_name'])) $data['first_name'] = $_POST['first_name'];
                if (isset($_POST['last_name'])) $data['last_name'] = $_POST['last_name'];
                if (isset($_POST['username'])) $data['username'] = $_POST['username'];
                if (isset($_POST['email'])) $data['email'] = $_POST['email'];
                if (isset($_POST['password'])) $data['password'] = $_POST['password'];
                if (isset($_POST['role'])) $data['role'] = $_POST['role'];
                if (isset($_POST['status'])) $data['status'] = $_POST['status'];
                
                // Handle avatar upload
                if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
                    $uploadDir = __DIR__ . '/uploads/avatars/';
                    if (!file_exists($uploadDir)) {
                        mkdir($uploadDir, 0755, true);
                    }
                    
                    $fileExtension = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
                    $allowedExtensions = ['jpg', 'jpeg', 'png'];
                    
                    if (in_array($fileExtension, $allowedExtensions) && $_FILES['avatar']['size'] <= 2 * 1024 * 1024) {
                        $fileName = uniqid() . '.' . $fileExtension;
                        $filePath = $uploadDir . $fileName;
                        
                        if (move_uploaded_file($_FILES['avatar']['tmp_name'], $filePath)) {
                            $data['avatar'] = $fileName;
                        }
                    }
                }
                
                // Create user
                if ($userModel->createUser($data)) {
                    header('Location: /admin/users?success=1');
                    exit;
                } else {
                    $error = "Kullanıcı oluşturulurken bir hata oluştu.";
                }
            }
            
            require_once APP_PATH . '/views/admin/user/create.php';
            break;
            
        case '/users/edit':
            if (isset($_GET['id']) && is_numeric($_GET['id'])) {
                $userId = (int)$_GET['id'];
                require_once APP_PATH . '/models/User.php';
                $userModel = new User();
                $user = $userModel->findById($userId);
                
                if (!$user) {
                    header('Location: /admin/users');
                    exit;
                }
                
                // Handle form submission
                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    $data = [];
                    
                    // Collect form data
                    if (isset($_POST['first_name'])) $data['first_name'] = $_POST['first_name'];
                    if (isset($_POST['last_name'])) $data['last_name'] = $_POST['last_name'];
                    if (isset($_POST['username'])) $data['username'] = $_POST['username'];
                    if (isset($_POST['email'])) $data['email'] = $_POST['email'];
                    if (isset($_POST['role'])) $data['role'] = $_POST['role'];
                    if (isset($_POST['status'])) $data['status'] = $_POST['status'];
                    
                    // Handle password update
                    if (!empty($_POST['password'])) {
                        $data['password'] = $_POST['password'];
                    }
                    
                    // Handle avatar upload
                    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
                        $uploadDir = __DIR__ . '/uploads/avatars/';
                        if (!file_exists($uploadDir)) {
                            mkdir($uploadDir, 0755, true);
                        }
                        
                        $fileExtension = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
                        $allowedExtensions = ['jpg', 'jpeg', 'png'];
                        
                        if (in_array($fileExtension, $allowedExtensions) && $_FILES['avatar']['size'] <= 2 * 1024 * 1024) {
                            $fileName = uniqid() . '.' . $fileExtension;
                            $filePath = $uploadDir . $fileName;
                            
                            if (move_uploaded_file($_FILES['avatar']['tmp_name'], $filePath)) {
                                // Remove old avatar if exists
                                if (!empty($user['avatar']) && file_exists($uploadDir . $user['avatar'])) {
                                    unlink($uploadDir . $user['avatar']);
                                }
                                $data['avatar'] = $fileName;
                            }
                        }
                    }
                    
                    // Handle avatar removal
                    if (isset($_POST['remove_avatar']) && $_POST['remove_avatar'] === '1') {
                        if (!empty($user['avatar']) && file_exists(__DIR__ . '/uploads/avatars/' . $user['avatar'])) {
                            unlink(__DIR__ . '/uploads/avatars/' . $user['avatar']);
                        }
                        $data['avatar'] = null;
                    }
                    
                    // Update user
                    if ($userModel->updateUser($userId, $data)) {
                        header('Location: /admin/users?success=1');
                        exit;
                    } else {
                        $error = "Kullanıcı güncellenirken bir hata oluştu.";
                    }
                }
                
                require_once APP_PATH . '/views/admin/user/edit.php';
            } else {
                header('Location: /admin/users');
                exit;
            }
            break;
            
        case '/auth/logout':
            require_once APP_PATH . '/controllers/AuthController.php';
            $authController = new AuthController();
            $authController->logout();
            break;
            
        default:
            // Check for dynamic content routes in admin
            if (preg_match('/^\/dynamic-content\/([^\/]+)(?:\/([^\/]+))?$/', $adminUri, $matches)) {
                $blueprintHandle = $matches[1];
                $action = $matches[2] ?? null;
                
                require_once APP_PATH . '/controllers/DynamicContentController.php';
                try {
                    $controller = new DynamicContentController($blueprintHandle);
                    
                    if ($action === 'create') {
                        $controller->create();
                    } elseif ($action === 'edit' && isset($_GET['id'])) {
                        $controller->edit();
                    } elseif ($action === 'save' && $requestMethod === 'POST') {
                        $controller->save();
                    } elseif ($action === 'sort' && $requestMethod === 'POST') {
                        $controller->sort();
                    } elseif ($action === 'tree-sort' && $requestMethod === 'POST') {
                        $controller->treeSort();
                    } elseif ($action === 'delete' && $requestMethod === 'DELETE') {
                        $controller->delete();
                    } elseif (is_numeric($action)) {
                        $controller->show($action);
                    } else {
                        $controller->index();
                    }
                } catch (Exception $e) {
                    http_response_code(404);
                    echo "<h1>404 - Blueprint Not Found</h1>";
                    echo "<p>The blueprint '{$blueprintHandle}' does not exist.</p>";
                    echo "<p><strong>Error:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
                    echo "<p><strong>File:</strong> " . htmlspecialchars($e->getFile()) . ":" . $e->getLine() . "</p>";
                    echo "<a href='/admin/dashboard'>Return to Dashboard</a>";
                }
                exit;
            }
            
            // Legacy blueprint routes (direct blueprint access without dynamic-content prefix)
            if (preg_match('/^\/([^\/]+)(?:\/([^\/]+))?$/', $adminUri, $matches)) {
                $blueprintHandle = $matches[1];
                $action = $matches[2] ?? null;
                
                require_once APP_PATH . '/controllers/DynamicContentController.php';
                try {
                    $controller = new DynamicContentController($blueprintHandle);
                    
                    if ($action === 'create') {
                        $controller->create();
                    } elseif ($action === 'edit' && isset($_GET['id'])) {
                        $controller->edit();
                    } elseif ($action === 'save' && $requestMethod === 'POST') {
                        $controller->save();
                    } elseif ($action === 'sort' && $requestMethod === 'POST') {
                        $controller->sort();
                    } elseif ($action === 'tree-sort' && $requestMethod === 'POST') {
                        $controller->treeSort();
                    } elseif ($action === 'delete' && $requestMethod === 'DELETE') {
                        $controller->delete();
                    } elseif (is_numeric($action)) {
                        $controller->show($action);
                    } else {
                        $controller->index();
                    }
                } catch (Exception $e) {
                    http_response_code(404);
                    echo "<h1>404 - Blueprint Not Found</h1>";
                    echo "<p>The blueprint '{$blueprintHandle}' does not exist.</p>";
                    echo "<p><strong>Error:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
                    echo "<p><strong>File:</strong> " . htmlspecialchars($e->getFile()) . ":" . $e->getLine() . "</p>";
                    echo "<a href='/admin/dashboard'>Return to Dashboard</a>";
                }
                exit;
            }
            
            http_response_code(404);
            echo "<h1>404 - Admin Page Not Found</h1>";
            echo "<p>The admin page you are looking for does not exist.</p>";
            echo "<a href='/admin/dashboard'>Return to Dashboard</a>";
            break;
    }
    exit;
}

// Image Optimize routes with clean URLs (no auth required): /opimage/{width}/{height}/{imagePath}
if (strpos($requestUri, '/opimage/') === 0) {
    // Parse clean URL format: /opimage/width/height/path/to/image.jpg
    $pathParts = explode('/', trim($requestUri, '/'));
    
    if (count($pathParts) >= 4 && $pathParts[0] === 'opimage') {
        $width = (int)$pathParts[1];
        $height = (int)$pathParts[2];
        $imagePath = implode('/', array_slice($pathParts, 3));
        
        require_once APP_PATH . '/controllers/ImageOptimizeController.php';
        $controller = new \App\Controllers\ImageOptimizeController();
        $controller->optimizeClean($width, $height, $imagePath);
        exit;
    } else {
        http_response_code(404);
        echo "Invalid image optimization URL format";
        exit;
    }
}

// API routes (require authentication for most)
if ($isApiRequest) {
    
    // Upload API route (no auth required for file uploads)
    if ($requestUri === '/api/upload') {
        require_once APP_PATH . '/controllers/UploadController.php';
        $controller = new UploadController();
        $controller->upload();
        exit;
    }
    
    // Blocks API routes (no auth required for block designer)
    if (strpos($requestUri, '/api/blocks/') === 0) {
        require_once APP_PATH . '/controllers/BlueprintController.php';
        $controller = new BlueprintController();
        
        switch ($requestUri) {
            case '/api/blocks/available':
                $controller->getAvailableBlocks();
                break;
            case '/api/blocks/definition':
                $controller->getBlockDefinition();
                break;
            case '/api/blocks/render-fields':
                // Handle block field rendering
                require_once APP_PATH . '/controllers/ApiController.php';
                $apiController = new ApiController();
                $apiController->renderBlockFields();
                break;
            default:
                http_response_code(404);
                echo json_encode(['error' => 'Blocks API endpoint not found']);
                break;
        }
        exit;
    }
    
    // Legacy Image Optimize API routes (keep for backward compatibility)
    if (strpos($requestUri, '/api/image-optimize') === 0) {
        require_once APP_PATH . '/controllers/ImageOptimizeController.php';
        $controller = new \App\Controllers\ImageOptimizeController();
        
        switch ($requestUri) {
            case '/api/image-optimize':
                $controller->optimize();
                break;
            case '/api/image-optimize/check-gd':
                $controller->checkGD();
                break;

            default:
                http_response_code(404);
                echo json_encode(['error' => 'Image optimize endpoint not found']);
                break;
        }
        exit;
    }
    
    // RecordFinder API routes (no auth required - used in admin forms)
    if ($requestUri === '/api/recordfinder-data') {
        $targetBlueprint = $_GET['target'] ?? null;
        if (!$targetBlueprint) {
            http_response_code(400);
            echo json_encode(['error' => 'Target blueprint is required']);
            exit;
        }
        
        try {
            require_once APP_PATH . '/controllers/DynamicContentController.php';
            $controller = new DynamicContentController($targetBlueprint);
            $controller->recordfinderData();
        } catch (Exception $e) {
            http_response_code(404);
            echo json_encode(['error' => 'Blueprint not found: ' . $targetBlueprint]);
        }
        exit;
    }
    
    // Check authentication for other API routes
    if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    
    // Blueprint API routes
    if (strpos($requestUri, '/api/blueprints/') === 0) {
        require_once APP_PATH . '/controllers/BlueprintController.php';
        $controller = new BlueprintController();
        
        switch ($requestUri) {
            case '/api/blueprints/list':
                $controller->list();
                break;
            case '/api/blueprints/get':
                $controller->get();
                break;
            case '/api/blueprints/save':
                $controller->save();
                break;
            case '/api/blueprints/delete':
                $controller->delete();
                break;
            case '/api/blueprints/migrate':
                $controller->migrate();
                break;
            case '/api/blueprints/migration-history':
                $controller->migrationHistory();
                break;
            case '/api/blueprints/rollback':
                $controller->rollback();
                break;
            case '/api/blueprints/global-history':
                $controller->globalHistory();
                break;
            case '/api/blueprints/available-blueprints':
                $controller->getAvailableBlueprints();
                break;
            case '/api/blueprints/relation-options':
                $controller->getRelationOptions();
                break;
            default:
                // Check for dynamic routes with parameters
                if (preg_match('/^\/api\/blueprints\/history-details\/(\d+)$/', $requestUri, $matches)) {
                    $_GET['id'] = $matches[1]; // Set the ID parameter
                    $controller->historyDetails();
                    break;
                }
                
                if ($requestUri === '/api/blueprints/history-details') {
                    $controller->historyDetails();
                    break;
                }
                
                http_response_code(404);
                echo json_encode(['error' => 'API endpoint not found']);
                break;
        }
        exit;
    }
    

    
    // Media API routes
    if (strpos($requestUri, '/api/media/') === 0) {
        require_once APP_PATH . '/controllers/MediaController.php';
        $controller = new MediaController();
        
        switch ($requestUri) {
            case '/api/media/list':
                $controller->list();
                break;
            case '/api/media/upload':
                $controller->upload();
                break;
            case '/api/media/delete':
                $controller->delete();
                break;
            case '/api/media/create-folder':
                $controller->createFolder();
                break;
            case '/api/media/navigate':
                $controller->navigate();
                break;
            case '/api/media/rename':
                $controller->rename();
                break;
            case '/api/media/move':
                $controller->move();
                break;
            case '/api/media/get-url':
                $controller->getUrl();
                break;
            default:
                http_response_code(404);
                echo json_encode(['error' => 'Media API endpoint not found']);
                break;
        }
        exit;
    }
    
    // Theme Editor API routes
    if (strpos($requestUri, '/api/theme-editor/') === 0) {
        require_once APP_PATH . '/controllers/ThemeEditorController.php';
        $controller = new ThemeEditorController();
        
        switch ($requestUri) {
            case '/api/theme-editor/get-file':
                $controller->getFile();
                break;
            case '/api/theme-editor/save':
                $controller->save();
                break;
            case '/api/theme-editor/create-file':
                $controller->createFile();
                break;
            default:
                http_response_code(404);
                echo json_encode(['error' => 'Theme Editor API endpoint not found']);
                break;
        }
        exit;
    }
    
    // PageFinder API routes
    if (strpos($requestUri, '/api/pagefinder-content') === 0 || strpos($requestUri, '/api/available-blueprints') === 0 || strpos($requestUri, '/api/available-blocks') === 0) {
        require_once APP_PATH . '/controllers/ApiController.php';
        $controller = new ApiController();
        
        switch ($requestUri) {
            case '/api/pagefinder-content':
                $controller->pagefinderContent();
                break;
            case '/api/available-blueprints':
                $controller->availableBlueprints();
                break;
            case '/api/available-blocks':
                $controller->availableBlocks();
                break;
            default:
                http_response_code(404);
                echo json_encode(['error' => 'PageFinder API endpoint not found']);
                break;
        }
        exit;
    }

    // Notification API routes
    if (strpos($requestUri, '/api/notifications') === 0) {
        require_once APP_PATH . '/controllers/ApiController.php';
        $controller = new ApiController();
        
        // Handle different HTTP methods
        $method = $_SERVER['REQUEST_METHOD'];
        
        if ($requestUri === '/api/notifications' && $method === 'GET') {
            $controller->notifications();
        } elseif ($requestUri === '/api/notifications' && $method === 'POST') {
            $controller->createNotification();
        } elseif ($requestUri === '/api/notifications/mark-all-read' && $method === 'POST') {
            $controller->markAllNotificationsRead();
        } elseif (preg_match('/^\/api\/notifications\/(\d+)\/read$/', $requestUri, $matches) && $method === 'POST') {
            $_POST['notification_id'] = $matches[1];
            $controller->markNotificationRead();
        } elseif (preg_match('/^\/api\/notifications\/(\d+)$/', $requestUri, $matches) && $method === 'DELETE') {
            $_POST['notification_id'] = $matches[1];
            $controller->deleteNotification();
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Notification API endpoint not found']);
        }
        exit;
    }
    
    // Language API routes
    if (strpos($requestUri, '/api/languages/') === 0) {
        require_once APP_PATH . '/controllers/LanguageController.php';
        $controller = new LanguageController();
        
        switch ($requestUri) {
            case '/api/languages/list':
                $controller->getLanguages();
                break;
            case '/api/languages/available':
                $controller->getAvailableLanguages();
                break;
            case '/api/languages/add':
                $controller->addLanguage();
                break;
            case '/api/languages/set-default':
                $controller->setDefault();
                break;
            case '/api/languages/toggle':
                $controller->toggleLanguage();
                break;
            case '/api/languages/delete':
                        $controller->deleteLanguage();
        break;
    
    case '/api/languages/update-order':
        $controller->updateSortOrder();
        break;
            case '/api/languages/initialize':
                $controller->initialize();
                break;
            default:
                http_response_code(404);
                echo json_encode(['error' => 'Language API endpoint not found']);
                break;
        }
        exit;
    }
    
    // Default API 404
    http_response_code(404);
    echo json_encode(['error' => 'API endpoint not found']);
    exit;
}

// Frontend routes (public, no authentication required)
// Handle all frontend requests with new Theme System
require_once APP_PATH . '/controllers/FrontendController.php';

try {
    $frontendController = new FrontendController();
    $frontendController->handleRequest($requestUri);
} catch (Exception $e) {
    error_log("Frontend Error: " . $e->getMessage());
    http_response_code(500);
    echo "<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>500 - Sunucu Hatası</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        h1 { color: #d32f2f; }
        p { color: #666; }
        a { color: #007cba; text-decoration: none; }
    </style>
</head>
<body>
    <h1>500 - Sunucu Hatası</h1>
    <p>Bir hata oluştu. Lütfen daha sonra tekrar deneyin.</p>
    <a href='/'>Ana Sayfaya Dön</a>
</body>
</html>";
} 