<?php

namespace app\controllers;

use Yii;
use app\models\AppSetup;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\components\Shopify;
use yii\web\Session;

/**
 * AppController implements the CRUD actions for AppSetup model.
 */
class AppController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /* Shopify Product Create Hook */

    public function actionSetup() {
        $filepath = "install.txt";
        $file = fopen($filepath, "w");
        $shopify_shop = isset($_GET['shop']) ? $_GET['shop'] : '';
        $shopify_code = isset($_GET['code']) ? $_GET['code'] : '';
        $app_key = Yii::$app->params['app_key'];
        $app_secret = Yii::$app->params['app_secret'];
        $base_url = Yii::$app->params['base_url'];

        $app_installed = AppSetup::find()->Where(['shopify_shop' => $shopify_shop])->one();
        if (!empty($app_installed)) {
            fwrite($file, "\n - here-if ");
            $shopify_shop = $app_installed->shopify_shop;
            $shopify_token = $app_installed->shopify_token;
        } else {
            $shopifyClient = new Shopify($shopify_shop, "", $app_key, $app_secret);
            $shopify_token = $shopifyClient->getAccessToken($shopify_code);
            if (empty($shopify_token)) {
                fwrite($file, "\n - empty token ");
                $shopify_scope = Yii::$app->params['scope'];
                $redirect_uri = $base_url . '/web/index.php/app/setup';
                header("Location: " . $shopifyClient->getAuthorizeUrl($shopify_scope, $redirect_uri));
                exit;
            } else {
                $sc = new Shopify($shopify_shop, $shopify_token, $app_key, $app_secret);
                $shop = $sc->call('GET', '/admin/shop.json');
                $appSetup = new AppSetup();
                fwrite($file, "\shop-response " . json_encode($shop));
                $appSetup->shopify_shop = $shopify_shop;
                $appSetup->shopify_token = $shopify_token;
                $appSetup->shopify_code = $shopify_code;
                $appSetup->shopify_status = 1;
                $appSetup->api_client_id = $app_key;
                $appSetup->created_at = date('Y-m-d H:i:s', time());

                if ($appSetup->save(false)) {
                    fwrite($file, "\n third - " . $shopify_shop);
                    $sc = new Shopify($shopify_shop, $shopify_token, $app_key, $app_secret);
                    fwrite($file, "\n " . json_encode($sc));
                    self::ShopifyHooks($sc, $shopify_shop);  /* Hooks for Shopify */
                    self::addScriptTag($sc, $shopify_shop);  /* Script tags for shopify */
                }
            }
        }

        $sc = new Shopify($shopify_shop, $shopify_token, $app_key, $app_secret);
        $appSetup = AppSetup::find()->Where(['shopify_shop' => $shopify_shop])->one();
        $session = Yii::$app->session;
        $session->open();
        $session->set('shop', $shopify_shop);
        if (!empty($appSetup)) {
//            return $this->redirect(['svg/index']);
            return $this->redirect(['design/index']);
        } else {
            echo "Something went wrong, please try again later.";
            exit();
        }
    }

    /* App unistalled hook and deleted shop data in our database */

    public function actionUninstall() {
        $filepath = "uninstall.txt";
        $file = fopen($filepath, "a");
        fwrite($file, " enter  ");
        ob_start();
        $serverProtocole = filter_input(INPUT_SERVER, 'SERVER_PROTOCOL', FILTER_SANITIZE_STRING);
        header($serverProtocole . ' 200 OK');
        header('Content-Encoding: none');
        header('Content-Length: ' . ob_get_length());
        header('Connection: close');
        ob_end_flush();
        ob_flush();
        flush();
        $shop_name = '';
        if (isset($_GET['shop'])) {
            $shop_name = $_GET['shop'];
        }
        /* delete Sprygo table data for unilstalled app */
        $appSetup = AppSetup::find()->Where(['shopify_shop' => $shop_name])->one();
        $appSetup->delete();
    }

    /**
     * Lists all AppSetup models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new AppSetupSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single AppSetup model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Finds the AppSetup model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AppSetup the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = AppSetup::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public static function ShopifyHooks($shopifyClient, $shopify_shop) {
        $base_url = Yii::$app->params['base_url'];
        $hooks = array();
        $filepath = "hooks.txt";
        $file = fopen($filepath, "a");

        try {
            fwrite($file, "\n in try - ");
            $hooks_tag = $shopifyClient->call('GET', '/admin/webhooks.json');
            fwrite($file, "\n hook tags - " . json_encode($hooks_tag));
            foreach ($hooks_tag as $exist_hooks) {
                $hooks[] = $exist_hooks['topic'];
            }
            if (!in_array("app/uninstalled", $hooks)) {
                $uninstall_hook = array(
                    "webhook" => array(
                        "topic" => "app/uninstalled",
                        "address" => $base_url . "/web/index.php/app/uninstall?shop=" . $shopify_shop,
                        "format" => "json"
                    )
                );
                $uninstall_tag = $shopifyClient->call('POST', '/admin/webhooks.json', $uninstall_hook);
            }
        } catch (Exception $exc) {
            echo "<pre>";
            print_r($exc);
            die('hook');
        }
    }

    public static function addScriptTag($shopifyClient, $shopify_shop) {
        $filepath = "hooks.txt";
        $file = fopen($filepath, "a");
        fwrite($file, "\n add script - ");
        $base_url = Yii::$app->params['base_url'];
        $script_tag_array = array(
            "script_tag" => array(
                "event" => "onload",
                "src" => $base_url . "/web/js/shopify_script.js?shop=" . $shopify_shop
            )
        );
        $script_tag = $shopifyClient->call('POST', '/admin/script_tags.json', $script_tag_array);
        fwrite($file, "\n" . json_encode($script_tag));
    }

}
