<?php
namespace OxygenApp\Hooks;

if ( ! defined( 'ABSPATH' ) ) exit;

use OxygenApp\Utils\OptionUtils;
use OxygenApp\Utils\OxySession;

class FilterTemplateInclude implements IHook {
    static function register() {
        add_filter('template_include', [self::class, 'onTemplateInclude'], 20);
    }

    static function onTemplateInclude(string $originalTemplate) {
        global $post;
        $isPage = isset($post) && isset($post->post_type) && $post->post_type === 'page';

        $isHomepageApp = OptionUtils::getInstance()->getOption('is_homepage_app');

        if ($isHomepageApp === 'on' && is_home()) {
            $appPageId = OptionUtils::getInstance()->getOption('app_page_id');
            if ($appPageId !== '') {
                // Initialize session for app homepage
                OxySession::initSession();

                $webAppTmplate = apply_filters('oxygen_app_filter_frontend_template_request', $originalTemplate);
                if (isset($webAppTmplate)) {
                    return $webAppTmplate;
                }
            }
        }


        if ($isPage && $post->post_type === 'page') {
            $appPageId = OptionUtils::getInstance()->getOption('app_page_id');
            if ($appPageId !== '' && (int) $appPageId === $post->ID) {
                // Initialize session for app page
                OxySession::initSession();

                $webAppTmplate = apply_filters('oxygen_app_filter_frontend_template_request', $originalTemplate);
                if (isset($webAppTmplate) && $webAppTmplate !== '') {
                    $originalTemplate = $webAppTmplate;
                }
            }
        }

        return $originalTemplate;
    }
}