<?php

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

// Load Environment Variables
$dotenv = Dotenv\Dotenv::createUnsafeImmutable(__DIR__ . '/../');
$dotenv->safeLoad();

use Models\Page;
use Models\Meta;
use Core\MultiTenancy;
use Core\Model;
use Core\Cache;
use Core\Sitemap;
use Core\Hook;
use Core\Component;
use Core\LayoutRenderer;
use Core\Auth;
use Core\Robots;
use League\Plates\Engine;
use Bramus\Router\Router;

// Initialize Multi-Tenancy
$tenantId = MultiTenancy::getTenantId();
$dbFile = getenv('DB_PATH') ?: 'database.sqlite';
define('DB_PATH', MultiTenancy::getDatabasePath($tenantId));

// Initialize tenant database if it doesn't exist
if (!file_exists(DB_PATH)) {
    copy(__DIR__ . '/../' . $dbFile, DB_PATH);
}

// Database Connection
try {
    $pdo = new PDO('sqlite:' . DB_PATH);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    // Set PDO for all models
    Model::setPdo($pdo);

} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}

// Load Plugins
$pluginFiles = glob(__DIR__ . '/../plugins/*.php');
foreach ($pluginFiles as $file) {
    require_once $file;
}

// Initialize Router
$router = new Router();

// CSRF Protection & Auth Middleware for Admin
$router->before('POST', '/admin/.*', function () {
    Auth::startSession();
    $token = $_POST['csrf_token'] ?? '';
    if (!Auth::verifyCsrfToken($token)) {
        http_response_code(403);
        die('CSRF token validation failed.');
    }
});

$router->before('GET|POST', '/admin/.*', function () {
    $uri = $_SERVER['REQUEST_URI'] ?? '';
    $authAllowed = ['login.php', 'install.php'];
    $isAllowed = false;
    foreach ($authAllowed as $allowed) {
        if (str_contains($uri, $allowed)) {
            $isAllowed = true;
            break;
        }
    }
    if (!Auth::check() && !$isAllowed) {
        header('Location: /admin/login.php');
        exit;
    }
});

// Initialize Plates Template Engine
$templates = new Engine(__DIR__ . '/../themes/default');

// Sitemap route
$router->get('/sitemap.xml', function () {
    header('Content-Type: application/xml');
    echo Sitemap::generate();
});

// Robots.txt route
$router->get('/robots.txt', function () {
    header('Content-Type: text/plain');
    echo Robots::generate();
});

// API V1 Routes
$router->get('/api/v1/(.*)', function ($slug) {
    header('Content-Type: application/json');
    $page = Page::findBySlug($slug ?: 'home');
    if ($page) {
        $page['meta'] = Meta::getForObject($page['id'], 'page');
        echo json_encode($page);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Not found']);
    }
});

// Admin Routes (Legacy fallback for now, but routed)
$router->all('/admin/(.*)', function ($path) use ($pdo) {
    // Inject PDO into global scope for legacy files
    $GLOBALS['pdo'] = $pdo;

    $adminFile = __DIR__ . '/admin/' . $path;
    if (is_dir($adminFile)) {
        $adminFile .= '/index.php';
    }
    if (file_exists($adminFile)) {
        require $adminFile;
    } else {
        http_response_code(404);
        echo "Admin page not found.";
    }
});

// Default Admin route
$router->get('/admin', function () use ($pdo) {
    $GLOBALS['pdo'] = $pdo;
    require __DIR__ . '/admin/index.php';
});

// Frontend Catch-All Route
$router->get('/(.*)', function ($slug) use ($templates) {
    $slug = $slug ?: 'home';
    $cacheKey = 'page_' . $slug;
    $page = Cache::get($cacheKey);

    if (!$page) {
        if (isset($_GET['preview']) && isset($_GET['page_id']) && Auth::check()) {
            $page = Page::find($_GET['page_id']);
        } else {
            $page = Page::findBySlug($slug);
        }

        if ($page && !isset($_GET['preview'])) {
            Cache::set($cacheKey, $page);
        }
    }

    if (!$page && $slug === 'home') {
        $page = [
            'id' => 0,
            'title' => 'Welcome to AI-Native CMS!',
            'content' => 'This is the default homepage. Create a page with slug "home" in the admin panel to customize it.',
            'status' => 'published',
            'template' => 'page.php'
        ];
    }

    if ($page && ($page['status'] === 'published' || isset($_GET['preview']) || $page['id'] === 0)) {

        // Check if this is a Visual Builder page (blank template with full HTML)
        $templateName = $page['template'] ?? 'page';
        $templateName = str_replace('.php', '', $templateName);
        $content = $page['content'] ?? '';

        // If blank template and content contains full HTML document, output directly
        if ($templateName === 'blank' && preg_match('/^\s*<!DOCTYPE|^\s*<html/i', $content)) {
            // Inject Tracking Codes
            $trackingHead = Meta::get(0, 'site', 'tracking_head');
            $trackingBody = Meta::get(0, 'site', 'tracking_body');

            if ($trackingHead) {
                $content = str_ireplace('</head>', $trackingHead . "\n</head>", $content);
            }
            if ($trackingBody) {
                $content = str_ireplace('<body', '<body', $content); // Ensure case insensitive
                $content = preg_replace('/(<body[^>]*>)/i', '$1' . "\n" . $trackingBody, $content);
            }

            echo $content;
            return;
        }

        // Parse layout and content
        $layoutParsed = LayoutRenderer::parseContentWithLayout($content);

        if ($layoutParsed['layout']) {
            $content = LayoutRenderer::render($layoutParsed['layout']);
            $content .= $layoutParsed['content'];
        }

        // Process Shortcodes and Filters
        $content = Component::renderShortcodes($content);
        $content = Component::renderBlockShortcodes($content);
        $content = Hook::applyFilters('content', $content);

        // Check for template
        $templateName = $page['template'] ?? 'page';
        $templateName = str_replace('.php', '', $templateName); // Plates uses names without .php

        // Render using Plates
        try {
            echo $templates->render($templateName, [
                'page' => $page,
                'content' => $content,
                'title' => $page['title'],
                'meta' => Meta::getForObject($page['id'] ?? 0, 'page')
            ]);
        } catch (Exception $e) {
            // Fallback to default page if custom template fails
            echo $templates->render('page', [
                'page' => $page,
                'content' => $content,
                'title' => $page['title'],
                'meta' => Meta::getForObject($page['id'] ?? 0, 'page')
            ]);
        }
    } else {
        http_response_code(404);
        echo $templates->render('404');
    }
});

$router->run();
