<?php

namespace Modules\PrintSuppliers\Controllers;

use Illuminate\Http\Request;
use Modules\PrintSuppliers\Controllers\Controller;
use Module;
use Modules\PrintSuppliers\Models\Template;
use View;
use DB;

class HomeController extends Controller
{
    public function __construct()
    {
        // Module::onView("content", function () {
        //     return "This is content view from PrintSuppliers Module HomeController";
        // }, 5);
    }

    public function index(Request $request)
    {
        $markets = json_encode(\Config::get('localization::module.locales'));
        return view('print-suppliers::home.welcome', [
            'markets' => $markets
        ]);
    }

    public function stuckAutoFF(Request $request)
    {
        $markets = json_encode(\Config::get('localization::module.locales'));
        return view('print-suppliers::report.stuck-autoff', [
            'markets' => $markets
        ]);
    } 

    public function locateImageToFrame(Request $request)
    {

        $frameWidth = $request->input('fw');
        $frameHeight = $request->input('fh', $frameWidth);

        if ($frameWidth) {
            $designUrl = $request->input('i');
            $designUrl = urldecode($designUrl);
            $x = $request->input('x', 0);
            $y = $request->input('y', 0);

            $identify = $designUrl . $frameWidth . $frameHeight . $x . $y;
            $hashName = hash('sha256', $identify);
            $frameDesignDir = public_path('pod-storage/framed-design/');

            try {

                $partDesignUrl = explode('/', $designUrl);
                $fileName = end($partDesignUrl);
                $fileName = explode('.', $fileName)[0];

                if (file_exists($frameDesignDir . $fileName . '/' . $hashName . '.png')) {
                    return $this->returnFramedDesign($fileName . '/' . $hashName . '.png');
                }

                if (!file_exists($frameDesignDir . $fileName)) {
                    mkdir($frameDesignDir . $fileName, 0777, true);
                }

            } catch (\Exception $ex) {
                //throw $th;
            }

            $designBaseImage = imagecreatetruecolor($frameWidth, $frameHeight);
            imagesavealpha($designBaseImage, true);
            $color = imagecolorallocatealpha($designBaseImage, 0, 0, 0, 127); // alpha trong suốt
            imagefill($designBaseImage, 0, 0, $color);  // áp dụng kênh apha vào

            if ($designUrl) 
            {
                $imageInfo = getimagesize($designUrl);
                $imageType = $imageInfo[2];

                header('Content-type: image/png');

                switch ($imageType) {
                    case IMAGETYPE_JPEG:
                        $designImage = imagecreatefromjpeg($designUrl);
                        break;
                    case IMAGETYPE_PNG:
                        $designImage = imagecreatefrompng($designUrl);
                        break;
                }

                if (!$designImage) {
                    echo "Unsupported image type!"; die;
                }

                imageAlphaBlending($designImage, true);
                imageSaveAlpha($designImage, true);

                imagecopy($designBaseImage, $designImage, -$x, -$y, 0, 0, imagesx($designImage), imagesy($designImage));

                imagepng($designBaseImage, $frameDesignDir . $fileName . '/' . $hashName . '.png');
                imagedestroy($designBaseImage);

                return $this->returnFramedDesign($fileName . '/' . $hashName . '.png');
            }
        }

        abort(404);
    }

    function returnFramedDesign($fileName)
    {
        return [
            'imageUrl' => asset('pod-storage/framed-design/' . $fileName)
        ];

        /* $fp = fopen($fileName, 'rb');
        header("Content-Type: image/png");
        header("Content-Length: " . filesize($fileName));

        ob_clean();
        flush();

        fpassthru($fp);
        exit; */
    }

    public function indexTemplate () {
        $templates = Template::paginate(50);
        View::share('templates', $templates);
        return view('print-suppliers::template.index');
    }

    public function editTemplate ($id) {
        $template = Template::findOrFail($id);
        $template->enable = intval($template->enable);
        $template->blueprint_id = intval($template->blueprint_id);
        $template->print_provider_id = intval($template->print_provider_id);
        $template->variant_id = intval($template->variant_id);

        View::share('template', $template);
        return view('print-suppliers::template.edit');
    }

    public function updateTemplate ($id, Request $request) {
        $template = Template::findOrFail($id);
        $template->enable = $request->input('enable');
        $template->blueprint_id = $request->input('blueprint_id');
        $template->print_provider_id = $request->input('print_provider_id');
        $template->variant_id = $request->input('variant_id');
        $template->save();
        return $template;
    }
    public function toggleTemplate ($id) {
        $template = Template::findOrFail($id);
        $template->enable = !$template->enable;
        $template->save();
        return redirect()->back();
    }

    public function autoTemplate ($id) {
        $template = Template::findOrFail($id);
        $history = DB::table('fulfill_history')
            ->orderBy('id', 'desc')
            ->where('category_id', $template->category_id)
            ->where('color', $template->color)
            ->where('size', $template->size)
            ->where('type', $template->type)
            ->where('style', $template->style)
            ->first();
        return response()->json($history);
    }

    public function enableAllTemplates () {
        $templates = Template::all();
        foreach ($templates as $key => $template) {
            $template->enable = 1;
            $template->save();
        }
        return redirect('/print-suppliers/template/');
    }

    public function autoAllTemplates () {
        $templates = Template::all();
        foreach ($templates as $key => $template) {
            $history = DB::table('fulfill_history')
                ->orderBy('id', 'desc')
                ->where('category_id', $template->category_id)
                ->where('color', $template->color)
                ->where('size', $template->size)
                ->where('type', $template->type)
                ->where('style', $template->style)
                ->first();
            $template->blueprint_id = $history->blueprint_id;
            $template->print_provider_id = $history->print_provider_id;
            $template->variant_id = $history->variant_id;
            $template->save();
        }
        return redirect('/print-suppliers/template/');
    }

    public function autoResolution () {
        $templates = Template::all();
        foreach ($templates as $key => $template) {
            $blueprintId = $template->blueprint_id;
            $printProviderId = $template->print_provider_id;
            $template->resolution = $this->getResolution($blueprintId, $printProviderId);
            $template->save();
        }
    }

    public function getResolution ($blueprintId, $printProviderId) {
        $resolution = '';
        try {
            $curl = curl_init();

            curl_setopt_array($curl, array(
              CURLOPT_URL => "https://api.printify.com/v1/catalog/blueprints/$blueprintId/print_providers/$printProviderId/variants.json",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'GET',
              CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIzN2Q0YmQzMDM1ZmUxMWU5YTgwM2FiN2VlYjNjY2M5NyIsImp0aSI6ImNjMDkxMTgxYTE0ZjFiNDgyZGM4YzY4MWYyNTI3ZjcyZDA2YWY4NWMxYjVhOWUxMDNiMzE0NDRjZTVmMWFjNzgwMDYyYjQ1MTJkNzFkNTNiIiwiaWF0IjoxNjM5Nzk4MTcxLCJuYmYiOjE2Mzk3OTgxNzEsImV4cCI6MTY3MTMzNDE3MSwic3ViIjoiNzY4NjY2NSIsInNjb3BlcyI6WyJzaG9wcy5tYW5hZ2UiLCJzaG9wcy5yZWFkIiwiY2F0YWxvZy5yZWFkIiwib3JkZXJzLnJlYWQiLCJvcmRlcnMud3JpdGUiLCJwcm9kdWN0cy5yZWFkIiwicHJvZHVjdHMud3JpdGUiLCJ3ZWJob29rcy5yZWFkIiwid2ViaG9va3Mud3JpdGUiLCJ1cGxvYWRzLnJlYWQiLCJ1cGxvYWRzLndyaXRlIiwicHJpbnRfcHJvdmlkZXJzLnJlYWQiXX0.AAG2k6eGgUrPbrSuL0Lpr1iIqiHzDB4nQXk0oCkr51rYSAPssVlwx-F74yjArhSC2GEZ_0n-CCZuAU6QZS0'
              ),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
            $response = json_decode($response);
            $response = $response->variants;
            $response = $response[0]->placeholders;
            $height = $response[0]->height;
            $width = $response[0]->width;
            $resolution = $width . 'x' . $height;
        } catch (\Exception $e) {
            \Log::info($e->getMessage());
        }


        return $resolution;
    }

    public function cronUpdateOrderMatching(Request $request) {
        set_time_limit(86400);
        $response = ["status" => "fail"];
        // $printifyController = new PrintifyController();
        $printifyController = app(PrintifyController::class);
        $gelatoController = new GelatoController();
        $dateStart = new \DateTime();
        $dateStart->modify("-3 days");
        $orderMatchingItems = \DB::table("order_matching_item")
            ->where("created_at", ">=", $dateStart->format("Y-m-d H:i:s"))
            ->whereIn("status", ["UPDATED", "PENDING"])
            ->get();
        foreach ($orderMatchingItems as $key => $item) {
            if ($item->resource_id) {
                $order = \DB::table("order")->where("id", $item->order_id)->first();
                $newOrderUpdate = null;
                if ($item->printing_code == 'printify') {
                    $newOrderUpdate = $printifyController->updatePrintifyOrderByGlt($item->resource_id, $order);
                } else if ($item->printing_code == 'gelato') {
                    $newOrderUpdate = $gelatoController->updateGltOrderByPrintify($item->resource_id, $order);
                }
                if ($newOrderUpdate) {
                    if ($item->status == 'PENDING') {
                        if ($newOrderUpdate["cost"] != $item->cost) {
                            \DB::table("order_matching_item")->where("id", $item->id)->update([
                                "cost" => $newOrderUpdate['cost'],
                                "shipping_cost" => $newOrderUpdate['shipping_cost'],
                                "status" => "UPDATED",
                                "updated_at" => new \Datetime()
                            ]);
                        }
                    } else if ($item->status == "UPDATED") {
                        if ($newOrderUpdate["cost"] == $item->cost) {
                            \DB::table("order_matching_item")->where("id", $item->id)->update([
                                "status" => "DONE",
                                "updated_at" => new \Datetime()
                            ]);
                        }
                    }
                }
            }
            
        }
        $response = ["status" => "successful"];
        return response()->json($response);
    }

}
