<?php

namespace App\Core\Service;

use App\Core\Repository\OfferPhotoMapping\OfferPhotoMappingRepository;
use App\Core\Validator\OfferPhotoMapping\OfferPhotoMappingCreateValidator;
use App\Core\Validator\OfferPhotoMapping\OfferPhotoMappingAddValidator;
use App\Core\Validator\OfferPhotoMapping\OfferCoverPhotoAddValidator;

use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;

class OfferPhotoMappingService
{

    private $offerPhotoMappingRepository;
    private $offerPhotoMappingCreateValidator;
    private $offerPhotoMappingAddValidator;
    private $offerCoverPhotoAddValidator;


    public function __construct(

        OfferPhotoMappingRepository $offerPhotoMappingRepository,
        OfferPhotoMappingCreateValidator $offerPhotoMappingCreateValidator,
        OfferCoverPhotoAddValidator $offerCoverPhotoAddValidator,
        OfferPhotoMappingAddValidator $offerPhotoMappingAddValidator
    )
    {
        $this->offerPhotoMappingRepository = $offerPhotoMappingRepository;
        $this->offerPhotoMappingCreateValidator = $offerPhotoMappingCreateValidator;
        $this->offerPhotoMappingAddValidator = $offerPhotoMappingAddValidator;
        $this->offerCoverPhotoAddValidator = $offerCoverPhotoAddValidator;
    }

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

            $validationResult = $this->offerPhotoMappingCreateValidator->validate($param);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $insertData =
                [
                    "offer_id" => fillOnUndefined($param, "offer_id"),
                    "property_photo_id" => fillOnUndefined($param, "property_photo_id"),

                    "status" => fillOnUndefined($param, "status", 0),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];

            $userCreateResult = $this->offerPhotoMappingRepository->create($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $userCreateResult["data"];
            $response = [
                'status' => true,
                '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->offerPhotoMappingRepository->findByCriteria($param, $column);

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

        } catch (ApiErrorException $e) {
            $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 {

            $updateResult = $this->offerPhotoMappingRepository->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 updateOrCreate($criteria = [], $saveData = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->offerPhotoMappingRepository->updateOrCreate($criteria, $saveData);
            if ($data['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $response = [
                'status' => true,
                'data' => $data,
            ];

        } catch (ApiErrorException $e) {
            $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 insertPhotoMapping($param = [])
    {

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

            $validationResult = $this->offerPhotoMappingAddValidator->validate($param);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $insertDataArray = [] ;
            foreach ($param['photo_mapping'] as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_photo_id" => $item,
                        "is_cover" => 0,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }
            $insertResult = $this->offerPhotoMappingRepository->createAll($insertDataArray);
            if ($insertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $insertResult["data"];
            $response = [
                'status' => true,
                '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 insertCoverPhotoMapping($param = [])
    {

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

            $validationResult = $this->offerCoverPhotoAddValidator->validate($param);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $insertDataArray = [] ;
            foreach ($param['cover_photos'] as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_photo_id" => $item,
                        "is_cover" => 1,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }
            $insertResult = $this->offerPhotoMappingRepository->createAll($insertDataArray);
            if ($insertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $insertResult["data"];
            $response = [
                'status' => true,
                '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 updatePhotoMapping($param = [], $offerPhotoMapping)
    {

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

            $validationResult = $this->offerPhotoMappingAddValidator->validate($param);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $insertThisIds = array_diff($param['photo_mapping'], $offerPhotoMapping);
            $deleteThisIds = array_diff($offerPhotoMapping, $param['photo_mapping']);

            $insertDataArray = [] ;
            foreach ($insertThisIds as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_photo_id" => $item,
                        "is_cover" => 0,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }
            $insertResult = $this->offerPhotoMappingRepository->createAll($insertDataArray);
            if ($insertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }


            $requestData = [
                'criteria' => [
                    ['field' => 'offer_id', 'condition' => '=', 'value' => fillOnUndefined($param, "offer_id")],
                ],
                "whereIn" =>
                    [
                        ["field" => "property_photo_id", "value" => $deleteThisIds]
                    ]
            ];
            $eraseMappingData = $this->offerPhotoMappingRepository->findByCriteria($requestData, ['id']);
            $eraseMappingData = $eraseMappingData ? $eraseMappingData : [] ;
            $deleteThisIds = collect($eraseMappingData)->keyBy('id')->keys()->all();

            if($deleteThisIds){
                $deleteThisArray = $this->offerPhotoMappingRepository->destroy($deleteThisIds);
                if ($deleteThisArray['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }



            $userData = $insertResult["data"];
            $response = [
                'status' => true,
                '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 updateCoverPhotoMapping($param = [], $offerCoverPhotoMapping)
    {

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


            $validationResult = $this->offerCoverPhotoAddValidator->validate($param);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }


            $insertThisIds = array_diff($param['cover_photos'], $offerCoverPhotoMapping);
            $deleteThisIds = array_diff($offerCoverPhotoMapping, $param['cover_photos']);


            $insertDataArray = [] ;
            foreach ($insertThisIds as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_photo_id" => $item,
                        "is_cover" => 1,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }
            $insertResult = $this->offerPhotoMappingRepository->createAll($insertDataArray);
            if ($insertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }


            $requestData = [
                'criteria' => [
                    ['field' => 'offer_id', 'condition' => '=', 'value' => fillOnUndefined($param, "offer_id")],
                ],
                "whereIn" =>
                    [
                        ["field" => "property_photo_id", "value" => $deleteThisIds]
                    ]
            ];
            $eraseMappingData = $this->offerPhotoMappingRepository->findByCriteria($requestData, ['id']);
            $eraseMappingData = $eraseMappingData ? $eraseMappingData : [] ;
            $deleteThisIds = collect($eraseMappingData)->keyBy('id')->keys()->all();

            if($deleteThisIds){
                $deleteThisArray = $this->offerPhotoMappingRepository->destroy($deleteThisIds);
                if ($deleteThisArray['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }



            $userData = $insertResult["data"];
            $response = [
                'status' => true,
                '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 destroy($params){

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

        try {
            $deleteCriteria = [
                'criteria' => [
                    ['field' => 'property_photo_id', 'condition' => '=', 'value' => $params['photo_id']],
                ]
            ];

            $deleteData = $this->offerPhotoMappingRepository->findByCriteria($deleteCriteria, ['id']);
            $deleteData = $deleteData ? $deleteData : [] ;
            if($deleteData){
                $deleteIds = array_column($deleteData, 'id') ;
                $destroyResult = $this->offerPhotoMappingRepository->destroy($deleteIds);
                if ($destroyResult['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

            $response = [
                'status' => true,
                'data' => null
            ];

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

        return output($response);


    }

}
