<?php

namespace App\Console\Commands\ChannelManager;

use App\Core\Mail\LogMail;
use App\Exceptions\ApiErrorException;
use App\Models\PropertyMeta;
use App\Models\PropertyMetaRoomRate;
use App\Models\PropertyRoomRateChannelMapping;
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\DB;
use Illuminate\Support\Facades\Log;

class PropertyMetaRoomRateService extends Command
{
    protected $signature = 'cron:propertymeta-roomrate-service {--property_id=}';

    protected $description = '';
    protected $mailer;

    public function __construct(
        Mailer $mailer
    )
    {
        parent::__construct();
        $this->mailer = $mailer;
    }

    public function handle()
    {

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


        if (!is_null($this->option('property_id'))) {
            $propertyMeta = PropertyMeta::where('status', 1)->where('property_id', $this->option('property_id'))->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'status'])->toArray();
        } else {
            $propertyMeta = PropertyMeta::where('status', 1)->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'status'])->toArray();
        }

        foreach ($propertyMeta as $property) {

            $this->info(date('Y-m-d H:i:s') . ' : Property Policy Start: ' . $property['property']['name']);


            //Property All Room Rate Price Policy
            $propertyRoomRateChannelMapping = PropertyRoomRateChannelMapping::with('propertyRoomRateMapping')
                ->with('propertyRoomRateMapping.propertyRoom')
                ->with('propertyRoomRateMapping.propertyRoomRate')
                ->with('propertyRoomRateChannelCancellationPolicy.propertyCancellationPolicy')
                ->with('propertyRoomRateChannelPricingAdultPolicy.propertyPricingPolicyAdult')
                ->with('propertyRoomRateChannelPricingChildPolicy.propertyPricingPolicyChild')
                ->with('propertyRoomRateChannelPromotion.propertyPromotion.promotionType')
                ->get()
                ->where('property_id', $property['property_id'])->where('channel_id', 1)
                ->where('status', 1);

            $propertyRoomRateChannelMapping = $propertyRoomRateChannelMapping->where('propertyRoomRateMapping', '!=', null)->toArray();

            //dd($propertyRoomRateChannelMapping);

            $roomRateMappingPolicy = [];
            foreach ($propertyRoomRateChannelMapping as $propertyRoom) {


                $roomRateMappingPolicy['promotion'][$propertyRoom['room_rate_mapping_id']] = [];
                foreach ($propertyRoom['property_room_rate_channel_promotion'] as $propertyRoomRateChannelPromotion) {

                    if($propertyRoomRateChannelPromotion['status'] != 1) {
                        continue;
                    }

                    $roomRateMappingPolicy['promotion'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateChannelPromotion['property_promotion_id']] = [
                        'type' => $propertyRoomRateChannelPromotion['property_promotion']['promotion_type']['type_code'],
                        'start_date' => $propertyRoomRateChannelPromotion['property_promotion']['start_date'],
                        'end_date' => $propertyRoomRateChannelPromotion['property_promotion']['end_date'],
                        'reservation_start_date' => $propertyRoomRateChannelPromotion['property_promotion']['reservation_start_date'],
                        'reservation_end_date' => $propertyRoomRateChannelPromotion['property_promotion']['reservation_end_date'],
                        'day_before' => $propertyRoomRateChannelPromotion['property_promotion']['day_before'],
                        'amount' => $propertyRoomRateChannelPromotion['property_promotion']['amount'],
                        'min_stay' => $propertyRoomRateChannelPromotion['property_promotion']['min_stay'],
                        'is_mobile' => $propertyRoomRateChannelPromotion['property_promotion']['is_mobile'],
                        'days' => $propertyRoomRateChannelPromotion['property_promotion']['days'],
                    ];

                }

                $roomRateMappingPolicy['cancellation_policy'][$propertyRoom['room_rate_mapping_id']] = [];
                foreach ($propertyRoom['property_room_rate_channel_cancellation_policy'] as $propertyRoomRateCancellationPolicy) {

                    $roomRateMappingPolicy['cancellation_policy'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateCancellationPolicy['cancellation_policy_id']] = [
                        'is_affected_price' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['is_affected_price'],
                        'affect_price_action_type' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['affect_price_action_type'],
                        'affect_price_type' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['affect_price_type'],
                        'affect_price_value' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['affect_price_value'],
                        'is_date_range' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['is_date_range'],
                        'start_date' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['start_date'],
                        'finish_date' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['finish_date'],
                    ];

                }

                $roomRateMappingPolicy['adult_policy'][$propertyRoom['room_rate_mapping_id']] = [];
                foreach ($propertyRoom['property_room_rate_channel_pricing_adult_policy'] as $propertyRoomRateAdultPolicy) {

                    $roomRateMappingPolicy['adult_policy'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateAdultPolicy['pricing_policy_adult_id']] = [
                        'adult_action_type' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['adult_action_type'],
                        'adult' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['adult'],
                        'action_type' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['action_type'],
                        'type' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['type'],
                        'value' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['value'],
                    ];

                }

                $roomRateMappingPolicy['child_policy'][$propertyRoom['room_rate_mapping_id']] = [];
                foreach ($propertyRoom['property_room_rate_channel_pricing_child_policy'] as $propertyRoomRateChildPolicy) {

                    $roomRateMappingPolicy['child_policy'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateChildPolicy['pricing_policy_child_id']] = [
                        'adult' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['adult'],
                        'child_order' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['child_order'],
                        'child_age_start' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['child_age_start'],
                        'child_age_end' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['child_age_end'],
                        'type' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['type'],
                        'value' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['value'],
                    ];

                }

            }
            //Property All Room Rate Price Policy

            $propertyMetaPolicyUpdate = [
                'cancellation_policy' => json_encode($roomRateMappingPolicy['cancellation_policy']),
                'adult_policy' => json_encode($roomRateMappingPolicy['adult_policy']),
                'child_policy' => json_encode($roomRateMappingPolicy['child_policy']),
                'promotion' => json_encode($roomRateMappingPolicy['promotion']),
            ];

            PropertyMeta::where('id', $property['id'])->update($propertyMetaPolicyUpdate);

            $this->info(date('Y-m-d H:i:s') . ' : Property Policy Finished: ' . $property['property']['name']);


            //$propertyMetaTemp
            /*$propertyMetaTemp = PropertyMeta::where('property_id', $property['property_id'])->with('property')->get()->first();
            $propertyMetaTemp = $propertyMetaTemp->toArray();
            $propertyMetaPolicyUpdate = [
                'cancellation_policy' => json_decode($propertyMetaTemp['cancellation_policy'], 1),
                'adult_policy' => json_decode($propertyMetaTemp['adult_policy'], 1),
                'child_policy' => json_decode($propertyMetaTemp['child_policy'], 1),
            ];*/
            //$propertyMetaTemp


            $this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Occupancy Start: ' . $property['property']['name']);


            //Property All Price Combination
            /*$propertyRoomRateChannelMapping = PropertyRoomRateChannelMapping::with('propertyRoomRateMapping')
                ->with('propertyRoomRateMapping.propertyRoom')
                ->with('propertyRoomRateMapping.propertyRoomRate')
                ->with('propertyRoomRateChannelCancellationPolicy.propertyCancellationPolicy')
                ->with('propertyRoomRateChannelPricingAdultPolicy')
                ->with('propertyRoomRateChannelPricingChildPolicy')
                ->get()
                ->where('property_id', $property['property_id'])->where('channel_id', 1)
                ->where('status', 1);

            $propertyRoomRateChannelMapping = $propertyRoomRateChannelMapping->where('propertyRoomRateMapping', '!=', null)->toArray();*/

            $roomRateOccupancy = [];
            foreach ($propertyRoomRateChannelMapping as $propertyRoom) {

                $roomId = $propertyRoom['property_room_rate_mapping']['room_id'];
                $propertyRoomRateMappingId = $propertyRoom['property_room_rate_mapping']['id'];
                $occupancyGroup = occupancyGroup(
                    $propertyRoom['property_room_rate_mapping']['property_room']['max_adult'],
                    $propertyRoom['property_room_rate_mapping']['property_room']['max_child'],
                    $propertyRoom['property_room_rate_mapping']['property_room']['max_occupancy']
                );

                //TODO: Burası incelenebilir, cancellation policy yok ise gelmiyor çünkü....
                /*if(empty($propertyRoom['property_room_rate_channel_cancellation_policy'])) {
                    $propertyRoom['property_room_rate_channel_cancellation_policy'][] = [
                        'cancellation_policy_id' => 0,
                        'property_cancellation_policy' => [
                            'name' => 'Refundable',
                            'is_nonrefundable' => 0,
                        ]
                    ];
                }*/

                foreach ($propertyRoom['property_room_rate_channel_cancellation_policy'] as $propertyRoomRateCancellationPolicy) {


                    foreach ($occupancyGroup as $occupancyCode) {

                        $roomRateOccupancyKey = $roomId . '-' . $propertyRoomRateMappingId . '-' . $propertyRoomRateCancellationPolicy['cancellation_policy_id'] . '-' . $occupancyCode;
                        $roomRateOccupancyKey = md5($roomRateOccupancyKey);

                        $cancellationPolicyName = [];
                        $cancellationPolicyName[] = $propertyRoomRateCancellationPolicy['property_cancellation_policy']['is_nonrefundable'] ? 'NonRefundable' : 'Refundable';
                        $cancellationPolicyName[] = !empty($propertyRoomRateCancellationPolicy['property_cancellation_policy']['name']) ? '(' . $propertyRoomRateCancellationPolicy['property_cancellation_policy']['name'] . ')' : null;
                        $cancellationPolicyName = implode(' ', $cancellationPolicyName);

                        $roomRateOccupancyTitle = [];
                        $roomRateOccupancyTitle[] = $propertyRoom['property_room_rate_mapping']['property_room']['name'];
                        $roomRateOccupancyTitle[] = $propertyRoom['property_room_rate_mapping']['property_room_rate']['name'];
                        $roomRateOccupancyTitle[] = $cancellationPolicyName;
                        $roomRateOccupancyTitle[] = $occupancyCode;

                        $roomRateOccupancyTitle = implode(' - ', $roomRateOccupancyTitle);

                        $roomRateOccupancy[$roomRateOccupancyKey] = [
                            'propertyId' => $property['property_id'],
                            'roomId' => $roomId,
                            'roomName' => $propertyRoom['property_room_rate_mapping']['property_room']['name'],
                            'roomRateMappingId' => $propertyRoomRateMappingId,
                            'roomRateMappingName' => $propertyRoom['property_room_rate_mapping']['property_room_rate']['name'],
                            'cancellationPolicyId' => $propertyRoomRateCancellationPolicy['cancellation_policy_id'],
                            'cancellationPolicyName' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['name'],
                            'occupancyCode' => $occupancyCode,
                            'includedOccupancy' => $propertyRoom['property_room_rate_mapping']['included_occupancy'],
                            'title' => $roomRateOccupancyTitle
                        ];

                    }

                }

            }
            //Property All Price Combination


            $propertyMetaRoomRateParam = [];
            foreach ($roomRateOccupancy as $roomRateOccupancyKey => $roomRate) {

                //$propertyMetaRoomRateCheck = PropertyMetaRoomRate::where('code', $roomRateOccupancyKey)->count();

                $propertyMetaRoomRateParam[] = [
                    'code' => $roomRateOccupancyKey,
                    'title' => $roomRate['title'],
                    'property_id' => $roomRate['propertyId'],
                    'room_id' => $roomRate['roomId'],
                    'room_rate_mapping_id' => $roomRate['roomRateMappingId'],
                    'cancellation_policy_id' => $roomRate['cancellationPolicyId'],
                    'included_occupancy' => $roomRate['includedOccupancy'],
                    'occupancy_code' => $roomRate['occupancyCode'],
                    'status' => 1,
                    'created_by' => 1,
                    'updated_by' => 1,
                    'created_at' => Carbon::now()->unix(),
                    'updated_at' => Carbon::now()->unix(),
                ];

                /*if ($propertyMetaRoomRateCheck) {
                    $propertyMetaRoomRateUpdate = PropertyMetaRoomRate::where('code', $roomRateOccupancyKey)->update($propertyMetaRoomRateParam);
                } else {
                    $propertyMetaRoomRateCreate = PropertyMetaRoomRate::create($propertyMetaRoomRateParam);
                }*/

                //$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Occupancy: ' . $roomRate['title']);

            }

            //Delete all codes
            if (!empty($propertyMetaRoomRateParam)) {
                PropertyMetaRoomRate::where('property_id', $property['property_id'])->delete();
                PropertyMetaRoomRate::insert($propertyMetaRoomRateParam);
            }

            $this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Occupancy Finished: ' . $property['property']['name']);


        }


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


    }
}
