<?php

class FacebookApplicationPlugin extends SJB_PluginAbstract
{
    /**
     * @param string $theme Original theme
     * @return string
     */
    public static function getCurrentTheme($theme)
    {
        if (strpos(SJB_Request::getVar('HTTP_REFERER', '', 'SERVER'), 'fbapp.smartjobboard.com') !== false && SJB_Request::getVar('original', false) === false) {
            $theme = 'Facebook';
            $signedRequest = SJB_Request::getVar('signed_request', false);
            if ($signedRequest) {
                $signedRequest = self::parse_signed_request($signedRequest);
                if (SJB_Array::get($signedRequest, 'app_data')) {
                    SJB_HelperFunctions::redirect('https://fbapp.smartjobboard.com/tab' . SJB_TemplateProcessor::listing_url(SJB_ListingManager::getListingInfoBySID(SJB_Array::get($signedRequest, 'app_data'))) . '?tabId=' . SJB_Request::getVar('facebookTabId', '', 'COOKIE'));
                }
            }
        }
        return $theme;
    }

    public static function parse_signed_request($signed_request)
    {
        list($encoded_sig, $payload) = explode('.', $signed_request, 2);
        // decode the data
        $sig = self::base64_url_decode($encoded_sig);
        return json_decode(self::base64_url_decode($payload), true);
    }

    private static function base64_url_decode($input)
    {
        return base64_decode(strtr($input, '-_', '+/'));
    }

    public static function handleSystemBoot()
    {
        $plugin = SJB_PluginManager::getPluginByName('FacebookApplicationPlugin');
        $isPluginActive = $plugin && $plugin['active'] == '1';
        if (!$isPluginActive) {
            return;
        }
        $isFbAppSettingsPage = SJB_Request::getVar('action') == 'settings' && SJB_Request::getVar('plugin') == 'FacebookApplicationPlugin';
        if ($isFbAppSettingsPage) {
            SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('ADMIN_SITE_URL') . '/system/miscellaneous/fb_app_settings/');
        }
        if (SJB_Navigator::getURI() == '/system/miscellaneous/fb_app_settings/') {
            SJB_System::getModuleManager()->addFunction('miscellaneous', 'fb_app_settings', [
                'display_name' => 'Facebook Application Plugin Settings',
                'script' => '../../plugins/facebook_app/module/miscellaneous/fb_app_settings.php',
                'type' => 'admin',
                'access_type' => ['admin'],
            ]);
            require_once __DIR__ . '/module/miscellaneous/fb_app_settings.php';
        }
    }

}
