<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyWebMenuMapping\PropertyWebMenuMappingRepository;

use App;
use App\Core\Service\PropertyWebMenuService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;

class PropertyWebMenuMappingService
{

    private $propertyWebMenuMappingRepository;
    private $propertyWebMenuService;
    private $propertyPlaceService;




    public function __construct(
        PropertyWebMenuMappingRepository $propertyWebMenuMappingRepository,
        PropertyPlaceService $propertyPlaceService,
        PropertyWebMenuService $propertyWebMenuService
    )
    {
        $this->propertyWebMenuMappingRepository = $propertyWebMenuMappingRepository;
        $this->propertyWebMenuService = $propertyWebMenuService;
        $this->propertyPlaceService = $propertyPlaceService ;
    }

    public function select($param = [], $column = ['*'])
    {

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

        try {
            $data = $this->propertyWebMenuMappingRepository->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 createPropertyWebMenuMapping($param = []){

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            // TODO validation yazılmalı!

            $propertyWebMenuMappingResult = $this->propertyWebMenuMappingRepository->insert($param);

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

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

        } 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 getPropertyWebMenuMapping($params, $select = ['*']){

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

            $return = [];
            $searchCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'property_web_id', 'condition' => '=', 'value' => $params['property_web_id']],
                    ['field' => 'status', 'condition' => '=', 'value' => 1]
                ]
            ];

            $searchResult = $this->select($searchCriteria, $select);

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

            $return = $searchResult['data'];

            $response = ['statusCode' => 200, 'status' => true, 'message' => '', 'data' => ['property_web_menu_mapping' => $return ] ];
        } 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 updatePropertyWebMenuMapping($params = []){

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

            $return  = [];

            $getDeletePropertyWebMenuRequest =  [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_id')],
                    ['field' => 'property_web_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_web_id')]
                ]
            ];

            $status = null;
            if($params['action'] === "publish"){
                $status = 1;
            }else if($params['action'] === "preview"){

                $getDeletePropertyWebMenuRequest['criteria'][] = ['field' => 'status', 'condition' => '=', 'value' => 2];
                $status = 2;
            }


            $deleteWebMenuId = $this->propertyWebMenuMappingRepository->findByCriteria($getDeletePropertyWebMenuRequest, ['id']) ;
            $deleteWebMenuId = array_column($deleteWebMenuId, 'id') ;


            if (!empty($deleteWebMenuId)) {
                $destroyStatus = $this->propertyWebMenuMappingRepository->destroy($deleteWebMenuId);
                if ($destroyStatus['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

            $webMenus = $this->propertyWebMenuService->getPropertyWebMenu();
            if ($webMenus['status'] != 'success') {
                throw new ApiErrorException($webMenus['message']);
            }

            $placeRequest = [
                'property_id' => $params['property_id']
            ] ;
            $myPlaces = $this->propertyPlaceService->webMenuPlaceCategoriesAndPlaces($placeRequest);
            if ($myPlaces['status'] != 'success') {
                throw new ApiErrorException($myPlaces['message']);
            }
            $myPlaces = $myPlaces['data'] ;
            $myWebMenus = $webMenus['data']['property_web_menus'] ;
            $myWebMenus = array_merge($myWebMenus, $myPlaces) ;
            $webMenus = collect($myWebMenus);
            $menus = collect($params['menus']);


            $createPropertyWebMenuMappingData = [];
            foreach ($menus as $menu){

                $checkMenu = $webMenus->where('menu_type', '=', $menu['menu_type'])->where('id', '=', $menu['id'])->first();
                if (!$checkMenu) {
                    throw new ApiErrorException('api-unknown-error');
                }

                $createPropertyWebMenuMappingData[] = [
                    'property_id' => fillOnUndefined($params, 'property_id'),
                    'property_web_id' => fillOnUndefined($params, 'property_web_id'),
                    'property_web_menu_id' => $menu['id'],
                    'order_number' => $menu['order_number'],
                    'type' => $menu['menu_type'],
                    'menu_code' => fillOnUndefined($menu, 'menu_code', null),
                    'status' => $status,
                    'created_by' => fillOnUndefined($params, 'user_id'),
                    'updated_by' => fillOnUndefined($params, 'user_id'),
                    'created_at' => time(),
                    'updated_at' => time(),
                ] ;


            }

            $propertyWebMenuMappingResult = $this->createPropertyWebMenuMapping($createPropertyWebMenuMappingData);
            if ($propertyWebMenuMappingResult['status'] != 'success'){
                throw new ApiErrorException($propertyWebMenuMappingResult['message']);
            }

            $response = ['statusCode' => 200, 'status' => true, 'message' => '', 'data' => ['property_web_menu_mapping' => $return ] ];

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

}
