<?php

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

use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Core\Mail\ChannelManagerNotificationMail;
use App\Core\Service\ChannelManager\Channex;

use App;
use Illuminate\Mail\Mailer;
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 ChannexController 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,
        ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
        Channex $channexService,
        Mailer $mailer
    )
    {

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

        $this->request = $request;
        $this->propertyChannelService = $propertyChannelService;
        $this->propertyChannelMappingService = $propertyChannelMappingService;
        $this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
        $this->mailer = $mailer;
        $this->channexService = $channexService;

        $payloadJson = $this->request->all();
        $this->param = $payloadJson;

        Log::debug($payloadJson);

        $this->channelManagerId = 2; //Channex

    }

    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 channelManagerProperty($propertyId)
    {

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

        try {

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

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


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


            $response = [
                'status' => true,
                'data' => $channelManagerPropertyMapping['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 notification(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['property_id'];

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


            $channelDetails = $this->channexService->getChannelDetails($this->param['payload']['channel_id']);
            if (!$channelDetails['status']) {
                throw new ApiErrorException($channelDetails['message']);
            }
            $channelDetails = $channelDetails['data'];


            $mailParams = [
                'propertyId' => $propertyChannelMapping['property']['id'],
                'propertyName' => $propertyChannelMapping['property']['name'],
                'channelName' => $channelDetails['attributes']['channel']
            ];

            $this->mailer->onQueue('channelManagerNotificationMail', new ChannelManagerNotificationMail($mailParams));

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

    }

}
