<?php
/**
 * @author WP Cloud Plugins
 * @copyright Copyright (c) 2023, WP Cloud Plugins
 *
 * @since       2.11
 * @see https://www.wpcloudplugins.com
 */

namespace TheLion\UseyourDrive;

defined('ABSPATH') || exit;

class AjaxRequest
{
    /**
     * The single instance of the class.
     *
     * @var AjaxRequest
     */
    protected static $_instance;

    public function __construct()
    {
        $this->set_hooks();
    }

    /**
     * AjaxRequest Instance.
     *
     * Ensures only one instance is loaded or can be loaded.
     *
     * @return AjaxRequest - AjaxRequest instance
     *
     * @static
     */
    public static function instance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    public function set_hooks()
    {
        // Ajax calls
        add_action('wp_ajax_nopriv_useyourdrive-get-filelist', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-get-filelist', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-search', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-search', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-get-gallery', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-get-gallery', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-upload-file', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-upload-file', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-delete-entries', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-delete-entries', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-rename-entry', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-rename-entry', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-move-entries', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-move-entries', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-copy-entries', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-copy-entries', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-move-entries', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-move-entries', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-create-shortcuts', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-create-shortcuts', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-edit-description-entry', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-edit-description-entry', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-create-entry', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-create-entry', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-get-playlist', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-get-playlist', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-create-zip', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-create-zip', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-download', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-download', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-stream', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-stream', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-preview', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-preview', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-edit', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-edit', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-thumbnail', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-thumbnail', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-check-recaptcha', [$this, 'check_recaptcha']);
        add_action('wp_ajax_useyourdrive-check-recaptcha', [$this, 'check_recaptcha']);

        add_action('wp_ajax_nopriv_useyourdrive-create-link', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-create-link', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-embedded', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-shorten-url', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-shorten-url', [$this, 'do_action']);

        add_action('wp_ajax_useyourdrive-getpopup', [$this, 'get_popup']);
        add_action('wp_ajax_useyourdrive-previewshortcode', [$this, 'preview_shortcode']);

        add_action('wp_ajax_nopriv_useyourdrive-getads', [$this, 'do_action']);
        add_action('wp_ajax_useyourdrive-getads', [$this, 'do_action']);

        add_action('wp_ajax_nopriv_useyourdrive-embed-image', [$this, 'embed_image']);
        add_action('wp_ajax_useyourdrive-embed-image', [$this, 'embed_image']);

        add_action('wp_ajax_useyourdrive-linkusertofolder', [$this, 'user_folder_link']);
        add_action('wp_ajax_useyourdrive-unlinkusertofolder', [$this, 'user_folder_unlink']);
        add_action('wp_ajax_useyourdrive-rating-asked', [$this, 'rating_asked']);
    }

    public function do_action()
    {
        if (!isset($_REQUEST['action'])) {
            return false;
        }

        require_once ABSPATH.'wp-includes/pluggable.php';
        Processor::instance()->start_process();

        exit;
    }

    public function get_popup()
    {
        switch ($_REQUEST['type']) {
            case 'shortcodebuilder':
                ShortcodeBuilder::instance()->render();

                break;

            case 'links':
                include_once USEYOURDRIVE_ROOTDIR.'/templates/admin/documents_linker.php';

                break;

            case 'embedded':
                include_once USEYOURDRIVE_ROOTDIR.'/templates/admin/documents_embedder.php';

                break;

            default:
                exit;
        }

        exit;
    }

    public function check_recaptcha()
    {
        if (!isset($_REQUEST['action']) || !isset($_REQUEST['response'])) {
            echo json_encode(['verified' => false]);

            exit;
        }

        check_ajax_referer($_REQUEST['action']);

        require_once USEYOURDRIVE_ROOTDIR.'/vendors/reCAPTCHA/autoload.php';
        $secret = Settings::get('recaptcha_secret');
        $recaptcha = new \ReCaptcha\ReCaptcha($secret);

        $resp = $recaptcha->setExpectedAction('wpcloudplugins')
            ->setScoreThreshold(0.5)
            ->verify($_REQUEST['response'], Helpers::get_user_ip())
        ;

        if ($resp->isSuccess()) {
            echo json_encode(['verified' => true]);
        } else {
            echo json_encode(['verified' => false, 'msg' => $resp->getErrorCodes()]);
        }

        exit;
    }

    public function preview_shortcode()
    {
        check_ajax_referer('wpcp-useyourdrive-block');

        include_once USEYOURDRIVE_ROOTDIR.'/templates/admin/shortcode_previewer.php';

        exit;
    }

    public function embed_image()
    {
        $entryid = $_REQUEST['id'] ?? null;

        if (empty($entryid)) {
            exit('-1');
        }

        if (!isset($_REQUEST['account_id'])) {
            // Fallback for old embed urls without account info

            $primary_account = Accounts::instance()->get_primary_account();
            if (false === $primary_account) {
                exit('-1');
            }
            $account_id = $primary_account->get_id();
        } else {
            $account_id = $_REQUEST['account_id'];
        }

        App::set_current_account_by_id($account_id);
        Processor::instance()->embed_image($entryid);

        exit;
    }

    public function rating_asked()
    {
        update_option('use_your_drive_rating_asked', true);
    }

    public function user_folder_link()
    {
        check_ajax_referer('useyourdrive-create-link');

        $userfolders = new UserFolders();

        $folder_id = sanitize_text_field(rawurldecode($_REQUEST['id']));
        $account_id = sanitize_text_field(rawurldecode($_REQUEST['account_id']));

        $linkedto = [
            'folderid' => $folder_id,
            'accountid' => $account_id,
        ];

        $userid = $_REQUEST['userid'];

        if (Helpers::check_user_role(Settings::get('permissions_link_users'))) {
            $userfolders->manually_link_folder($userid, $linkedto);
        }
    }

    public function user_folder_unlink()
    {
        check_ajax_referer('useyourdrive-create-link');

        $userfolders = new UserFolders();

        $userid = $_REQUEST['userid'];

        if (Helpers::check_user_role(Settings::get('permissions_link_users'))) {
            $userfolders->manually_unlink_folder($userid);
        }
    }
}
