<?php

namespace App\Core\Service;

use App\Core\Service\LanguageService;
use App\Core\Repository\PropertyWebPopup\PropertyWebPopupRepository;
use App\Core\Validator\Property\PropertyPhotoValidator;
use App\Core\Repository\PropertyWeb\PropertyWebRepository;


use App;
use Carbon\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Redis;
use Intervention\Image\Facades\Image;

class PropertyWebPopupService
{

    private $languageService;
    private $propertyWebPopupRepository;
    private $propertyPhotoValidator;


    public function __construct(
        PropertyWebPopupRepository $propertyWebPopupRepository,
        PropertyPhotoValidator $propertyPhotoValidator,
        LanguageService $languageService,
        PropertyWebRepository $propertyWebRepository
    )
    {
        $this->languageService = $languageService;
        $this->propertyWebPopupRepository = $propertyWebPopupRepository;
        $this->propertyPhotoValidator = $propertyPhotoValidator;
        $this->propertyWebRepository = $propertyWebRepository;
    }

    public function create($param = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $codeParams = [];
            $codeParams[] = fillOnUndefined($param, "property_id");
            $codeParams[] = fillOnUndefined($param, "title");
            $codeParams[] = fillOnUndefined($param, "language_code");
            $codeParams[] = fillOnUndefined($param, "start_date");
            $codeParams[] = fillOnUndefined($param, "end_date");
            $code = md5(implode('-', $codeParams));

            $insertData = [
                "code" => $code,
                "property_id" => fillOnUndefined($param, "property_id"),
                "title" => fillOnUndefined($param, "title"),
                "language_code" => fillOnUndefined($param, "language_code"),
                "image" => fillOnUndefined($param, "image"),
                "start_date" => fillOnUndefined($param, "start_date"),
                "end_date" => fillOnUndefined($param, "end_date"),
                "url" => fillOnUndefined($param, "url"),
                "status" => fillOnUndefined($param, "status", 1),
                "created_by" => fillOnUndefined($param, "user_id"),
                "updated_by" => fillOnUndefined($param, "user_id"),
                "created_at" => time(),
                "updated_at" => time(),
            ];

            //TODO: be activate validator
            /*$validationResult = $this->propertyContentCreateValidator->validate($insertData);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }*/

            $createResult = $this->propertyWebPopupRepository->create($insertData);
            if ($createResult['status'] != 'success') {
                throw new ApiErrorException('api-unknown_error');
            }

            $response['status'] = 1;
            $response['data'] = $createResult["data"];

            //Domain Cache Clean
            $propertyRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($param, 'property_id')],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ], 'firstRow' => true
            ];
            $propertyWebData = $this->propertyWebRepository->findByCriteria($propertyRequest, ['id', 'domain']);

            if ($propertyWebData) {
                $checkDomainStatusCacheKey = 'myweb:' . md5('checkDomainStatus-' . $propertyWebData['domain'] . '-' . Carbon::now()->toDateString());
                if (!empty(Redis::executeRaw(['KEYS', $checkDomainStatusCacheKey]))) {
                    Redis::executeRaw(['DEL', $checkDomainStatusCacheKey]);
                }
            }
            //Domain Cache Clean


        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function select($param = [], $column = ['*'])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->propertyWebPopupRepository->findByCriteria($param, $column);

            if (!$data) {
                throw new ApiErrorException(lang('Data is not found.'));
            }

            $response['status'] = 1;
            $response['data'] = $data;


        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function selectWebContentCategory($param = [], $column = ['*'])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->propertyWebPopupRepository->findByCriteria($param, $column);

            if (!$data) {
                throw new ApiErrorException(lang('Data is not found.'));
            }

            $response['status'] = 1;
            $response['data'] = $data;


        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function update($id, $param = [])
    {


        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {


            $chekDataParam = [
                'criteria' => [
                    ['field' => 'id', 'condition' => '=', 'value' => $id],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $param['property_id']],
                ],
                'firstRow' => true
            ];
            $chekData = $this->propertyWebPopupRepository->findByCriteria($chekDataParam);
            if (empty($chekData)) {
                throw new Exception('You are not authorized to perform this action.');
            }


            $updateResult = $this->propertyWebPopupRepository->update($id, $param);
            if ($updateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $updateData = $updateResult["data"];
            $response = [
                'status' => true,
                'data' => $updateData,
            ];

            //Domain Cache Clean
            $propertyRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($param, 'property_id')],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ], 'firstRow' => true
            ];
            $propertyWebData = $this->propertyWebRepository->findByCriteria($propertyRequest, ['id', 'domain']);

            if ($propertyWebData) {
                $checkDomainStatusCacheKey = 'myweb:' . md5('checkDomainStatus-' . $propertyWebData['domain'] . '-' . Carbon::now()->toDateString());
                if (!empty(Redis::executeRaw(['KEYS', $checkDomainStatusCacheKey]))) {
                    Redis::executeRaw(['DEL', $checkDomainStatusCacheKey]);
                }
            }
            //Domain Cache Clean

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function delete($id, $param = [])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {


            $chekDataParam = [
                'criteria' => [
                    ['field' => 'id', 'condition' => '=', 'value' => $id],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $param['property_id']],
                ],
                'firstRow' => true
            ];
            $chekData = $this->propertyWebPopupRepository->findByCriteria($chekDataParam);
            if (empty($chekData)) {
                throw new Exception('You are not authorized to perform this action.');
            }

            $deleteResult = $this->propertyWebPopupRepository->destroy([$id]);
            if ($deleteResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }

            $urlPath = '/property-web-popup/' . $param['property_id'] . "/";
            $filePath = Config::get('app.fileSystemDriver') . $urlPath;

            $fileExplode = explode('.', $chekData['image'], 2);
            $fileName = $fileExplode[0];
            $fileExt = $fileExplode[1];

            $fileCombinations = [];
            $fileCombinations[] = $filePath . $fileName . '.' . $fileExt;
            $fileCombinations[] = $filePath . $fileName . '_medium.' . $fileExt;
            $fileCombinations[] = $filePath . $fileName . '_thumbnail.' . $fileExt;

            foreach ($fileCombinations as $fileCombination) {
                if (file_exists($fileCombination)) {
                    File::delete($fileCombination);
                }
            }

            $response = [
                'status' => true
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function uploadPhoto($params = [])
    {

        $response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
        try {
            $validateParams = [
                'photo' => $params['photo']
            ];

            $uploadedFile = $params['photo'];
            $validationResult = $this->propertyPhotoValidator->validate($validateParams);
            if ($validationResult->errors()->first()) {
                throw new ApiErrorException($validationResult->errors()->all());
            }

            $uploadedOriginalImage = Image::make($uploadedFile);
            $imageWidth = $uploadedOriginalImage->width();
            $imageHeight = $uploadedOriginalImage->height();

            $fileExt = $uploadedFile->getClientOriginalExtension();
            $fileSize = (int)ceil(Image::make($uploadedFile)->filesize() / 1024);

            $imageExtension = 'jpg';
            $fileExt = $fileExt != $imageExtension ? $imageExtension : $fileExt;
            $quality = 80;

            $urlPath = '/property-web-popup/' . $params['property_id'] . "/";
            $filePath = Config::get('app.fileSystemDriver') . $urlPath;
            $fileName = md5(Carbon::now()->format('dmyHi') . '-' . md5($uploadedFile->getClientOriginalName()));

            if (!File::exists($filePath)) {
                File::makeDirectory($filePath, 0777, true);
            }

            $originalImageMustResize = ($imageHeight > 2000 || $imageWidth > 2000);

            if ($imageHeight < 768) {
                throw new ApiErrorException('image size error: minimum height must be 768px');
            }

            if ($imageHeight > $imageWidth) {

                $ratio = $imageHeight / 768;
                //$ratio200 = 768/200;
                $resizeWidth = intval($imageWidth / $ratio);
                //$resizeThumbWidth = intval($resizeWidth/$ratio200);

                if ($originalImageMustResize) {
                    $imageHRatio = $imageHeight / 2000;
                    $imageResizedOriginalWidth = intval($imageWidth / $imageHRatio);
                    $image = $uploadedOriginalImage->fit($imageResizedOriginalWidth, 2000)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '.' . $fileExt, $quality);
                } else {
                    $image = $uploadedOriginalImage->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '.' . $fileExt, $quality);
                }
                $image->fit($resizeWidth, 768)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '_medium' . '.' . $fileExt);
                $image->fit(600, 600)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '_thumbnail' . '.' . $fileExt);
            } else {

                $ratio = $imageHeight / 768;
                $resizeWidth = intval($imageWidth / $ratio);

                $ratioThumbnail = 768 / 600;
                $resizeThumbWidth = intval($resizeWidth / $ratioThumbnail);

                if ($originalImageMustResize) {
                    $imageWRatio = $imageWidth / 2000;
                    $imageResizedOriginalHeight = intval($imageHeight / $imageWRatio);
                    $image = $uploadedOriginalImage->fit(2000, $imageResizedOriginalHeight)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '.' . $fileExt, $quality);
                } else {
                    $image = $uploadedOriginalImage->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '.' . $fileExt, $quality);
                }

                if ($resizeWidth > 1599) {
                    $image->fit(1600, 768)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '_medium' . '.' . $fileExt);
                    $image->fit(600, 600)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '_thumbnail' . '.' . $fileExt);
                } else {
                    $image->fit($resizeWidth, 768)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '_medium' . '.' . $fileExt);
                    $image->fit(600)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '_thumbnail' . '.' . $fileExt);
                }

            }

            $response = [
                'status' => true,
                'data' => [
                    //'photo_path' => $urlPath,
                    //'photo_name' => $fileName,
                    'image' => $fileName . '.' . $fileExt,
                    //'file_size' => $fileSize,
                    //'file_ext' => $fileExt,
                    'image_resolution' => $imageWidth . 'x' . $imageHeight,
                    'imageUrl' => [
                        'default' => Config::get('app.imageUrl') . '/property-web-popup/' . $params['property_id'] . '/' . $fileName . '.' . $fileExt,
                        'thumb' => Config::get('app.imageUrl') . '/property-web-popup/' . $params['property_id'] . '/' . $fileName . '_thumbnail.' . $fileExt,
                        'fixed' => Config::get('app.imageUrl') . '/property-web-popup/' . $params['property_id'] . '/' . $fileName . '_medium.' . $fileExt,
                    ]

                ]
            ];

        } catch (Exception $e) {
            $message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['status'] = false;
        }

        return output($response);
    }
}
