<?php

namespace App\Http\Controllers\ChannelManager\Athena\v1;

use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;

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

class AthenaController extends Controller
{


    private $username;
    private $password;

    private $request;
    private $propertyChannelService;
    private $propertyChannelMappingService;
    private $propertyRoomRatePriceService;
    private $param;
    private $channelId;
    private $channelManagerLogId;


    public function __construct(
        Request $request,
        PropertyChannelService $propertyChannelService,
        PropertyChannelMappingService $propertyChannelMappingService,
        PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
        PropertyRoomRatePriceService $propertyRoomRatePriceService,
        PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
        PropertyRoomService $propertyRoomService,
        BookingService $bookingService,
        ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
        ChannelManagerLogService $channelManagerLogService
    )
    {

        //Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
        //Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.

        $this->username = 'athena';
        $this->password = 'AU3EUmA9LChTzAzv';

        $this->request = $request;
        $this->propertyChannelService = $propertyChannelService;
        $this->propertyChannelMappingService = $propertyChannelMappingService;
        $this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
        $this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
        $this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
        $this->propertyRoomService = $propertyRoomService;
        $this->bookingService = $bookingService;
        $this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
        $this->channelManagerLogService = $channelManagerLogService;

        $payload = $this->request->getContent();
        $payloadJson = json_decode($payload, 1);
        $this->param = $payloadJson;

        $this->channelId = 1;
        $this->channelManagerId = 5; //Athena

        $getRequestUri = $request->getRequestUri();
        $getRequestUriExplode = explode('/', $getRequestUri);
        $serviceRequestName = last($getRequestUriExplode);

        //channelManagerLogService
        $logArray = ['update-room-availability', 'update-room-rate'];
        $this->channelManagerLogId = null;
        if (in_array($serviceRequestName, $logArray)) {
            $insertDataLog = [
                'property_id' => $this->param['hotel_id'],
                'channel_manager_id' => $this->channelManagerId,
                'type' => 'C2E',
                'service' => $serviceRequestName,
                'request' => json_encode($payloadJson),
                'response' => null,
                'status' => null
            ];


            $channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
            if ($channelManagerLog['status'] == 'success') {
                $this->channelManagerLogId = $channelManagerLog['data']['id'];
            }
        }
        //channelManagerLogService


    }

    public function checkAuthentication($username, $password)
    {

        $response = ['status' => false, 'message' => ''];

        if ($this->username != $username || $this->password != $password) {
            $response['message'] = 'Your username or password is incorrect.';
        } else {
            $response['status'] = true;
        }

        return $response;

    }


    public function responseError($errorMessage)
    {

        $response = [
            'status' => false,
            'message' => $errorMessage,
        ];

        //channelManagerLogService
        if (!is_null($this->channelManagerLogId)) {
            $updateDataLog = [
                'response' => json_encode($response),
                'status' => 0
            ];
            $channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
        }
        //channelManagerLogService

        return response()->json($response);

    }

    public function responseSuccess($responseData = null)
    {

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

        //channelManagerLogService
        if (!is_null($this->channelManagerLogId)) {
            $updateDataLog = [
                'response' => json_encode($response),
                'status' => 1
            ];
            $channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
        }
        //channelManagerLogService

        return response()->json($response);

    }

    public function propertyChannelMapping($propertyId)
    {

        $response = ['status' => false, 'message' => ''];

        try {

            $propertyChannelMappingCriteria = [
                'criteria' => [
                    ['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
                'firstRow' => true
            ];


            $propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);

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

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


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

    }

    public function channelPropertyRoomRate($propertyId)
    {

        $response = ['status' => false, 'message' => ''];

        try {

            $requestParam = [
                'criteria' => [
                    //['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
                'with' => [
                    'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
                    'propertyRoomRateMapping.propertyRoom.propertyRoomType',
                ]
            ];

            $getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);

            if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
                throw new ApiErrorException('Property Room Rate not found');
            }

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


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

    }

    public function channelManagerPropertyCheck($propertyId)
    {

        $response = ['status' => false, 'message' => ''];

        try {

            $requestParam =
                [
                    'criteria' =>
                        [
                            ['field' => 'status', 'condition' => '=', 'value' => 1],
                            ['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
                            ['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
                        ],
                    'firstRow' => true
                ];

            $channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);


            if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
                throw new ApiErrorException('Property Room Rate not found');
            }

            $channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];

            if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
                throw new ApiErrorException('This hotel can only be updated by ENW');
            }

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


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

    }


    public function roomRate(Request $request)
    {

        $response = ['status' => false, 'message' => ''];

        //checkAuthentication
        $checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
        if (!$checkAuthentication['status']) {
            return $this->responseError($checkAuthentication['message']);
        }

        try {

            $propertyId = $this->param['hotel_id'];

            $channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
            if (!$channelManagerPropertyCheck['status']) {
                throw new ApiErrorException($channelManagerPropertyCheck['message']);
            }


            $channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
            if (!$channelPropertyRoomRate['status']) {
                throw new ApiErrorException($channelPropertyRoomRate['message']);
            }

            $channelPropertyRoomRate = $channelPropertyRoomRate['data'];


            $propertyChannelMapping = $this->propertyChannelMapping($propertyId);
            if (!$propertyChannelMapping['status']) {
                throw new ApiErrorException($propertyChannelMapping['message']);
            }

            $propertyChannelMapping = $propertyChannelMapping['data'];


            $response = [];

            $roomRates = [];
            foreach ($channelPropertyRoomRate as $roomRate) {

                if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
                    continue;
                }

                if($roomRate['status'] == 0) {
                    continue;
                }

                if(empty($roomRate['property_room_rate_mapping'])) {
                    continue;
                }


                $roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
                    'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
                    'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
                    'status' => 'Active',
                    'capacity' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
                    'capacity_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
                ];

                $roomRates[$roomRate['property_room_rate_mapping']['room_id']]
                ['rate'][$roomRate['property_room_rate_mapping']['id']] = [
                    'id' => $roomRate['property_room_rate_mapping']['id'],
                    'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
                    'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
                    'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
                ];

            }

            $roomKey = 0;
            $response['rooms'] = [];
            foreach ($roomRates as $roomId => $roomRate) {

                $response['rooms'][$roomKey] = [
                    'id' => $roomId,
                    'room_name' => $roomRate['room']['name'],
                ];

                $roomRateKey = 0;
                $response['rooms'][$roomKey]['rates'] = [];
                foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {

                    $response['rooms'][$roomKey]['rates'][$roomRateKey] = [
                        'id' => $roomRateMappingId,
                        'rate_name' => $rateData['name'] . ' - ' . $rateData['rate'],
                        'board_id' => $rateData['accommodationId'],
                        'board_name' => $rateData['name'],
                    ];

                    $roomRateKey++;

                }

                $roomKey++;
            }

            return $this->responseSuccess($response);


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

        if (!$response['status']) {
            return $this->responseError($response['message']);
        }

    }

    public function channel(Request $request)
    {

        $response = ['status' => false, 'message' => ''];

        //checkAuthentication
        $checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
        if (!$checkAuthentication['status']) {
            return $this->responseError($checkAuthentication['message']);
        }

        try {

            $propertyId = $this->param['hotel_id'];

            $channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
            if (!$channelManagerPropertyCheck['status']) {
                throw new ApiErrorException($channelManagerPropertyCheck['message']);
            }

            $propertyChannelCriteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
                'with' => ['parentChannel','propertyChannelCategory'],
                'orderBy' => [
                    ['field' => 'id', 'value' => 'ASC']
                ],
            ];

            $propertyChannel = $this->propertyChannelService->select($propertyChannelCriteria);
            if (!$propertyChannel['status']) {
                throw new ApiErrorException($propertyChannel['message']);
            }

            $propertyChannel = $propertyChannel['data'];

            $response = [];

            $response['channels'] = [];
            foreach ($propertyChannel as $channel) {

                $response['channels'][] = [
                    'id' => $channel['id'],
                    'name' => $channel['name'],
                    'category_id' => $channel['property_channel_category']['id'],
                    'category_name' => $channel['property_channel_category']['name'],
                ];
            }

            return $this->responseSuccess($response);


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

        if (!$response['status']) {
            return $this->responseError($response['message']);
        }

    }


}
