<?php

namespace Miladmodaresi\Taamito\Admin;

use Miladmodaresi\Taamito\Base\BaseController;
use Miladmodaresi\Taamito\Model\TaamSync;
use WP_REST_Request;

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class Dashboard extends BaseController
{

    public function admin_ajax_init()
    {
        taamitoApp()->ajax('login', [$this, 'login']);
        taamitoApp()->ajax('send_otp', [$this, 'sendOtp']);
        taamitoApp()->ajax('verify', [$this, 'verify']);
        taamitoApp()->ajax('logout', [$this, 'logout']);
    }

    public function admin_page()
    {
        $taamito_icon = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/Pgo8IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDIwMDEwOTA0Ly9FTiIKICJodHRwOi8vd3d3LnczLm9yZy9UUi8yMDAxL1JFQy1TVkctMjAwMTA5MDQvRFREL3N2ZzEwLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4wIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzNDEuMDAwMDAwIDM0MS4wMDAwMDAiCiBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWlkWU1pZCBtZWV0Ij4KCjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAuMDAwMDAwLDM0MS4wMDAwMDApIHNjYWxlKDAuMTAwMDAwLC0wLjEwMDAwMCkiCmZpbGw9IiNhMmFhYjIiIHN0cm9rZT0ibm9uZSI+CjxwYXRoIGQ9Ik01ODUgMzM3MSBjLTIxOCAtNTQgLTQwMCAtMjAzIC00OTYgLTQwNyAtNzggLTE2NSAtNzQgLTk0IC03NCAtMTI1OQowIC0xMTY1IC00IC0xMDk0IDc0IC0xMjU5IDk1IC0yMDIgMjY1IC0zNDQgNDg3IC00MDggbDc5IC0yMiA5ODMgLTQgYzYwOSA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gLTE1ODUgYzE0MSAtNTYgMTAyIC0yNjQgLTUwIC0yNjQgLTUzIDAgLTkyIDIzIC0xMTkKNzAgLTI2IDQ3IC0yNyA4MCAtMSAxMzAgMjAgMzkgNDEgNTYgODkgNzEgMzcgMTEgMzcgMTEgODEgLTd6IG05NDEgNiBjMTEyCi0zMSAxMzUgLTE5MCAzNiAtMjUwIC04MCAtNDkgLTE4OCAtMiAtMjEwIDkxIC0xNSA2MCAzNSAxNDAgOTkgMTU5IDM5IDExIDM0CjExIDc1IDB6Ii8+CjxwYXRoIGQ9Ik0xNjQxIDIwMzYgYy03IC05IC0xMSAtNDEgLTkgLTgzIGwzIC02OCA3NSAwIDc1IDAgMyA3NCBjMiA1MyAtMSA3NwotMTAgODIgLTIyIDE1IC0xMjQgMTAgLTEzNyAtNXoiLz4KPHBhdGggZD0iTTEyMzAgMjAxMSBjLTUgLTExIC0xMCAtNzYgLTEwIC0xNDQgMCAtMTYyIC01IC0xNTcgMTYzIC0xNTcgMTcwIDAKMTY3IC0yIDE2NyAxNjEgMCA2NiAtNSAxMjkgLTEwIDE0MCAtMTAgMTcgLTIzIDE5IC0xNTUgMTkgLTEzMiAwIC0xNDUgLTIKLTE1NSAtMTl6Ii8+CjxwYXRoIGQ9Ik0yMjA0IDE4NTcgYy0zIC04IC00IC0zMiAtMiAtNTMgbDMgLTM5IDU1IDAgNTUgMCAwIDUwIDAgNTAgLTUzIDMKYy0zOCAyIC01NCAtMSAtNTggLTExeiIvPgo8cGF0aCBkPSJNMTY2NCAxNzU3IGMtMiAtNyAtMyAtNTggLTIgLTExMyBsMyAtOTkgMTEwIDAgMTEwIDAgMCAxMTAgMCAxMTAKLTEwOCAzIGMtODMgMiAtMTA5IDAgLTExMyAtMTF6Ii8+CjwvZz4KPC9zdmc+Cg==';
        taamitoApp()->createAdminPage(__('Taamito Settings','taamito'), 'taamito_settings', [$this, 'settingPage'], $taamito_icon);
        add_submenu_page('taamito_settings', __('Data Transfer Wizard','taamito'), __('Data Transfer Wizard','taamito'), 'manage_options', 'taamito_wizard', [$this, 'wizardPage']);
    }

    public function settingPage()
    {
        if ( 
            !in_array( 
              'woocommerce/woocommerce.php', 
              apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) 
            ) 
          ) {
            return taamitoApp()->view('need-woocommerce');
        }

        $user = taamitoApp()->getOption('user');
        taamitoApp()->addCss('style', 'style.css');

        taamitoApp()->addJs('script', 'script.js', true);

        if ($user) {
            taamitoApp()->addCss('info', 'info.css');

            taamitoApp()->addJs('info', 'info.js', true);

            $wizardCompleted = taamitoApp()->getOption('wizard_completed', false);
            return taamitoApp()->view('info', [
                'user' => taamitoApp()->getOption('user'),
                'wizard_completed' => (bool)$wizardCompleted
            ]);
        }

        taamitoApp()->addCss('login', 'login.css');

        taamitoApp()->addJs('login', 'login.js', true);

        return taamitoApp()->view('login');
    }

    public function login()
    {
        $response = taamitoApi()->post('dm/wordpress/login', $this->request->get_attributes());
        return taamitoApp()->view($response);
    }

    public function sendOtp()
    {
        $response = taamitoApi()->post('dm/wordpress/send-otp', $this->request->get_attributes());
        return taamitoApp()->view($response);
    }

    public function verify()
    {
        $request = $this->request->get_attributes();
        $request['domain'] = get_site_url();
        $request['token'] = taamitoGenerateRandomString(100);
        $response = taamitoApi()->post('dm/wordpress/verify', $request);
        $domain = $response->entity->tenants[0]->domain;
        $rawFields = ((array)$response->entity)['fields'] ?? null;
        try {
            $fields = taamitoNormalizeFields($rawFields);
            if ($fields !== null) {
                taamitoApp()->saveOption('fields', $fields);
            }
        } catch (\Throwable $th) {
            // silent; leave previous fields intact
        }
        taamitoApp()->saveOption('domain', $domain);
        taamitoApp()->saveOption('user', (array)$response->entity);
        taamitoApp()->saveOption('token', $request['token']);
        taamitoApp()->saveOption('can_delete', (array)((array)$response->entity)['can_delete']);

        return taamitoApp()->view($response);
    }

    public function logout()
    {
        taamitoApp()->deleteOption('user');
        taamitoApp()->deleteOption('token');
        return taamitoApp()->view([]);
    }

    public function wizardPage()
    {
        if ( 
            !in_array( 
              'woocommerce/woocommerce.php', 
              apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) 
            ) 
          ) {
            return taamitoApp()->view('need-woocommerce');
        }

        $user = taamitoApp()->getOption('user');
        if (!$user) {
            wp_redirect(admin_url('admin.php?page=taamito_settings'));
            exit;
        }

        taamitoApp()->addCss('style', 'style.css');
        taamitoApp()->addCss('wizard', 'wizard.css');
        taamitoApp()->addJs('wizard', 'wizard.js', true);

        return taamitoApp()->view('wizard');
    }
}
