<?php
$isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || 
            (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');

ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
if ($isSecure) {
    ini_set('session.cookie_secure', '1');
}
ini_set('session.gc_maxlifetime', '3600');
ini_set('session.cookie_lifetime', '0');

session_start();

if (!isset($_SESSION['_created'])) {
    $_SESSION['_created'] = time();
} elseif (time() - $_SESSION['_created'] > 1800) {
    session_regenerate_id(true);
    $_SESSION['_created'] = time();
}

if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    $_SESSION['_last_activity'] = $_SESSION['_last_activity'] ?? time();
    if (time() - $_SESSION['_last_activity'] > 3600) {
        session_unset();
        session_destroy();
        session_start();
        $_SESSION['_created'] = time();
    } else {
        $_SESSION['_last_activity'] = time();
    }
}

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/database/schema.php';
require_once __DIR__ . '/models/functions.php';
require_once __DIR__ . '/functions.php';

initDatabase();

header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
if ($isSecure) {
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com; img-src 'self' data: https:; frame-src https://www.youtube.com https://youtube.com; connect-src 'self'; base-uri 'self'; form-action 'self';");

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = rtrim($uri, '/') ?: '/';

if (preg_match('#^/assets/(.+)$#', $uri, $m)) {
    $requestedPath = $m[1];
    if (strpos($requestedPath, '..') !== false || strpos($requestedPath, "\0") !== false) {
        http_response_code(403);
        exit;
    }
    $file = realpath(__DIR__ . '/assets/' . $requestedPath);
    $assetsDir = realpath(__DIR__ . '/assets');
    if ($file && $assetsDir && strpos($file, $assetsDir) === 0 && is_file($file)) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        $types = ['css' => 'text/css', 'js' => 'application/javascript', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'webp' => 'image/webp', 'svg' => 'image/svg+xml', 'ico' => 'image/x-icon'];
        if (!isset($types[$ext])) {
            http_response_code(403);
            exit;
        }
        header('Content-Type: ' . $types[$ext]);
        readfile($file);
        exit;
    }
}

if (preg_match('#^/uploads/(.+)$#', $uri, $m)) {
    $requestedPath = $m[1];
    if (strpos($requestedPath, '..') !== false || strpos($requestedPath, "\0") !== false) {
        http_response_code(403);
        exit;
    }
    $file = realpath(__DIR__ . '/uploads/' . $requestedPath);
    $uploadsDir = realpath(__DIR__ . '/uploads');
    if ($file && $uploadsDir && strpos($file, $uploadsDir) === 0 && is_file($file)) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
        if (!in_array($ext, $allowedExts)) {
            http_response_code(403);
            exit;
        }
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file);
        $allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'];
        if (!in_array($mime, $allowedMimes)) {
            http_response_code(403);
            exit;
        }
        header('Content-Type: ' . $mime);
        header('X-Content-Type-Options: nosniff');
        header('Content-Disposition: inline');
        readfile($file);
        exit;
    }
}

$adminPages = [
    '/admin' => 'dashboard',
    '/admin/sliders' => 'sliders',
    '/admin/sections' => 'sections',
    '/admin/announcements' => 'announcements',
    '/admin/resources' => 'resources',
    '/admin/facilities' => 'facilities',
    '/admin/settings' => 'settings',
    '/admin/delete' => 'delete',
    '/admin/messages' => 'messages',
    '/admin/services' => 'admin_services',
    '/admin/workshops' => 'admin_workshops',
    '/admin/articles' => 'admin_articles',
    '/admin/categories' => 'admin_categories',
    '/admin/team' => 'admin_team',
    '/admin/alumni' => 'admin_alumni',
    '/admin/registrations' => 'admin_registrations',
    '/admin/newsletter' => 'admin_newsletter',
    '/admin/audit' => 'admin_audit',
    '/admin/seo' => 'admin_seo',
    '/admin/users' => 'admin_users',
    '/admin/menu' => 'admin_menu',
    '/admin/gallery' => 'admin_gallery',
];

if ($uri === '/admin/login') {
    include __DIR__ . '/admin/login.php';
    exit;
}

if ($uri === '/admin/logout') {
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    session_destroy();
    header('Location: /admin/login');
    exit;
}

if ($uri === '/admin/upload') {
    header('Content-Type: application/json');
    if (!isAdminAuthenticated()) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Not authenticated']);
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            echo json_encode(['success' => false, 'error' => 'Invalid token']);
        } else {
            $result = handleFileUpload('file');
            echo json_encode($result);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'POST required']);
    }
    exit;
}

if ($uri === '/admin/menu-order') {
    header('Content-Type: application/json');
    if (!isAdminAuthenticated()) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Not authenticated']);
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        if (!verifyCsrfToken($input['csrf_token'] ?? '')) {
            echo json_encode(['success' => false, 'error' => 'Invalid token']);
        } else {
            $db = getDB();
            $stmt = $db->prepare("UPDATE menu_items SET sort_order = ?, parent_id = NULLIF(?, 0) WHERE id = ?");
            foreach ($input['order'] as $item) {
                $stmt->execute([(int)$item['sort_order'], (int)$item['parent_id'], (int)$item['id']]);
            }
            echo json_encode(['success' => true]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'POST required']);
    }
    exit;
}

if (isset($adminPages[$uri])) {
    if (!isAdminAuthenticated()) {
        header('Location: /admin/login');
        exit;
    }
    $adminFile = $adminPages[$uri];
    if ($adminFile === 'dashboard') {
        $settings = getAllSettings();
    }
    include __DIR__ . '/admin/' . $adminFile . '.php';
    exit;
}

switch ($uri) {
    case '/':
        $settings = getAllSettings();
        $sliders = getActiveSliders();
        $sections = getActiveSections();
        $announcements = getActiveAnnouncements();
        $resources = getActiveResources();
        $facilities = getActiveFacilities();
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/home.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/about':
        $settings = getAllSettings();
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/about.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/sections':
        $settings = getAllSettings();
        $sections = getActiveSections();
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/sections.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/contact':
        $settings = getAllSettings();
        $contactMsg = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!checkRateLimit('contact', 5, 300)) {
                $contactMsg = 'Too many submissions. Please try again later.';
            } elseif (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
                $contactMsg = 'Invalid security token. Please refresh and try again.';
            } else {
                $name = sanitizeString($_POST['name'] ?? '', 200);
                $email = sanitizeEmail($_POST['email'] ?? '');
                $subject = sanitizeString($_POST['subject'] ?? '', 300);
                $message = sanitizeString($_POST['message'] ?? '', 5000);
                if ($name && $email && $message && verifyCaptcha($_POST['captcha'] ?? '')) {
                    try {
                        $db = getDB();
                        $stmt = $db->prepare("INSERT INTO contact_messages (name, email, subject, message) VALUES (?, ?, ?, ?)");
                        $stmt->execute([$name, $email, $subject, $message]);
                        header('Location: /contact?sent=1');
                        exit;
                    } catch (PDOException $e) {
                        $contactMsg = 'An error occurred. Please try again.';
                    }
                } else {
                    $contactMsg = 'Please fill in all required fields with valid information and complete the security check.';
                }
            }
        }
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/contact.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/services':
        $settings = getAllSettings();
        $services = getActiveServices();
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/services.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/workshops':
        $settings = getAllSettings();
        $workshops = getActiveWorkshops();
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/workshops.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/articles':
        $settings = getAllSettings();
        $categories = getArticleCategories();
        $currentCategory = isset($_GET['category']) ? (int)$_GET['category'] : null;
        $searchQuery = $_GET['q'] ?? $_GET['search'] ?? '';
        $perPage = 6;
        $currentPage = max(1, (int)($_GET['page'] ?? 1));
        $totalArticles = countPublishedArticles($currentCategory, $searchQuery);
        $articles = getPublishedArticles($perPage, ($currentPage - 1) * $perPage, $currentCategory, $searchQuery);
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/articles.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/alumni':
        $settings = getAllSettings();
        $alumni = getActiveAlumni();
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/alumni.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/gallery':
        $settings = getAllSettings();
        $galleryCategories = getGalleryCategories();
        $recentImages = getRecentGalleryImages(12);
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/gallery.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/resources/forms':
    case '/resources/courseware':
    case '/resources/publications':
        $settings = getAllSettings();
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/resource.php';
        include __DIR__ . '/views/footer.php';
        break;

    case '/newsletter/subscribe':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (checkRateLimit('newsletter', 3, 300) && verifyCsrfToken($_POST['csrf_token'] ?? '')) {
                $email = sanitizeEmail($_POST['email'] ?? '');
                $name = sanitizeString($_POST['name'] ?? '', 200);
                if ($email && verifyCaptcha($_POST['captcha'] ?? '')) {
                    try {
                        $db = getDB();
                        $stmt = $db->prepare("INSERT INTO newsletter_subscribers (email, name) VALUES (?, ?) ON CONFLICT (email) DO NOTHING");
                        $stmt->execute([$email, $name]);
                    } catch (PDOException $e) {
                    }
                }
            }
            header('Location: /?subscribed=1');
            exit;
        }
        header('Location: /');
        exit;

    case '/sitemap.xml':
        header('Content-Type: application/xml');
        include __DIR__ . '/views/sitemap.php';
        exit;

    default:
        if (preg_match('#^/section/([a-zA-Z0-9_-]+)$#', $uri, $matches)) {
            $settings = getAllSettings();
            $db = getDB();
            $stmt = $db->prepare("SELECT * FROM sections WHERE slug = ?");
            $stmt->execute([$matches[1]]);
            $section = $stmt->fetch();
            if (!$section) {
                http_response_code(404);
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/404.php';
                include __DIR__ . '/views/footer.php';
            } else {
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/section_detail.php';
                include __DIR__ . '/views/footer.php';
            }
            break;
        }

        if (preg_match('#^/service/([a-zA-Z0-9_-]+)$#', $uri, $matches)) {
            $settings = getAllSettings();
            $db = getDB();
            $stmt = $db->prepare("SELECT * FROM services WHERE slug = ? AND active = TRUE");
            $stmt->execute([$matches[1]]);
            $service = $stmt->fetch();
            if (!$service) {
                http_response_code(404);
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/404.php';
                include __DIR__ . '/views/footer.php';
            } else {
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/service_detail.php';
                include __DIR__ . '/views/footer.php';
            }
            break;
        }

        if (preg_match('#^/workshop/([a-zA-Z0-9_-]+)$#', $uri, $matches)) {
            $settings = getAllSettings();
            $db = getDB();
            $stmt = $db->prepare("SELECT * FROM workshops WHERE slug = ? AND active = TRUE");
            $stmt->execute([$matches[1]]);
            $workshop = $stmt->fetch();
            if (!$workshop) {
                http_response_code(404);
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/404.php';
                include __DIR__ . '/views/footer.php';
            } else {
                $registrationMsg = '';
                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    if (!checkRateLimit('workshop_reg', 5, 300)) {
                        $registrationMsg = 'Too many submissions. Please try again later.';
                    } elseif (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
                        $registrationMsg = 'Invalid security token. Please refresh and try again.';
                    } else {
                        $rName = sanitizeString($_POST['name'] ?? '', 200);
                        $rEmail = sanitizeEmail($_POST['email'] ?? '');
                        $rPhone = sanitizeString($_POST['phone'] ?? '', 30);
                        $rOrg = sanitizeString($_POST['organization'] ?? '', 300);
                        $rMsg = sanitizeString($_POST['message'] ?? '', 2000);
                        if ($rName && $rEmail && verifyCaptcha($_POST['captcha'] ?? '')) {
                            try {
                                $stmt = $db->prepare("INSERT INTO workshop_registrations (workshop_id, name, email, phone, organization, message) VALUES (?, ?, ?, ?, ?, ?)");
                                $stmt->execute([$workshop['id'], $rName, $rEmail, $rPhone, $rOrg, $rMsg]);
                                $registrationMsg = 'success';
                            } catch (PDOException $e) {
                                $registrationMsg = 'An error occurred. Please try again.';
                            }
                        } else {
                            $registrationMsg = 'Please fill in all required fields with valid information.';
                        }
                    }
                }
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/workshop_detail.php';
                include __DIR__ . '/views/footer.php';
            }
            break;
        }

        if (preg_match('#^/article/([a-zA-Z0-9_-]+)$#', $uri, $matches)) {
            $settings = getAllSettings();
            $db = getDB();
            $stmt = $db->prepare("SELECT a.*, c.name as category_name, c.slug as category_slug FROM articles a LEFT JOIN article_categories c ON a.category_id = c.id WHERE a.slug = ? AND a.published = TRUE");
            $stmt->execute([$matches[1]]);
            $article = $stmt->fetch();
            if (!$article) {
                http_response_code(404);
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/404.php';
                include __DIR__ . '/views/footer.php';
            } else {
                $db->prepare("UPDATE articles SET views = views + 1 WHERE id = ?")->execute([$article['id']]);
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/article_detail.php';
                include __DIR__ . '/views/footer.php';
            }
            break;
        }

        if (preg_match('#^/gallery/([a-zA-Z0-9_-]+)$#', $uri, $matches)) {
            $settings = getAllSettings();
            $category = getGalleryCategoryBySlug($matches[1]);
            if (!$category) {
                http_response_code(404);
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/404.php';
                include __DIR__ . '/views/footer.php';
            } else {
                $images = getGalleryImages($category['id']);
                include __DIR__ . '/views/header.php';
                include __DIR__ . '/views/gallery_detail.php';
                include __DIR__ . '/views/footer.php';
            }
            break;
        }

        $settings = getAllSettings();
        http_response_code(404);
        include __DIR__ . '/views/header.php';
        include __DIR__ . '/views/404.php';
        include __DIR__ . '/views/footer.php';
        break;
}
