<?php

namespace App\Core\Service;

use App\Core\Service\LanguageService;
use App\Core\Repository\PropertyContentCategory\PropertyContentCategoryRepository;
use App\Core\Repository\PropertyContent\PropertyContentRepository;
Use App\Core\Validator\PropertyContent\PropertyContentCreateValidator ;



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

class PropertyContentService
{

    private $languageService;
    private $propertyContentCreateValidator ;
    private $propertyContentCategoryRepository;
    private $propertyContentRepository;


    public function __construct(
        PropertyContentCategoryRepository $propertyContentCategoryRepository,
        PropertyContentRepository $propertyContentRepository,
        PropertyContentCreateValidator $propertyContentCreateValidator,
        LanguageService $languageService
    )
    {
        $this->languageService = $languageService;
        $this->propertyContentCreateValidator = $propertyContentCreateValidator;
        $this->propertyContentCategoryRepository = $propertyContentCategoryRepository;
        $this->propertyContentRepository = $propertyContentRepository;
    }

    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"),
                    "content" => fillOnUndefined($param, "content"),
                    "locale" => fillOnUndefined($param, "locale"),
                    "status" => fillOnUndefined($param, "status", 0),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];

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

            $userCreateResult = $this->propertyContentRepository->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->propertyContentRepository->findByCriteria($param, $column);

            if (!$data) {
                throw new ApiErrorException(lang('User 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 {


            $updateResult = $this->propertyContentRepository->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->propertyContentRepository->updateOrCreate($criteria, $saveData);
            if ($data['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $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 propertyContent($params)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            $contentRequest = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'content_category_id', 'condition' => '=', 'value' => $params['category_id']],
                    ['field' => 'language_code', 'condition' => '=', 'value' => $params['language_code']],
                ]
            ];

            $contentData = $this->propertyContentRepository->findByCriteria($contentRequest, ['id', 'property_id', 'content_category_id', 'language_code', 'content']);

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

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

        return output($response);

    }

    public function propertyContentUpdate($params)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            $contentCollection = collect(fillOnUndefined($params, 'contents')) ;
            $updates = $contentCollection->where('content_id', '!=' , null)->toArray();

            // get all property contents
            $propertyContentRequest = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                ]
            ];
            $propertyContentResponse = $this->select($propertyContentRequest);

            if($propertyContentResponse['status'] != 'success'){
                throw new ApiErrorException(lang('Executive Data Not Loaded'));
            }
            $propertyContentCollection = collect($propertyContentResponse['data']);
            foreach ($contentCollection as $content){

                $contentCheck = $propertyContentCollection
                    ->where('property_id', '=', $params['property_id'])
                    ->where('content_category_id', '=', $content['category_id'])
                    ->where('locale', '=', $params['locale'])
                    ->first();

                if($contentCheck){
                    $saveData = [
                        'content' => $content['value'],
                        'updated_by' => $params['user_id'],
                    ];
                    $updateStatus = $this->update($contentCheck['id'], $saveData) ;

                    if($updateStatus['status'] != 'success'){
                        throw new Exception(lang('Not updated'));
                    }

                }else{

                    $saveData = [
                        'property_id' => $params['property_id'],
                        'content_category_id' => $content['category_id'],
                        'content' => $content['value'],
                        'locale' => $params['locale'],
                        'status' => 1,
                        'created_by' => $params['user_id'],
                        'updated_by' => $params['user_id'],

                    ];
                    $saveStatus = $this->create($saveData) ;
                    if($saveStatus['status'] != 'success'){
                        throw new ApiErrorException(lang('Not saved'));
                    }

                }

            }

            $requestParams = [

                'locale' => fillOnUndefined($params, 'locale'),
                'property_id' => fillOnUndefined($params, 'property_id'),

            ];
            $propertyContent = $this->propertyContent($requestParams);

            if($propertyContent['status'] != 'success'){
                throw new ApiErrorException($propertyContent['message']);
            }

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

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

        return output($response);

    }
}
