<?php

namespace app\controllers;

use Yii;
use app\models\AppSetup;
use app\components\Shopify;
use app\models\ProductsSvg;
use app\models\ProductsSvgSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use app\models\AlphabetsK3;
use app\models\MultipleCase;

//require 'vendor/autoload.php';
require '/var/www/html/basic/DropboxUploader.php';

//use tpmanc\imagick\Imagick;

/* SvgController implements the CRUD actions for ProductsSvg model.
 */

class SvgController extends Controller {

    /**
     * @inheritdoc
     */
    public $enableCsrfValidation = false;

    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                    'deleteSVG' => ['POST'],
                ],
            ],
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    // restrict access to domains:
                    'Origin' => static::allowedDomains(),
                    'Access-Control-Request-Method' => ['POST'],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age' => 3600, // Cache (seconds)
                ],
            ],
        ];
    }

    public static function allowedDomains() {
        return [
            // '*'                    // star allows all domains ,
            'https://everythingetched-dev.myshopify.com', 'https://ee-design-store.myshopify.com'
        ];
    }

    /**
     * @inheritdoc
     */

    /**
     * Lists all ProductsSvg models.
     * @return mixed
     */
    public function actionIndex() {

        $app_secret = Yii::$app->params['app_secret'];
        $app_key = Yii::$app->params['app_key'];
        $session = Yii::$app->session;
        $shop = $session->get('shop');
        $app_installed = AppSetup::find()->Where(['shopify_shop' => $shop])->one();
        if (!empty($app_installed)) {
            $shopify_token = $app_installed->shopify_token;
        }
        $sc = new Shopify($shop, $shopify_token, $app_key, $app_secret);
        $shop_details = $sc->call('GET', '/admin/shop.json');
        $shop_id = $shop_details['id'];

        $searchModel = new ProductsSvgSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $shop_id);

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

    /**
     * Displays a single ProductsSvg 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),
        ]);
    }

    /**
     * Creates a new ProductsSvg model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new ProductsSvg();
        $session = Yii::$app->session;
        $shop = $session->get('shop');
        //echo $shop;die;
        $app_secret = Yii::$app->params['app_secret'];
        $app_key = Yii::$app->params['app_key'];
        $app_installed = AppSetup::find()->Where(['shopify_shop' => $shop])->one();
        if (!empty($app_installed)) {
            $shopify_token = $app_installed->shopify_token;
        }
        $sc = new Shopify($shop, $shopify_token, $app_key, $app_secret);
        $shop_details = $sc->call('GET', '/admin/shop.json');
        $shop_id = $shop_details['id'];
        $added_products = ProductsSvg::find()->select('product_id')->where(['shop_id' => $shop_id])->one();
        $added_products_array = array();
        if ($added_products) {
            foreach ($added_products as $key => $value) {
                if ($value) {
                    array_push($added_products_array, $value);
                }
            }
        }
        $products_list_options = array();
        $products_list = $sc->call('GET', '/admin/products.json');
        foreach ($products_list as $key => $value) {
            if (!in_array($value['id'], $added_products_array)) {
                $id = (string) $value['id']; // change id to string 
                $products_list_options[$id] = $value['title'];
            }
        }
        $post = $model->load(Yii::$app->request->post());
        //echo "<pre>";print_r(Yii::$app->request->post());die;
        if ($post) {
            $products_list = $sc->call('GET', '/admin/products/' . $model->product_id . '.json');
            $model->shop_id = $shop_id;
            $model->created_at = date('Y-m-d H:i:s', time());
            $model->product_title = $products_list['title'];
            $model->product_image = $products_list['image']['src'];
            if ($model->save(false)) {
                Yii::$app->session->setFlash('success', 'Your data has been saved Successfully!');
                return $this->redirect(['index']);
            }
        }
        return $this->render('create', [
                    'model' => $model, 'data' => $products_list_options
        ]);
    }

    /**
     * Updates an existing ProductsSvg model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);
        $post = $model->load(Yii::$app->request->post());
        //echo "<pre>";print_r(Yii::$app->request->post());die;
        if ($post) {
            $model->updated_at = date('Y-m-d H:i:s', time());
            if ($model->save(false)) {
                Yii::$app->session->setFlash('success', 'Your data has been saved Successfully!');
            }
            return $this->redirect(['index']);
        }


        return $this->render('update', [
                    'model' => $model
        ]);
    }

    /**
     * Deletes an existing ProductsSvg model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

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

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

    public function actionDeletesvg() {
        $id = Yii::$app->request->post('id');
        $svg_img = Yii::$app->request->post('svg_img');
        // return json_encode($svg_img);
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost) {

            $model->$svg_img = "";
            if ($model->save(false)) {
                return true;
            }
        }
        return false;
    }

    public function actionGetsvg() {
        $id = Yii::$app->request->get('p_id');
        $model = ProductsSvg::find()->Where(['product_id' => $id])->one();
        $product_image_type = $model->product_image_type;

        if ($product_image_type == 'alphabet') {
            $alphabets = AlphabetsK3::find()->all();
            $result = "<option value=''>-- Please select an alphabet --</option>";
            foreach ($alphabets as $alphabet) {
                $result .= '<option value="' . $alphabet->id . '">' . $alphabet->name . '</option>';
            }
            $svg_image = $alphabets[0]['image'];
            $result2 = "";
        } else if ($product_image_type == 'multiple') {
            $records_data = MultipleCase::find()->all();
            $svg_image = $records_data[0]['svg_image'];
            $records = MultipleCase::find()->select('case_type')->distinct()->all();
            $result = "<option value=''>-- Please select a title --</option>";
            if (!empty($records)) {
                foreach ($records as $record) {
                    $title = $record->case_type;
                    $result .= '<option value="' . $title . '">' . $title . '</option>';
                }
            }
            $record_s = MultipleCase::find()->select('case_number')->distinct()->all();
            $result2 = "<option value=''>-- Please select a number --</option>";
            if (!empty($record_s)) {
                foreach ($record_s as $record) {
                    $number = $record->case_number;
                    $result2 .= '<option value="' . $number . '">' . $number . '</option>';
                }
            }
        } else {
            $result = 0;
            $result2 = 0;
        }

        $base_url = Yii::$app->params['base_url'];
        $svg_file = file_get_contents($base_url . '/web/uploads/' . $svg_image);

        $find_string = '<svg';
        $position = strpos($svg_file, $find_string);
        $svg_file_new = substr($svg_file, $position);

        return json_encode(['svg' => $svg_file_new, 'result' => $result, 'result2' => $result2]);
    }

    public function actionCreatenewsvg() {
        $base_url = Yii::$app->params['base_url'];
        $ref_no = Yii::$app->request->post('ref_no');
        $content = '<?xml version="1.0" encoding="UTF-8"?>' . Yii::$app->request->post('content');

        $imagick = new \Imagick();
        //$imagick->setFont("fonts/casy_cz.ttf");
        //$imagick->setFont("fonts/Chunkfive Ex.ttf");
        $imagick->readImageBlob($content);

        /* bmp settings */
        $imagick->setImageFormat("bmp");
        $imagick->resizeImage(1400, 1400, \imagick::FILTER_POINT, 0.8, 1);
        //$cropWidth = $imagick->getImageWidth();
        //$cropHeight = $imagick->getImageHeight();
//        $cropZoom = false;
//        if ($cropZoom) {
//            $newWidth = $cropWidth / 2;
//            $newHeight = $cropHeight / 2;
//
//            $imagick->cropimage(
//                $newWidth,
//                $newHeight,
//                ($cropWidth - $newWidth) / 2,
//                ($cropHeight - $newHeight) / 2
//            );
//
//            $imagick->scaleimage(
//                $imagick->getImageWidth() * 4,
//                $imagick->getImageHeight() * 4
//            );
//        }


        if (file_put_contents("svg_created_images/$ref_no.bmp", $imagick)) {
            return json_encode($ref_no . '.bmp');
        }
    }

    public function actionChangesvg() {
        //$id = Yii::$app->request->post('p_id');
        $base_url = Yii::$app->params['base_url'];
//        $usmap = $base_url . '/web/uploads/DADEST_2.svg';
//        $im = new \Imagick();
//        $svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?' . file_get_contents($usmap);
//        $im->readImageBlob($svg);
//
//        /* png settings */
//        $im->setImageFormat("bmp");
//        $im->resizeImage(400, 250, \imagick::FILTER_LANCZOS, 1);  /* Optional, if you need to resize */
//        header("Content-Type: image/bmp");
//        $img = $im->getImageBlob();
//        echo $img;
        //file_put_contents('svg_created_images/testt.bmp', $im);
//        $base_url = Yii::$app->params['base_url'];
//        $id = Yii::$app->request->post('p_id');
//        $content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?' . Yii::$app->request->post('content');
        //DADEST_1b
        $usmap = $base_url . '/web/uploads/test.svg';
        //echo $usmap;die;
        $imagick = new \Imagick();
        //$imagick->setFont("fonts/casy_cz.ttf");
        $svg = file_get_contents($usmap);
        $svg1 = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $svg;
        $imagick->readImageBlob($svg1);
//        var_dump($svg1); die('wa');
        //        echo $svg1;die;
        /* bmp settings */
        $imagick->setImageFormat("bmp");
        //$imagick->adaptiveResizeImage(150, 150);
        //$imagick->resizeImage(1400, 1400, \imagick::FILTER_LANCZOS, 1);
        header("Content-Type: image/bmp");
        $img = $imagick->getImageBlob();
        echo $img;
    }

    public function actionSave() {

        $access_token = Yii::$app->request->get('access_token');
        echo $access_token;
    }

    public function actionSaveimage() {
        $url = $base_url . '/web/uploads/DADEST_55.svg';
        //paste a temporary token from https://dev.onedrive.com/auth/msa_oauth.htm
//        $token = 'EwBwA8l6BAAURSN/FHlDW5xN74t6GzbtsBBeBUYAATtLJrWGZH43NBcXkHLXE2ga86OsPiYRfQ98NxN4vzdktbVvx4Tgi9AjGkQt/V8JtKVV4Nj5C98cAywEIl4npaJeHXZ5PzTNzUClg8JbU0zVTr1lTNimzAELN7KN7JRRIcOBu93Zdb3svsnfrUOVCO30Y3jUjc6fJH%2b%2brbP/j/gzNQ246PRx7dZWfWH7rYW7OXLF5r9aW1JTHmI2vns67M4rzmaBdZzWyFDxAZeHCBUrVtCIAylpQaPNMW1iV%2bRY1/fat4PVHWRK88lDOxIFUoNpWqzBi68NW9f7dlTfp/QGHn0mNzjp3NzLuggLg1mEauos85MxN%2bUxD1EBgeD3kn8DZgAACAgi42ba0oyoQAJTRvBste9rWQVhVJjLGuT3NEXPm6npzIsPFgbMYyy4srG/nejEgnfSmUXI8wq4SgY9zTLedRPvylCYk7RAUeFty9KkqLqch2leKxEIPPjKhF1I4L7IaLxVlKElLI%2bjL6J22u1YQGopHHScGzaC3BL3qij%2by9qWb6kCDp6Wjj%2bMxZZbFlGrr%2bOPTAq1VENgSUp7k0zjcLFXtDUHB7khmBj%2bkXjEvwQdJ0OSmnYr7lHuXQYI7YheIR%2breEmyoxqIl7WI3DV27CM54g%2bcv6oemKJWsWHlQercrHkX49ZXqgsFFN5147OPcoQAJc/v9G15iJCDGI1uH%2bM0w5PwlCLOJ9uRsLxh44IxM1a%2bgDKSeZEvi/gs3CSH4/pxzNjmbqPM0jG%2bkkairfsCgexit5NoXsgk8W2ONPQGI7eYxU5gVEgaZF/FPzNPJ94Efs0fUbWZicvVYvrpNbnbTNWSUaeOzqBPyN%2bDMEHfP7xSjXcSsAU7hzD1AxlgDAI3H895wS/KdehBLmrZO/AjETEN532T6ssMu4%2bxqDM7pN6cI5T7xd0C%2bueFGUlooATg%2bURzHqNUska9pV%2bvRbwqCsvfvAAbAPrKvB1hvNLMSyWoacwXSGnDqun0BAQdLESpaWLWp/uQJoEuZNcG2DltiujqMEjKFTsjCDd%2bf5jig57DYdfIUD/KQpN4Q2GsQddmxosC0a2rsNgdOJg9VWzRvUn/Bm0ZE33eA59SiitVNvA7q4vptnuyAYAx8r5SbwqvIBCMOI6mpzyQAg%3d%3d';
//
//        $oneDriveClient = new \JacekBarecki\FlysystemOneDrive\Client\OneDriveClient($token, new \GuzzleHttp\Client());
//        $oneDriveAdapter = new \JacekBarecki\FlysystemOneDrive\Adapter\OneDriveAdapter($oneDriveClient);
        $uploader = new DropboxUploader('preeti.nautiyal@brihaspatitech.com', 'developer981');
        $uploader->upload($url);
    }

    public function actionChangeSvgImage() {
        $title = $_POST['title'];
        $number = $_POST['number'];
        $base_url = Yii::$app->params['base_url'];
        $model = MultipleCase::find()->Where(['case_number' => $number])->andWhere(['case_type' => $title])->one();
        if (!empty($model)) {
            $svg_file = file_get_contents($base_url . '/web/uploads/' . $model->svg_image);
            if (!empty($svg_file)) {
                $find_string = '<svg';
                $position = strpos($svg_file, $find_string);
                $svg_file_new = substr($svg_file, $position);
                return json_encode($svg_file_new);
            } else {
                $no_svg = '<div class="no_svg" style="min-height: 150px; text-align: center; font-size: 24px;padding-top: 50px;">No svg image..</div>';
                return json_encode($no_svg);
            }
        }
    }

    public function actionChangeAlphaSvg() {
        $base_url = Yii::$app->params['base_url'];
        $alpha_id = $_POST['value'];
        $Alphabets = AlphabetsK3::find()->where(['id' => $alpha_id])->one();
        if (!empty($Alphabets)) {
            $svg_file = file_get_contents($base_url . '/web/uploads/' . $Alphabets->image);
            if (!empty($svg_file)) {
                $find_string = '<svg';
                $position = strpos($svg_file, $find_string);
                $svg_file_new = substr($svg_file, $position);
                return json_encode($svg_file_new);
            }
        }
    }

    public function actionUploadimage() {
        $base_url = Yii::$app->params['base_url'];
        $img = $base_url . '/web/uploads/DADEST_55.svg';
//        curl -X POST https://content.dropboxapi.com/2/files/upload \
//    --header "Authorization: Bearer " \
//    --header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}" \
//    --header "Content-Type: application/octet-stream" \
//    --data-binary @local_file.txt

        $curl = curl_init();
        $url = 'https://content.dropboxapi.com/2/files/upload';
        $data = $img;
        //switch ($method) {
        //case "POST":
        curl_setopt($curl, CURLOPT_POST, 1);
//                if ($data)
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//                break;
//            case "PUT":
//                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
//                if ($data)
//                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//                break;
//            default:
//                if ($data)
//                    $url = sprintf("%s?%s", $url, http_build_query($data));
        //}
        // OPTIONS:
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            //'Content-Type: application/x-www-form-urlencoded',
            //$header
            "Authorization: Bearer RVrX-eCvGlAAAAAAAAAAIcJ7J4KzAfjc-2by7kzFrPTp2UqEkqaPe7tPyfgmpxxc",
            "Dropbox-API-Arg: {\"path\": \"/Homework/math\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}",
            "Content-Type: application/octet-stream"
                //data-binary @local_file.txt
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        // EXECUTE:
        $result = curl_exec($curl);
        if (!$result) {
            die("ConnectionÂ Failure");
        }
        curl_close($curl);
        echo "<pre>";
        print_r($result);
    }

}
