<?php

namespace App\Http\Controllers\V1;


use App\Core\Service\PropertyService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Core\Service\PropertyPhotoService\PropertyPhotoService;
use App\Core\Service\Google\GoogleVisionLabelService;
use Exception;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use App\Core\Service\PropertyConfigService;
use Illuminate\Support\Str;
use ZipArchive ;

class PropertyPhotoController extends Controller
{

    private $request;
    private $propertyPhotoService;
    private $googleVisionLabelService;
    private $propertyConfigService;
    private $propertyService;

    public function __construct
    (
        PropertyPhotoService $propertyPhotoService,
        PropertyService $propertyService,
        GoogleVisionLabelService $googleVisionLabelService,
        PropertyConfigService $propertyConfigService
    )
    {
        $this->propertyPhotoService = $propertyPhotoService;
        $this->googleVisionLabelService = $googleVisionLabelService;
        $this->propertyConfigService = $propertyConfigService;
        $this->propertyService = $propertyService ;
    }

    public function getPropertyPhotos(Request $request)
    {
        $response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];

        try
        {
            if ( is_null( $request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = json_decode($request->getContent(),1);
            $params = current($params);

            //TODO : Validation Yapılması gerekiyor.
            $response = $this->propertyPhotoService->getPropertyPhotos($params);

        }catch (ApiErrorException $e)
        {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function uploadPropertyPhoto(Request $request)
    {
        $response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
        try
        {
            if(!$request->hasFile('image'))
            {
                throw new ApiErrorException(lang('Photos not found'));
            }

            $propertyId        = $request->input('property_id');
            $photo             = $request->file('image');

            $param =
                [
                    "property_id" => $propertyId,
                    "photo"      => $photo,
                ];

            $response = $this->propertyPhotoService->propertyPhotoUploadFilter($param);

            $rateParams = [
                'property_id' => $propertyId,
                'user_id' => 1,
                'property_rate_for' => 'Property.Photo.Upload',
            ];
            $this->propertyConfigService->rateProperty($rateParams);


        }catch (ApiErrorException $e)
        {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function setDefaultPhoto(Request $request)
    {
        $response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];

        try
        {
            if ( is_null( $request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = json_decode($request->getContent(),1);
            $params = current($params);
            //TODO : Validation Yapılması gerekiyor.
            $response = $this->propertyPhotoService->setDefaultPhoto($params);



        }catch (ApiErrorException $e)
        {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function setPropertyPhotoOrder(Request $request)
    {
        $response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];

        try
        {
            if ( is_null( $request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = json_decode($request->getContent(),1);
            $params = current($params);


            $requestParams = [
                'locale' => fillOnUndefined($params, 'locale'),
                'set_photo_order' => fillOnUndefined($params, 'set_photo_order'),
                'property_id' => fillOnUndefined($params, 'property_id'),
                'user_id' => $request->credentials->user_id,
            ];

            //TODO : Validation Yapılması gerekiyor.
            $response = $this->propertyPhotoService->setPhotoOrder($requestParams);

        }catch (ApiErrorException $e)
        {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function publishPhotos(Request $request)
    {

        $response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];

        try
        {
            if ( is_null( $request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = json_decode($request->getContent(),1);
            $params = current($params);

            //TODO : Validation Yapılması gerekiyor.
            $response = $this->propertyPhotoService->publishPhotos($params);

        }catch (ApiErrorException $e)
        {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function deletePropertyPhotos(Request $request)
    {
        $response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];

        try
        {
            if ( is_null( $request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = json_decode($request->getContent(),1);
            $params = current($params);

            //TODO : Validation Yapılması gerekiyor.
            $deletePhoto = $this->propertyPhotoService->deletePhotos($params);
            if ($deletePhoto['status'] == false) {
                throw new ApiErrorException($deletePhoto['message']);
            }

            $defaultPhotoCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'is_default', 'condition' => '=', 'value' => 1],
                ],
                'firstRow' => 1
            ];

            $propertyPhotoData = $this->propertyPhotoService->select($defaultPhotoCriteria, ['id']);
            if ($propertyPhotoData['status'] == false) {
                throw new ApiErrorException($propertyPhotoData['message']);
            }

            $defaultPhoto = isset($propertyPhotoData['data']['id']) ? $propertyPhotoData['data']['id'] : null ;

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['default_photo' => $defaultPhoto] ];


        }catch (ApiErrorException $e)
        {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function setPropertyPhotoCategory(Request $request)
    {
        $response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];

        try
        {
            if ( is_null( $request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = json_decode($request->getContent(),1);
            $params = current($params);


            $requestParams = [
                'locale' => fillOnUndefined($params, 'locale'),
                'property_id' => fillOnUndefined($params, 'property_id'),
                'user_id' => $request->credentials->user_id,
                'set_photo_category' => fillOnUndefined($params, 'set_photo_category'),
            ];

            //TODO : Validation Yapılması gerekiyor.
            $response = $this->propertyPhotoService->setPhotoCategory($requestParams);



        }catch (ApiErrorException $e)
        {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }


    public function downloadPropertyPhotos(Request $request)
    {

        $response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
        try {
            if (is_null($request->getContent())) {
                throw new Exception('api-unknown_error');
            }
            $params = json_decode($request->getContent(), 1);
            $params = current($params);
            $responseData = null ;
            $propertyId = $params['property_id'];
            $getPhotosRequest = [
                'property_id' => $propertyId
            ];

            if(isset($params['custom']) && !empty($params['custom'])) {
                $getPhotosRequest['custom'] = $params['custom'];
            }

            $response = $this->propertyPhotoService->getPropertyPhotos($getPhotosRequest);

            if ($response['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            if (!$response['data']) {
                throw new Exception('api-unknown_error');
            }
            $photos = $response['data'];

            if ($photos) {
                $public_dir = public_path();
                $zipFileStoragePath = $public_dir . '/property-zip-files';
                $propertyRequest = [
                    'criteria' => [
                        ['field' => 'id', 'condition' => '=', 'value' => $propertyId],
                    ],
                    'firstRow' => true
                ];
                $thisProperty = $this->propertyService->select($propertyRequest);
                if ($thisProperty['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
                $hotelName = Str::slug($thisProperty['data']['name'], '_', 'en');
                if (!File::exists($zipFileStoragePath)) {
                    File::makeDirectory($zipFileStoragePath, 0777, true);
                }
                $zipFileName = $hotelName . '_photos.zip';
                $zip = new ZipArchive;
                if(file_exists($zipFileStoragePath . '/' . $zipFileName)) {
                    unlink($zipFileStoragePath . '/' . $zipFileName);
                }

                if ($zip->open($zipFileStoragePath . '/' . $zipFileName, ZipArchive::CREATE) === TRUE) {
                    foreach ($photos as $photo) {
                        $photoUrlFilePath = Config::get('app.fileSystemDriver') . "/property-photos/{$photo['property_id']}" . "/{$photo['photo_name']}_medium.{$photo['file_ext']}";
                        $fileName = "{$photo['photo_name']}_medium.{$photo['file_ext']}";
                        if (file_exists($photoUrlFilePath)) {
                            $zip->addFile($photoUrlFilePath, $fileName);
                        }
                    }
                    $zip->close();
                }
                $responseData = Config::get('app.zipFilesUrl').$zipFileName;
            }
            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['zipFile' => $responseData]];
        } catch (ApiErrorException $e) {
            $response['message'] = $e->getMessage();

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

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

}
