<?php

namespace App\Console\Commands\ChannelManager;

use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerBookingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;

class ReservationPushService extends Command
{
    protected $signature = 'cron:reservation-push-service';

    protected $description = '';
    protected $channelService;
    protected $channelManagerBookingService;

    public function __construct(
        Mailer                       $mailer,
        Reseliva                     $channelService,
        ChannelManagerBookingService $channelManagerBookingService
    )
    {
        parent::__construct();
        $this->mailer = $mailer;
        $this->channelService = $channelService;
        $this->channelManagerBookingService = $channelManagerBookingService;

    }

    public function handle()
    {


        $this->info(date('Y-m-d H:i:s') . ' : Start');

        $pendingBookingCriteria = [
            'criteria' =>
                [
                    //['field' => 'id', 'condition' => '=', 'value' => 22461],#21390
                    ['field' => 'is_pushed', 'condition' => '=', 'value' => null],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
            'with' => [
                'channelManager',
                'bookingDetail.bookingContact', 'bookingDetail.bookingChannel',
                'bookingDetail.bookingPayment', 'bookingDetail.bookingPaymentType',
                'bookingDetail.bookingStatus', 'bookingDetail.bookingRoom.roomPax.paxCountry'
            ],
            'orderBy' => [
                ['field' => 'id', 'value' => 'ASC']
            ],
            'take' => 100
        ];

        $pendingBooking = $this->channelManagerBookingService->select($pendingBookingCriteria);


        if ($pendingBooking['status'] == 'success') {

            $pendingBooking = $pendingBooking['data'];

            foreach ($pendingBooking as $booking) {

                try {

                    $this->info(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id']);

                    $channelService = App::make("App\Core\Service\ChannelManager\\{$booking['channel_manager']['name']}");

                    $this->info(date('Y-m-d H:i:s') . ' : Channel: ' . $booking['channel_manager']['name']);

                    if ($booking['channel_manager_id'] == 10) {
                        //After 3 minutes, the faulty operation is set to status 2 for Hyperguest.
                        if (Carbon::createFromTimestamp($booking['created_at'])->diffInMinutes(Carbon::now()) > 3) {
                            $this->channelManagerBookingService->update($booking['id'], ['status' => 2]);
                            $this->error(date('Y-m-d H:i:s') . ' : Channel: ' . $booking['channel_manager']['name']);
                            continue;
                        }
                    }

                    //After 30 minutes, the faulty operation is set to status 2.
                    if (Carbon::createFromTimestamp($booking['created_at'])->diffInMinutes(Carbon::now()) > 30) {
                        $this->channelManagerBookingService->update($booking['id'], ['status' => 2]);
                    }

                    $requestPostReservationPushParam = $channelService->requestPostReservationPushParam($booking['property_id'], $booking['booking_id'], $booking['type'], $booking);

                    if (empty($requestPostReservationPushParam)) {
                        throw new ApiErrorException('requestPostReservationPushParam Error');
                    }

                    $this->info(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id'] . ' Push');

                    $this->channelManagerBookingService->update($booking['id'], ['request' => $requestPostReservationPushParam]);

                    $requestPostReservationPush = $channelService->requestPostReservationPush($requestPostReservationPushParam);

                    if ($requestPostReservationPush['status']) {

                        $this->info(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id'] . ' Success');
                        $this->channelManagerBookingService->update($booking['id'], ['is_pushed' => 1, 'status' => 1, 'response' => $requestPostReservationPush['response']]);

                    } else {

                        //$logMessage
                        $mailParams = [
                            'title' => 'ReservationPushService Error - ChannelManagerName: ' . $booking['channel_manager']['name'],
                            'logMessage' => '<pre>' . print_r(array_merge($booking, $requestPostReservationPush), true) . '</pre>'
                        ];

                        $this->mailer->onQueue('logMail', new LogMail($mailParams));
                        //$logMessage

                        $this->error(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id'] . ' Failed');

                        $this->channelManagerBookingService->update($booking['id'], ['response' => $requestPostReservationPush['message']]);
                    }


                } catch (ApiErrorException $e) {
                    $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
                    Log::error($message);
                    $this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
                } catch (Exception $e) {
                    $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
                    Log::error($message);
                    $this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
                }

            }


        }


        $this->info(date('Y-m-d H:i:s') . ' : Finished');


    }

}
