<?php

/**
 * ======================================================================
 * LICENSE: This file is subject to the terms and conditions defined in *
 * file 'license.txt', which is part of this source code package.       *
 * ======================================================================
 */

/**
 * Logout Redirect service
 *
 * @since 6.9.26 https://github.com/aamplugin/advanced-access-manager/issues/360
 * @since 6.9.12 https://github.com/aamplugin/advanced-access-manager/issues/291
 * @since 6.4.0  https://github.com/aamplugin/advanced-access-manager/issues/76
 * @since 6.1.0  Fixed bug where white screen occurs if "Default" option is
 *               explicitly selected
 * @since 6.0.5  Fixed the bug with logout redirect
 * @since 6.0.0  Initial implementation of the class
 *
 * @package AAM
 * @version 6.9.26
 */
class AAM_Service_LogoutRedirect
{
    use AAM_Core_Contract_ServiceTrait;

    /**
     * AAM configuration setting that is associated with the service
     *
     * @version 6.0.0
     */
    const FEATURE_FLAG = 'core.service.logout-redirect.enabled';

    /**
     * Contains the redirect instructions for just logged out user
     *
     * @var array
     *
     * @access protected
     * @since 6.0.5
     */
    protected $redirect = null;

    /**
     * Constructor
     *
     * @return void
     *
     * @access protected
     * @version 6.0.0
     */
    protected function __construct()
    {
        add_filter('aam_get_config_filter', function($result, $key) {
            if ($key === self::FEATURE_FLAG && is_null($result)) {
                $result = true;
            }

            return $result;
        }, 10, 2);

        $enabled = AAM_Framework_Manager::configs()->get_config(self::FEATURE_FLAG);

        if (is_admin()) {
            // Hook that initialize the AAM UI part of the service
            if ($enabled) {
                add_action('aam_init_ui_action', function () {
                    AAM_Backend_Feature_Main_LogoutRedirect::register();
                });
            }

            // Hook that returns the detailed information about the nature of the
            // service. This is used to display information about service on the
            // Settings->Services tab
            add_filter('aam_service_list_filter', function ($services) {
                $services[] = array(
                    'title'       => __('Logout Redirect', AAM_KEY),
                    'description' => __('Manage logout redirect for any group of users or individual user after user logged out successfully.', AAM_KEY),
                    'setting'     => self::FEATURE_FLAG
                );

                return $services;
            }, 35);
        }

        if ($enabled) {
            $this->initializeHooks();
        }
    }

    /**
     * Initialize Logout redirect hooks
     *
     * @return void
     *
     * @since 6.9.26 https://github.com/aamplugin/advanced-access-manager/issues/360
     * @since 6.9.12 https://github.com/aamplugin/advanced-access-manager/issues/291
     * @since 6.4.0  https://github.com/aamplugin/advanced-access-manager/issues/76
     * @since 6.1.0  Fixed bug where white screen occurs if "Default" option is
     *               explicitly selected
     * @since 6.0.5  Fixed bug where user was not redirected properly after logout
     *               because AAM was already hooking into `set_current_user`.
     * @since 6.0.0  Initial implementation of the method
     *
     * @access protected
     * @version 6.9.26
     */
    protected function initializeHooks()
    {
        // Capture currently logging out user settings
        add_action('clear_auth_cookie', function() {
            $this->redirect = AAM::getUser()->getObject(
                AAM_Core_Object_LogoutRedirect::OBJECT_TYPE
            )->getOption();
        });

        // Fired after the user has been logged out successfully
        add_action('wp_logout', function() {
            // Determining redirect type
            $type = 'default';
            if (!empty($this->redirect['logout.redirect.type'])) {
                $type = $this->redirect['logout.redirect.type'];
            }

            if ($type !== 'default') {
                AAM_Core_Redirect::execute($type, array(
                    $type => $this->redirect["logout.redirect.{$type}"]
                ));
            }

            // Halt the execution. Redirect should carry user away if this is not
            // a CLI execution (e.g. Unit Test)
            if (php_sapi_name() !== 'cli' && $type !== 'default') {
                exit;
            }
        }, PHP_INT_MAX);

        // Policy generation hook
        add_filter(
            'aam_generated_policy_filter', array($this, 'generatePolicy'), 10, 4
        );

        // Register RESTful API
        AAM_Restful_LogoutRedirectService::bootstrap();
    }

    /**
     * Generate Logout Redirect policy params
     *
     * @param array                     $policy
     * @param string                    $resource_type
     * @param array                     $options
     * @param AAM_Core_Policy_Generator $generator
     *
     * @return array
     *
     * @access public
     * @version 6.4.0
     */
    public function generatePolicy($policy, $resource_type, $options, $generator)
    {
        if ($resource_type === AAM_Core_Object_LogoutRedirect::OBJECT_TYPE) {
            if (!empty($options)) {
                $policy['Param'] = array_merge(
                    $policy['Param'],
                    $generator->generateRedirectParam($options, 'logout')
                );
            }
        }

        return $policy;
    }

}

if (defined('AAM_KEY')) {
    AAM_Service_LogoutRedirect::bootstrap();
}