<?php
namespace App\Models;
use League\Period\Period;

class ListingModel extends BaseModel{
    public string $table_name = "vb_units";
    public string $images_table_name = "vb_unit_images";
    public string $reservations_table = "escapiareservations";
    public string $ru_seasons = "ru_seasons";
    public string $ru_charges = "ru_charges";
    public string $ru_taxes = "ru_taxes";
    public string $vb_vrbo_amenities = "vb_vrbo_amenities";
    public string $vb_unit_vrbo_amenities = "vb_unit_vrbo_amenities";
    


    public function getMarkup(){
        $q = "SELECT * FROM vrbo_markup where id = 1";
        return $this->select($q,$conditionsValues)[0];
    }
    public function getList($conditions=[],$page=1,$limit = 50){
//        $this->getCount($this->table_name);
        $q = "SELECT * FROM $this->table_name where send_to_vrbo = 1"; //LIMIT ".$this->getOffset($page,$limit).",".$limit
        // check for AND and OR keyword > probably in future
        $conditionsValues = [];
        $qConditions = [];
        foreach ($conditions as $field=>$value){
            $qConditions[] = "$field = ?";
            $conditionsValues[] = $value;
        }
        if(count($qConditions) > 0) {
            $q .= ' WHERE ' . implode(' AND ', $qConditions);
        }
        return $this->select($q,$conditionsValues);
    }
    
    public function getConfig(){
        $q = "SELECT * FROM vrbo_default_settings where id = 1"; //LIMIT ".$this->getOffset($page,$limit).",".$limit
        return $this->select($q);        
    }
    
    public function getListing($id){
        $q = "SELECT *,CAST(CONVERT(long_description USING utf8) AS binary) as long_description_utf  FROM $this->table_name where id = ?"; //JOIN vb_unit_images as images ON
        $unit = $this->select($q,[$id]);
        if(empty($unit)){
            return [];
        }
        if(is_numeric($unit[0]['city'])){
            $q = "SELECT * FROM ru_location_city WHERE location_id = '".$unit[0]['city']."'";
            $city = $this->select($q);
            if(count($city) > 0){
                $unit[0]['city'] = $city[0]['name'];
            }
        }
        $unit[0]['images'] = $this->getUnitImages($id);
        return $unit;
    }
    public function getAmenities($unit_id){
        $q = "SELECT code FROM $this->vb_vrbo_amenities WHERE ID IN (SELECT vb_vrbo_amenitiy_id FROM $this->vb_unit_vrbo_amenities WHERE unit_id = $unit_id AND is_checked = 1)";
        return $this->select($q);
    }

    public function getUnitImages($unit_id){
        $q = "SELECT * FROM $this->images_table_name where unit_id = ? ORDER BY ordering ASC"; //and o_width >= 1024
        return $this->select($q,[$unit_id]);
    }

    public function getAvailibilityByUnitId($unitId,$start_date,$end_date){
        $start_date = date('Y-m-d',strtotime($start_date));
        $end_date = date('Y-m-d',strtotime($end_date));
        $q = "SELECT * FROM $this->reservations_table where arrival_checkout_date >= '$start_date' and arrival_checkin_date <= '$end_date' and unit_id = '$unitId' and iscancelled = false";
        $reservations = $this->select($q);
//        $bookedDates = array_map(function($reservation){
//            $period = new Period($reservation->arrival_checkin_date,$reservation->arrival_checkout_date,Period::INCLUDE_ALL);
//              // could have used array reduce then flatten that array
//        },$reservations);
        $availibilityDates = [];
        $checkinDates = [];
        $checkoutDates = [];
        $bookedDates = [];
        foreach ($reservations as $reservation){
            $reservationPeriod = new Period($reservation['arrival_checkin_date'],date('Y-m-d',strtotime('+1 day',strtotime($reservation['arrival_checkout_date']))),Period::INCLUDE_ALL);
            $checkinDates[] = $reservation['arrival_checkin_date'];
            $checkoutDates[] = $reservation['arrival_checkout_date'];
            foreach ($reservationPeriod->getDatePeriod("1 DAY") as $date){
                $dateFormattedforres = $date->format('Y-m-d');
                if($dateFormattedforres == $reservation['arrival_checkin_date'] || $dateFormattedforres == $reservation['arrival_checkout_date']){ continue; }
                $bookedDates[] = $dateFormattedforres;
            }
        }

        $yearPeriod = new Period(date('Y-m-d',strtotime($start_date)),date('Y-m-d',strtotime('+1 day',strtotime($end_date))),Period::INCLUDE_ALL);
        // echo "<pre>";
        // print_r($bookedDates);
        // print_r($checkinDates);
        // print_r($checkoutDates);
        // die;
        
        $seasons_up = $this->getSeasonsByUnitId($unitId);
        $seasons = [];
        $allSeasons = [];
        foreach($seasons_up as $season){
            $seasons[$season['date_from']] = $season['min_stay'];    
            $allSeasons[$season['date_from']] = $season;
        }
        
        foreach ($yearPeriod->getDatePeriod("1 DAY") as $date){
            $dateFormatted = $date->format('Y-m-d');
            $dateFormattedDay = $date->format('w');
            $isAvailable = "Y";
            if(in_array($dateFormatted,$bookedDates)){
                $isAvailable = "N";
            }
            $dateAllowedFor = "C";
            if((isset($allSeasons[$dateFormatted]))){
                //  <ChangeoverType ID="1">CheckIn</ChangeoverType>
                // <ChangeoverType ID="2">CheckOut</ChangeoverType>
                // <ChangeoverType ID="3">None</ChangeoverType>
                // <ChangeoverType ID="4">Both</ChangeoverType>
           
                $changeOver = ($this->getChangeoverDays($allSeasons[$dateFormatted]['id'],$dateFormatted));
                
                $changeOverType = $changeOver[0]['type'];
                switch(true){
                    case $changeOverType == 1:
                        $dateAllowedFor = "I";
                    break;
                    case $changeOverType == 2:
                        $dateAllowedFor = "O";
                    break;
                    case $changeOverType == 3:
                        $dateAllowedFor = "X";
                    break;
                    case $changeOverType == 4:
                        $dateAllowedFor = "C";
                    break;
                }
            }
            // if((isset($seasons[$dateFormatted])) && $seasons[$dateFormatted] == 7){
            //     echo "<pre>";print_r($season);die;
            //     if($dateFormattedDay == 6){
            //         $dateAllowedFor = "C";
            //     }
            //     else{
            //         $dateAllowedFor = "X";
            //     }
            // }
            
            if(in_array($dateFormatted,$bookedDates)){
                $dateAllowedFor = 'X';
            }
            if (in_array($dateFormatted,$checkinDates)){
                $dateAllowedFor = "O";
                $isAvailable = "N";
            }
            if (in_array($dateFormatted,$checkoutDates)){
                $dateAllowedFor = "I";
                // $isAvailable = "N";
            }
            if (in_array($dateFormatted,$checkinDates) && in_array($dateFormatted,$checkoutDates)){
                $dateAllowedFor = "X";
                $isAvailable = "N";
            }
            
            
            
            $availibilityDates[] = [
                'isAvailable'=>$isAvailable,
                'dateAllowedFor'=> $dateAllowedFor,
                'availableUnitCount' => ($isAvailable) ? 1:0,
                'minStay'=>(isset($seasons[$dateFormatted])) ? $seasons[$dateFormatted] : 3,
                'maxStay'=>28,
                // 'date'=>$dateFormatted
//                'stayIncrement'=>'D'
            ];
        }

        // echo "<pre>";
        // print_r($availibilityDates);
        // die;
        return $availibilityDates;
    }

    public function getSeasonsByUnitId($id){
        $date = date('Y-m-d',strtotime('-1 month'));
        $q = "SELECT * FROM $this->ru_seasons where unit_id = '$id' and date_from >= '$date' ORDER BY date_from ASC";
        return $this->select($q);
    }
    public function getChangeoverDays($ru_season_id,$date){
        $q = "SELECT * FROM ru_seasons_change_over_days where ru_season_id = '$ru_season_id' and date = '$date'";
        return $this->select($q);
    }
    public function getChargeTemplate($ct_id){
        $q = "SELECT * FROM chargetemplates where id = '$ct_id'";
        return $this->select($q);
    }

    public function getChargesByUnit($id){
        $q = "SELECT * FROM $this->ru_charges where unit_id = '$id'";
        return $this->select($q);
    }

    public function getTaxesByUnit($id){
        $q = "SELECT * FROM $this->ru_taxes where unit_id = '$id'";
        return $this->select($q);
    }

    public function getVBUnitIdByListId($listingPropertyId){
        return $listingPropertyId;
        $q = "SELECT * FROM $this->table_name where listingPropertyId = ?";
        return $this->select($q,[$listingPropertyId]);
    }
    public function getVBUnitIdByUnitId($unitPropertyId){
        return $unitPropertyId;
        $q = "SELECT * FROM $this->table_name where unitPropertyId = ?";
        return $this->select($q,[$unitPropertyId]);
    }
    public function getVBUnitIdByListIdAndUnitId($listingPropertyId,$unitPropertyId){
        return $listingPropertyId;
        $q = "SELECT * FROM $this->table_name where listingPropertyId = ? AND unitPropertyId = ?";
        return $this->select($q,[$listingPropertyId,$unitPropertyId]);
    }


}