<?php


namespace App\Http\Controllers\V1;

use App\Core\Service\LanguageService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyWebService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Exception;

class PropertyWebComponentController extends Controller
{

    private $params;
    private $propertyChannelMappingService;
    private $languageService;


    public function __construct(
        PropertyWebService $propertyWebService,
        PropertyChannelMappingService $propertyChannelMappingService,
        LanguageService $languageService
    )
    {
        $this->params = Input::all();
        $this->params = $this->params['params'];
        $this->propertyWebService = $propertyWebService;
        $this->propertyChannelMappingService = $propertyChannelMappingService;
        $this->languageService = $languageService;
    }


    public function getPropertyWebComponent(Request $request)
    {

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

        try {

            //TODO: Validator

            $propertyWebComponentCriteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ]
            ];

            $propertyWebComponent = $this->propertyWebService->selectPropertyWebComponent($propertyWebComponentCriteria);
            $propertyWebComponent = $propertyWebComponent['status'] == 'success' && !empty($propertyWebComponent['data']) ? $propertyWebComponent['data'] : [];


            $propertyWebComponentMappingCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
                    ['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['channel_id']],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ]
            ];

            $propertyWebComponentMapping = $this->propertyWebService->selectPropertyWebComponentMapping($propertyWebComponentMappingCriteria);
            $propertyWebComponentMapping = $propertyWebComponentMapping['status'] == 'success' && !empty($propertyWebComponentMapping['data']) ? $propertyWebComponentMapping['data'] : [];
            $propertyChannelAddonCollect = collect($propertyWebComponentMapping);

            $propertyWebComponentList = [];
            foreach ($propertyWebComponent as $webComponentKey => $webComponent) {

                $webComponentMapping = $propertyChannelAddonCollect->where('component_id', $webComponent['id'])->first();

                $webComponentDetail = null;
                $isSelected = $webComponentMapping ? true : false;

                if ($webComponentMapping) {
                    $webComponentDetail = [
                        'component_id' => $webComponentMapping['component_id'],
                        'parameterArray' => $webComponentMapping['parameterArray'],
                        'language' => $webComponentMapping['language'],
                        'languageArray' => $webComponentMapping['languageArray'],
                    ];
                }


                $propertyWebComponentList[] = [
                    //'code' => $webComponent['code'],
                    'id' => $webComponent['id'],
                    'name' => $webComponent['name'],
                    'component' => $webComponent['component'],
                    'icon' => $webComponent['icon'],
                    'iconUrl' => $webComponent['iconUrl'],
                    'parameterArray' => $webComponent['parameterArray'],
                    'is_selected' => $isSelected,
                    'componentDetail' => $webComponentDetail
                ];

            }


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

        } 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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

    public function syncPropertyWebComponent(Request $request)
    {

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

        try {


            $propertyWebComponentCriteria = [
                'criteria' => [
                    ['field' => 'id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'component_id')],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
                'firstRow' => true
            ];

            $propertyWebComponent = $this->propertyWebService->selectPropertyWebComponent($propertyWebComponentCriteria);
            $propertyWebComponent = $propertyWebComponent['status'] == 'success' && !empty($propertyWebComponent['data']) ? $propertyWebComponent['data'] : [];

            if(empty($propertyWebComponent)){
                throw new ApiErrorException(lang('Component data not found'));
            }


            //Parameter Check
            if (!empty($this->params['componentDetail'])) {

                $parameterCheck = array_diff(array_keys($propertyWebComponent['parameterArray']),array_keys($this->params['componentDetail']['parameter']));
                if(!empty($parameterCheck)) {
                    throw new ApiErrorException(lang('Missing or incorrect parameter'));
                }
            }


            $propertyWebComponentMappingCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'property_id')],
                    ['field' => 'channel_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'channel_id')],
                    ['field' => 'component_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'component_id')],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
                'firstRow' => true
            ];

            $propertyWebComponentMapping = $this->propertyWebService->selectPropertyWebComponentMapping($propertyWebComponentMappingCriteria);
            $propertyWebComponentMapping = $propertyWebComponentMapping['status'] == 'success' && !empty($propertyWebComponentMapping['data']) ? $propertyWebComponentMapping['data'] : [];


            //Parameter Check


            DB::beginTransaction();

            if ($propertyWebComponentMapping) {


                //Remove
                if (empty($this->params['componentDetail'])) {

                    $syncPropertyWebComponent = $this->propertyWebService->deletePropertyWebComponentMapping($propertyWebComponentMapping['id']) ;
                    if($syncPropertyWebComponent['status'] != 'success'){
                        throw new Exception('api-unknown_error');
                    }

                } else {

                    //Update
                    $updateParam = [
                        'property_id' => fillOnUndefined($this->params, 'property_id'),
                        'channel_id' => fillOnUndefined($this->params, 'channel_id'),
                        'component_id' => fillOnUndefined($this->params, 'component_id'),
                        'parameter' => fillOnUndefined($this->params['componentDetail'], 'parameter') ? json_encode($this->params['componentDetail']['parameter']) : null,
                        'language' => fillOnUndefined($this->params['componentDetail'], 'language') ? json_encode($this->params['componentDetail']['language']) : null,
                        'updated_by' => $request->auth->id,
                    ];

                    $syncPropertyWebComponent = $this->propertyWebService->updatePropertyWebComponentMapping($propertyWebComponentMapping['id'], $updateParam);

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

                }

            } else {

                $createParam = [
                    'property_id' => fillOnUndefined($this->params, 'property_id'),
                    'channel_id' => fillOnUndefined($this->params, 'channel_id'),
                    'component_id' => fillOnUndefined($this->params, 'component_id'),
                    'parameter' => fillOnUndefined($this->params['componentDetail'], 'parameter') ? json_encode($this->params['componentDetail']['parameter']) : null,
                    'language' => fillOnUndefined($this->params['componentDetail'], 'language') ? json_encode($this->params['componentDetail']['language']) : null,
                    'status' => 1,
                    'created_by' => $request->auth->id,
                ];

                $syncPropertyWebComponent = $this->propertyWebService->createPropertyWebComponentMapping($createParam);

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

            }


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

        } 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;
        }

        if ($response['status']) {
            DB::commit();
        } else {
            DB::rollBack();
        }

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

    }


}

