<?php

namespace App\Core\Service;

use App\Core\Service\LanguageService;
use App\Core\Repository\PropertyWebContent\PropertyWebContentRepository;
use App\Core\Repository\PropertyWebContent\PropertyWebContentCategoryRepository;
use App\Core\Validator\Property\PropertyPhotoValidator;


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 Intervention\Image\Facades\Image;

class PropertyWebContentService
{

    private $languageService;
    private $propertyContentCreateValidator;
    private $propertyWebContentRepository;
    private $propertyWebContentCategoryRepository;
    private $propertyPhotoValidator;


    public function __construct(
        PropertyWebContentRepository $propertyWebContentRepository,
        PropertyWebContentCategoryRepository $propertyWebContentCategoryRepository,
        PropertyPhotoValidator $propertyPhotoValidator,
        LanguageService $languageService
    )
    {
        $this->languageService = $languageService;
        $this->propertyWebContentRepository = $propertyWebContentRepository;
        $this->propertyWebContentCategoryRepository = $propertyWebContentCategoryRepository;
        $this->propertyPhotoValidator = $propertyPhotoValidator;
    }

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

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

            $insertData['slug'] = str_slug($insertData['title']);

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

            $userCreateResult = $this->propertyWebContentRepository->create($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $userCreateResult["data"];
            $response['status'] = 1;
            $response['data'] = $userData;


        } 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->propertyWebContentRepository->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->propertyWebContentCategoryRepository->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 {

            $param['slug'] = str_slug($param['title']);


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

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

        } 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->propertyWebContentRepository->findByCriteria($chekDataParam);
            if (empty($chekData)) {
                throw new Exception('You are not authorized to perform this action.');
            }

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

            $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-content/' . $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(300, 300)->encode($imageExtension, $quality)->orientate()->save($filePath . $fileName . '_thumbnail' . '.' . $fileExt);
            } else {

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

                $ratioThumbnail = 768 / 300;
                $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(300, 300)->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(300)->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-content/' . $params['property_id'] . '/' . $fileName . '.' . $fileExt,
                        'thumb' => Config::get('app.imageUrl') . '/property-web-content/' . $params['property_id'] . '/' . $fileName . '_thumbnail.' . $fileExt,
                        'fixed' => Config::get('app.imageUrl') . '/property-web-content/' . $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);
    }
}
