<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Dashboard\Form\{
    SightseeingGeneralInfoForm,
    SightseeingRateForm,
    SightseeingMetaTagForm,
    SightseeingTermConditionForm,
    SightseeingImageForm
};
use Zend\Json\Json;
use Zend\Session\Container;
use Zend\Debug\Debug;
use Dashboard\Model\User;
use Dashboard\Model\CommonModel;

class SightseeingController extends RestAPIClientController {

    /**
     * Index
     * @return ViewModel
     */
    public function __construct() {
        $this->userModel = new User();
        $this->commonModel = new CommonModel();
    }

    private $masterPackageType = 6;

    public function indexAction() {
        $sessionSightseeingContainer = new Container('addSightseeingData');
        unset($sessionSightseeingContainer->s_id);
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $data = [
            'company_id' => $this->config()->getConfig()->company->companyId,
        ];
        $packageListing = $this->commonModel->getActivityList($data);
        //echo '<pre>';print_r($packageListing);die();
        $viewModel = new ViewModel(['packageListing' => $packageListing]);
        return $viewModel;
    }

    public function GeneralInformationAction() {
        SightseeingGeneralInfoForm:: $languages = $this->userModel->getLanguageList();
        SightseeingGeneralInfoForm:: $sightseeing_category = $this->commonModel->getSightseeingCategory();
        SightseeingGeneralInfoForm:: $sightseeing_type = $this->commonModel->getSightseeingType();
        SightseeingGeneralInfoForm:: $seasons = $this->userModel->getMonth();
        SightseeingGeneralInfoForm:: $things_to_carry = $this->commonModel->getThingsToCarry();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $form = new SightseeingGeneralInfoForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'city_id' => trim($postData['city_search_id'], ';'),
                    'sightseeing_name' => $postData['sightseeing_name'],
                    'latitude' => $postData['latitude'],
                    'longitude' => $postData['longitude'],
                    'address' => $postData['address'],
                    'coverage_km' => $postData['coverage_kilometre'],
                    'coverage_hrs' => $postData['coverage_hours'],
                    'difficulty_level' => $postData['difficulty_level'],
                    'is_unique' => isset($postData['is_unique']) ? $postData['is_unique'] : 0,
                    'popularity' => $postData['popularity'],
                    'youtube_url' => $postData['youtube_url'],
                    'description' => $postData['about_sightseeing'],
                    'meeting_point' => $postData['meeting_point'],
                    'highlights' => $postData['highlights'],
                    'sightseeing_cover' => $postData['sightseeing_cover'],
                    "s_season" => isset($postData['season']) ? implode(",", $postData['season']) : '',
                    'language' => isset($postData['languages']) ? implode(",", $postData['languages']) : '',
                    'created_date' => date('Y-m-d'),
                    "s_category" => isset($postData['category']) ? implode(",", $postData['category']) : '',
                    "s_type" => isset($postData['Sightseeing_type']) ? implode(",", $postData['Sightseeing_type']) : '',
                    "s_things" => isset($postData['things_to_carry']) ? implode(",", $postData['things_to_carry']) : '',
                    "ip" => $_SERVER['REMOTE_ADDR'],
                    'user_id' => $userId,
                    "bkg_type_id" => $this->config()->getConfig()->masterBookingType->activityId,
                ];
                //echo'<pre>';print_r($finalData);die();
                $responseData = $this->insertSightseeing($finalData);
                //echo'<pre>';print_r($responseData);die();
                if ($responseData['response']['status'] == 'success') {
                    $msg = "Details Added Successfully!..";
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Details Could Not Added!..";
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
                $this->redirect()->toRoute('sightseeing', ['action' => 'rate']);
            }
//            else {
//                $msg = $form->getMessages();
//                echo'<pre>';
//                print_r($msg);
//                die();
//            }
        }
        $viewModel = new ViewModel(['form' => $form, 
            'tab' => 'general-information',
            'google_map_url' => $this->config()->getConfig()->google_map->url,  
            'google_map_key' => $this->config()->getConfig()->google_map->key
            ]);
        return $viewModel;
    }

    public function editGeneralInformationAction() {
        SightseeingGeneralInfoForm:: $languages = $this->userModel->getLanguageList();
        SightseeingGeneralInfoForm:: $sightseeing_category = $this->commonModel->getSightseeingCategory();
        SightseeingGeneralInfoForm:: $sightseeing_type = $this->commonModel->getSightseeingType();
        SightseeingGeneralInfoForm:: $seasons = $this->userModel->getMonth();
        SightseeingGeneralInfoForm:: $things_to_carry = $this->commonModel->getThingsToCarry();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $form = new SightseeingGeneralInfoForm();
        $id = $this->params()->fromQuery('id');
        if (!empty($id)) {
            $data = [
                'auto_id' => $id,
                'company_id' => $this->config()->getConfig()->company->companyId,
                'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
            ];
            $vehicleData = $this->commonModel->getSightseeingDetailsList($data);
            $vehicleData = $vehicleData[0];
            //var_dump($vehicleData); die;
            $form->setData($vehicleData);
            $form->get('id')->setValue($vehicleData['s_id']);
            $form->get('city_search')->setValue($vehicleData['city_name']);
            $form->get('city_search_id')->setValue($vehicleData['city_id']);
            $form->get('latitude')->setValue($vehicleData['sightseeing_latitude']);
            $form->get('longitude')->setValue($vehicleData['sightseeing_logitude']);
            $form->get('address')->setValue($vehicleData['sightseeing_address']);
            $form->get('coverage_kilometre')->setValue($vehicleData['coverage_km']);
            $form->get('coverage_hours')->setValue($vehicleData['coverage_hrs']);
            $form->get('address')->setValue($vehicleData['sightseeing_address']);
            $form->get('about_sightseeing')->setValue($vehicleData['description']);
            $form->get('id')->setValue($vehicleData['s_id']);
        }
        $sessionSightseeingContainer = new Container('addSightseeingData');
        unset($sessionSightseeingContainer->s_id);
        $sessionSightseeingContainer->s_id = $id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                if (isset($postData['id']) && !empty($postData['id'])) {
                    $autoId = $postData['id'];
                    $url = 'rate';
                } else {
                    $autoId = $postData['sightseeing_name'];
                    $url = 'rate';
                }
                $finalData = [
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'city_id' => trim($postData['city_search_id'], ';'),
                    'sightseeing_name' => $postData['sightseeing_name'],
                    'latitude' => $postData['latitude'],
                    'longitude' => $postData['longitude'],
                    'address' => $postData['address'],
                    'coverage_km' => $postData['coverage_kilometre'],
                    'coverage_hrs' => $postData['coverage_hours'],
                    'difficulty_level' => $postData['difficulty_level'],
                    'is_unique' => isset($postData['is_unique']) ? $postData['is_unique'] : 0,
                    'popularity' => $postData['popularity'],
                    'youtube_url' => $postData['youtube_url'],
                    'description' => $postData['about_sightseeing'],
                    'meeting_point' => $postData['meeting_point'],
                    'highlights' => $postData['highlights'],
                    'sightseeing_cover' => $postData['sightseeing_cover'],
                    "s_season" => isset($postData['season']) ? implode(",", $postData['season']) : '',
                    'language' => isset($postData['languages']) ? implode(",", $postData['languages']) : '',
                    'created_date' => date('Y-m-d'),
                    "s_category" => isset($postData['category']) ? implode(",", $postData['category']) : '',
                    "s_type" => isset($postData['Sightseeing_type']) ? implode(",", $postData['Sightseeing_type']) : '',
                    "s_things" => isset($postData['things_to_carry']) ? implode(",", $postData['things_to_carry']) : '',
                    "ip" => $_SERVER['REMOTE_ADDR'],
                    'user_id' => $userId,
                    "bkg_type_id" => $this->config()->getConfig()->masterBookingType->activityId,
                    's_id' => $postData['id'],
                    'auto_id' => $autoId
                ];
                //echo'<pre>';print_r($finalData);die();
                $responseData = $this->commonModel->updateSighseetingDetails($finalData);
                //echo'<pre>';print_r($responseData);die();
                if ($responseData['response']['status'] == 'success') {
                    $msg = "Details Updated Successfully!..";
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Details Could Not Updated!..";
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
                //return $this->redirect()->toUrl('edit-payment-feature-hotel?id='.$postData['id']);
                return $this->redirect()->toUrl($url);
            }
//            else {
//                $msg = $form->getMessages();
//                echo'<pre>';
//                print_r($msg);
//                die();
//            }
        }
        $sightData = [
            'mapping_id' => $id,
            'bkg_type_id' => $this->config()->getConfig()->masterBookingType->activityId,
        ];
        $sightLangData = $this->commonModel->getSightseeingLanguagesList($sightData);
        $sightCategoryData = $this->commonModel->getSightseeingCategoryList($sightData);
        $sightTypeData = $this->commonModel->getSightseeingTypeList($sightData);
        $sightSeasonData = $this->commonModel->getSightseeingSeasonList($sightData);
        $sightThingsData = $this->commonModel->getSightseeingThingsList($sightData);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'general-information',
            'sightLangData' => $sightLangData,
            'sightCategoryData' => $sightCategoryData,
            'sightTypeData' => $sightTypeData,
            'sightSeasonData' => $sightSeasonData,
            'sightThingsData' => $sightThingsData,
            'google_map_url' => $this->config()->getConfig()->google_map->url,  
            'google_map_key' => $this->config()->getConfig()->google_map->key
        ]);
        return $viewModel;
    }

    public function rateAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $finalval = [];
        $dataVendor['user_type_id'] = $this->config()->getConfig()->userTypeId->vendor;
        $data = ['company_id' => $this->config()->getConfig()->company->companyId];
        $userListing = $this->userModel->getUserList($dataVendor);

        $vendors = [];
        if (count($userListing['data']['responsedata']) > 0) {
            foreach ($userListing['data']['responsedata'] as $key => $value) {
                $vendors [$value['user_id']] = $value['name'];
            }
        }
        SightseeingRateForm:: $sightseeing_list = $this->commonModel->getSightSeeingList($this->config()->getConfig()->company->companyId);
        SightseeingRateForm:: $languages = $this->userModel->getLanguageList();
        SightseeingRateForm:: $vendors = $vendors;
        SightseeingRateForm:: $currency = $this->userModel->getCurrencyList();
        SightseeingRateForm::$weekDaysList = $this->userModel->getWeekDaysList();
//SightseeingRateForm::$mealPlanList = $this->commonModel->getMealPlanList($data);
        SightseeingRateForm::$mealPlanList = $meals = $this->commonModel->getMeals();

        $form = new SightseeingRateForm();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            //if ($form->isValid()) {
            //----- For Vehicle Type -----
            $vehicleType = '';
            $stayingdetails = "";
            $SeasonalDetails = "";
            $lastBookingDetails = "";
            $earlyBookingDetails = "";
            $dayWiseDetails = "";
            if ($postData['ss_type'] == 1) {
                $vehicleType = $postData['vehicle_type'];
            } else {
                $vehicleType = '';
            }

            //----- For Rate Type -----
            $commission_Type = '';
            if ($postData['commissionable_type'] == 2) {
                $commission_Type = $postData['commission_type'];
            } else {
                $commission_Type = '';
                $postData['commission_value'] = '';
            }

            $rate_Type = '';
            if ($postData['tax'] == 2) {
                $rate_Type = $postData['taxextratype'];
            } else {
                $rate_Type = '';
                $postData['tax_value'] = '';
            }

            $currency = array_values(array_filter($postData['currency']));
            $adult = array_values(array_filter($postData['adult']));
            $child = array_values(array_filter($postData['child']));
            $infant = array_values(array_filter($postData['infant']));
            $senior_citizen = array_values(array_filter($postData['senior_citizen']));
            $is_guide = '';
            if (isset($postData['is_guide'])) {
                $is_guide = array_values(array_filter($postData['is_guide']));
            }
            $guide_language = array_values(array_filter($postData['guide_language']));
            $guide_cost = array_values(array_filter($postData['guide_cost']));

            $currency_Data = [];
            for ($i = 0; $i < count($currency); $i++) {
                $currency_Data['currency'][$i] = $currency[$i];
                $currency_Data['adult'][$i] = $adult[$i];
                $currency_Data['child'][$i] = $child[$i];
                $currency_Data['infant'][$i] = $infant[$i];
                $currency_Data['senior_citizen'][$i] = $senior_citizen[$i];
                if (isset($is_guide[$i])) {
                    $currency_Data['is_guide_available'][$i] = $is_guide[$i];
                    $currency_Data['guide_lang'][$i] = $guide_language[$i];
                    $currency_Data['guide_cost'][$i] = $guide_cost[$i];
                }
            }


            //Stay More Get More Discount            
            if (isset($postData['stay_get_mor_dis']) && !empty($postData['stay_get_mor_dis'])) {
                $stayingdetails = [];
                $staying_days = array_values(array_filter($postData['staying_days']));
                $more_discount_from = array_values(array_filter($postData['more_discount_from']));
                $more_discount_to = array_values(array_filter($postData['more_discount_to']));
                $stay_more_discount_type = array_values(array_filter($postData['stay_more_discount_type']));
                $staying_amount = array_values(array_filter($postData['staying_amount']));
                for ($i = 0; $i < count($staying_days); $i++) {
                    $stayingdetails['stay_more_week_days'][$i] = $staying_days[$i];
                    $stayingdetails['stay_more_from_date'][$i] = date('Y-m-d', strtotime($more_discount_from[$i]));
                    $stayingdetails['stay_more_to_date'][$i] = date('Y-m-d', strtotime($more_discount_to[$i]));
                    $stayingdetails['stay_more_type'][$i] = $stay_more_discount_type[$i];
                    $stayingdetails['stay_more_value'][$i] = $staying_amount[$i];
                }
            }


            //Seasonal Discount
            if (isset($postData['seasonal_discount']) && !empty($postData['seasonal_discount'])) {
                $SeasonalDetails = [];
                $season_name = array_values(array_filter($postData['season_name']));
                $season_date_from = array_values(array_filter($postData['season_date_from']));
                $season_date_to = array_values(array_filter($postData['season_date_to']));
                $season_dis_type = array_values(array_filter($postData['season_dis_type']));
                $season_amount = array_values(array_filter($postData['season_amount']));

                for ($i = 0; $i < count($season_name); $i++) {
                    $SeasonalDetails['season_name'][$i] = $season_name[$i];
                    $SeasonalDetails['season_from_date'][$i] = date('Y-m-d', strtotime($season_date_from[$i]));
                    $SeasonalDetails['season_to_date'][$i] = date('Y-m-d', strtotime($season_date_to[$i]));
                    $SeasonalDetails['season_discount_type'][$i] = $season_dis_type[$i];
                    $SeasonalDetails['season_discount_value'][$i] = $season_amount[$i];
                }
            }


            //Last Minute Booking
            if (isset($postData['last_minute_booking']) && !empty($postData['last_minute_booking'])) {
                $lastBookingDetails = [];
                $last_minute_booking_hour = array_values(array_filter($postData['last_minute_booking_hour']));
                $last_booking_from = array_values(array_filter($postData['last_booking_from']));
                $last_booking_to = array_values(array_filter($postData['last_booking_to']));
                $last_minute_booking_type = array_values(array_filter($postData['last_minute_booking_type']));
                $last_minute_booking_amount = array_values(array_filter($postData['last_minute_booking_amount']));
                for ($i = 0; $i < count($last_minute_booking_hour); $i++) {
                    $lastBookingDetails['last_min_hour'][$i] = $last_minute_booking_hour[$i];
                    $lastBookingDetails['last_min_from_date'][$i] = date('Y-m-d', strtotime($last_booking_from[$i]));
                    $lastBookingDetails['last_min_to_date'][$i] = date('Y-m-d', strtotime($last_booking_to[$i]));
                    $lastBookingDetails['last_min_discount_type'][$i] = $last_minute_booking_type[$i];
                    $lastBookingDetails['last_min_discount_value'][$i] = $last_minute_booking_amount[$i];
                }
            }


            //Early Booking
            if (isset($postData['early_booking']) && !empty($postData['early_booking'])) {
                $earlyBookingDetails = [];
                $early_booking_days = array_values(array_filter($postData['early_booking_days']));
                $early_booking_from = array_values(array_filter($postData['early_booking_from']));
                $early_booking_to = array_values(array_filter($postData['early_booking_to']));
                $early_booking_type = array_values(array_filter($postData['early_booking_type']));
                $early_booking_amount = array_values(array_filter($postData['early_booking_amount']));
                for ($i = 0; $i < count($early_booking_days); $i++) {
                    $earlyBookingDetails['early_week_days'][$i] = $early_booking_days[$i];
                    $earlyBookingDetails['early_from_date'][$i] = date('Y-m-d', strtotime($early_booking_from[$i]));
                    $earlyBookingDetails['early_to_date'][$i] = date('Y-m-d', strtotime($early_booking_to[$i]));
                    $earlyBookingDetails['early_discount_type'][$i] = $early_booking_type[$i];
                    $earlyBookingDetails['early_discount_value'][$i] = $early_booking_amount[$i];
                }
            }


            //Day Wise Discount
            if (isset($postData['day_wise_discount']) && !empty($postData['day_wise_discount'])) {
                $dayWiseDetails = [];
                $dis_days = array_values(array_filter($postData['dis_days']));
                $day_wise_from = array_values(array_filter($postData['day_wise_from']));
                $day_wise_to = array_values(array_filter($postData['day_wise_to']));
                $day_wise_dis_type = array_values(array_filter($postData['day_wise_dis_type']));
                $day_wise_discount_amount = array_values(array_filter($postData['day_wise_discount_amount']));
                for ($i = 0; $i < count($dis_days); $i++) {
                    $dayWiseDetails['daywise_week_days'][$i] = $dis_days[$i];
                    $dayWiseDetails['daywise_from_date'][$i] = date('Y-m-d', strtotime($day_wise_from[$i]));
                    $dayWiseDetails['daywise_to_date'][$i] = date('Y-m-d', strtotime($day_wise_to[$i]));
                    $dayWiseDetails['daywise_discount_type'][$i] = $day_wise_dis_type[$i];
                    $dayWiseDetails['daywise_discount_value'][$i] = $day_wise_discount_amount[$i];
                }
            }

            if (isset($postData['sightseeing_name']) && !empty($postData['sightseeing_name'])) {
                $url = 'meta-tag?id=' . $postData['sightseeing_name'];
            } else {
                $url = 'meta-tag';
            }
            
             if (isset($postData['service_charge']) && !empty($postData['service_charge'])) {
                if($postData['service_charge']=="Yes"){
                    $serviceChargeType = $postData['service_charge_type'];
                    $serviceChargeValue = $postData['service_charge_value'];                    
                }else{
                    $serviceChargeType = "";
                    $serviceChargeValue = "";
                }
            }
            
            
            if (isset($postData['discounttypeofcommission']) && !empty($postData['discounttypeofcommission'])) {
                if($postData['discounttypeofcommission']=="Commissionable Rate"){
    $discountcommissiontype = $postData['discountcommissiontype'];
    $discountcomissionValue = $postData['discount_commission_value'];
    if($postData['discount_valid_from']!=""){
    $discountvalidFrom = date('Y-m-d', strtotime($postData['discount_valid_from']));
    }else{
    $discountvalidFrom = date('Y-m-d', strtotime($postData['valid_from']));    
    }
    
    if($postData['discount_valid_to']!=""){
      $discountvalidTo = date('Y-m-d', strtotime($postData['discount_valid_to']));
    }else{
      $discountvalidTo = date('Y-m-d', strtotime($postData['valid_to']));
    }
                }else{
                    $discountcommissiontype = "";
                    $discountcomissionValue = "";
                    $discountvalidFrom = "";
                    $discountvalidTo = "";
                }
            }

            $finalval = [
                "s_id" => $postData['sightseeing_name'],
                "vendor_id" => $postData['vendor_name'],
                "tour_type" => $postData['ss_type'],
                "passenger" => $vehicleType,
                "from_date" => date('Y-m-d', strtotime($postData['valid_from'])),
                "to_date" => date('Y-m-d', strtotime($postData['valid_to'])),
                "rate_type" => $postData['commissionable_type'],
                "rate_per_fixed" => $commission_Type,
                "rate_value" => $postData['commission_value'],
                "tax_type" => $postData['tax'],
                "tax_per_fixed" => $rate_Type,
                "tax_value" => $postData['tax_value'],
                
        'service_charge' => $postData['service_charge'],
        'service_charge_type' => $serviceChargeType,
        'service_charge_value' => $serviceChargeValue,
                
        'discount_netrate_commissionrate' => $postData['discounttypeofcommission'],
        'discount_commission_rate_type' => $discountcommissiontype,
        'discount_commission_rate_value' => $discountcomissionValue,
        'discount_valid_from' => $discountvalidFrom,
        'discount_valid_to' => $discountvalidTo,
                
                "opening_time" => $postData['operating_time_from'],
                "closing_time" => $postData['operating_time_to'],
                "estimated_time" => $postData['duration'],
                "age_from" => $postData['allowed_age_group_from'],
                "age_to" => $postData['allowed_age_group_to'],
                "transfer" => $postData['transfers'],
                "pickup_point" => $postData['pick_up_point'],
                "allocation" => $postData['allocation'],
                "cut_off_days" => $postData['cut_off_days'],
                "price_plan_name" => $postData['name_of_price_plan'],
                "stay_more_status" => !empty($stayingdetails) ? $postData['stay_get_mor_dis'] : 0,
                "seasonal_discount_status" => !empty($SeasonalDetails) ? $postData['seasonal_discount'] : 0,
                "last_min_booking_status" => !empty($lastBookingDetails) ? $postData['last_minute_booking'] : 0,
                "early_booking_status" => !empty($earlyBookingDetails) ? $postData['early_booking'] : 0,
                "daywise_discount_status" => !empty($dayWiseDetails) ? $postData['day_wise_discount'] : 0,
                "user_id" => $userId,
                "created_date" => date('Y-m-d'),
                "week_days" => implode(',', $postData['weekdays']),
                "meal" => implode(',', $postData['meal_plan_id']),
                "bkg_type_id" => $this->config()->getConfig()->masterBookingType->activityId,
                "currency_value" => $currency_Data,
                "stay_more_discount_value" => $stayingdetails,
                "seasonal_discount_value" => $SeasonalDetails,
                "last_min_booking_value" => $lastBookingDetails,
                "early_booking_value" => $earlyBookingDetails,
                "daywise_discount_value" => $dayWiseDetails,
                "ip" => $_SERVER['REMOTE_ADDR'],
            ];

            //echo "<pre>"; print_r($finalval); die;

            $responseData = $this->insertRatingDetails($finalval);

            if ($responseData['response']['status'] == 'success') {
                $msg = "Details Added Successfully!..";
                $this->flashMessenger()->addMessage(array('success' => $msg));
            } else {
                $msg = "Details Could Not Added!..";
                $color = "red";
                $this->flashMessenger()->addMessage(array('danger' => $msg));
            }
            return $this->redirect()->toUrl($url);
            //}
        }

        $week_days = $this->userModel->getWeekDaysList();
        $getVehType = $this->commonModel->getVehType();
        $meals = $this->commonModel->getMeals();
        $data = [
            'company_id' => $this->config()->getConfig()->company->companyId,
            'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
        ];
        //$packageListing = $this->commonModel->getSightseeingDetailsList($data);
        $packageListing = $this->commonModel->getActivityDetailsList($data);
        $viewModel = new ViewModel([
            'form' => $form,
            'week_days' => $week_days,
            'vehicleType' => $getVehType,
            'meals' => $meals,
            'tab' => 'rate',
            'packageListing' => $packageListing
        ]);
        return $viewModel;
    }

    public function editRateAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $finalval = [];
        $data['user_type_id'] = $this->config()->getConfig()->userTypeId->vendor;
        $data['company_id'] = $this->config()->getConfig()->userTypeId->companyId;
        $userListing = $this->userModel->getUserList($data);

        $vendors = [];
        if (count($userListing['data']['responsedata']) > 0) {
            foreach ($userListing['data']['responsedata'] as $key => $value) {
                $vendors [$value['user_id']] = $value['name'];
            }
        }
        SightseeingRateForm:: $sightseeing_list = $this->commonModel->getSightSeeingList($this->config()->getConfig()->company->companyId);
        SightseeingRateForm:: $languages = $this->userModel->getLanguageList();
        SightseeingRateForm:: $vendors = $vendors;
        SightseeingRateForm:: $currency = $this->userModel->getCurrencyList();
        SightseeingRateForm::$weekDaysList = $this->userModel->getWeekDaysList();
        //SightseeingRateForm::$mealPlanList = $this->commonModel->getMealPlanList($data);
        SightseeingRateForm::$mealPlanList = $this->commonModel->getMeals();


        $form = new SightseeingRateForm();

        $id = $this->params()->fromQuery('id');
        if (!empty($id)) {
            $sessionSightseeingContainer = new Container('addSightseeingData');
            $sessionSigntseeingId = $sessionSightseeingContainer->s_id;
            if ($sessionSigntseeingId == $id) {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
                ];
            } else {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId
                ];
            }
            //$vehicleData = $this->commonModel->getSightseeingDetailsList($data);              
            $vehicleData = $this->commonModel->getActivityDetailsList($data);
            $vehicleData = $vehicleData[0];
            //echo "<pre>";print_r($vehicleData); die;
            $form->setData($vehicleData);
            $form->getInputFilter()->get('sightseeing_name')->setRequired(false);
            $form->get('id')->setValue($vehicleData['s_detail_id']);
            $form->get('sightseeing_name')->setValue($vehicleData['s_id']);
            //$form->get('sightseeing_name')->setAttribute("disabled",[$vehicleData['s_id']]);    
            $form->get('vendor_name')->setValue($vehicleData['vendor_id']);
            $form->get('commission_value')->setValue($vehicleData['rate_value']);
            $form->get('tax_value')->setValue($vehicleData['tax_value']);
            $form->get('valid_from')->setValue(date('d-m-Y', strtotime($vehicleData['from_date'])));
            $form->get('valid_to')->setValue(date('d-m-Y', strtotime($vehicleData['to_date'])));
            $form->get('operating_time_from')->setValue($vehicleData['opening_time']);
            $form->get('operating_time_to')->setValue($vehicleData['closing_time']);
            $form->get('duration')->setValue($vehicleData['estimated_time']);
            $form->get('allowed_age_group_from')->setValue($vehicleData['age_from']);
            $form->get('allowed_age_group_to')->setValue($vehicleData['age_to']);
            $form->get('transfers')->setValue($vehicleData['transfer']);
            $form->get('pick_up_point')->setValue($vehicleData['pickup_point']);
            $form->get('name_of_price_plan')->setValue($vehicleData['price_plan_name']);
            
            if(!empty($vehicleData['discount_valid_from'])){
              $form->get('discount_valid_from')->setValue(date('d-m-Y', strtotime($vehicleData['discount_valid_from'])));
             }
             
             if(!empty($vehicleData['discount_valid_to'])){
             $form->get('discount_valid_to')->setValue(date('d-m-Y', strtotime($vehicleData['discount_valid_to'])));
             }
             
             $form->get('discount_commission_value')->setValue($vehicleData['discount_commission_rate_value']);
            $activityData = ['bkg_type_id' => $this->config()->getConfig()->masterBookingType->activityId, 'mapping_id' => $id];
            $activityStayMoreDiscountData = $this->commonModel->getStayMoreDiscountList($activityData);
            $activityLastMinuteDiscountData = $this->commonModel->getLastMinuteDiscountList($activityData);
            $activityEarlyDiscountData = $this->commonModel->getEarlyDiscountList($activityData);
            $activityDayWiseDiscountData = $this->commonModel->getDayWiseDiscountList($activityData);
            $activitySeasonDiscountData = $this->commonModel->getSeasonDiscountList($activityData);
            $activityMealsData = $this->commonModel->getMealList($activityData);
            $activityWeekDaysData = $this->commonModel->getWeekDaysList($activityData);
            $activityFareData = $this->commonModel->getActivityFareList($activityData);
        }

        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            //if ($form->isValid()) {
            //----- For Vehicle Type -----
            $vehicleType = '';
            $stayingdetails = "";
            $SeasonalDetails = "";
            $lastBookingDetails = "";
            $earlyBookingDetails = "";
            $dayWiseDetails = "";
            if ($postData['ss_type'] == 1) {
                $vehicleType = $postData['vehicle_type'];
            } else {
                $vehicleType = '';
            }

            //----- For Rate Type -----
            $commission_Type = '';
            if ($postData['commissionable_type'] == 2) {
                $commission_Type = $postData['commission_type'];
            } else {
                $commission_Type = '';
                $postData['commission_value'] = '';
            }

            $rate_Type = '';
            if ($postData['tax'] == 2) {
                $rate_Type = $postData['taxextratype'];
            } else {
                $rate_Type = '';
                $postData['tax_value'] = '';
            }

            $currency = array_values(array_filter($postData['currency']));
            $adult = array_values(array_filter($postData['adult']));
            $child = array_values(array_filter($postData['child']));
            $infant = array_values(array_filter($postData['infant']));
            $senior_citizen = array_values(array_filter($postData['senior_citizen']));
            $is_guide = '';
            if (isset($postData['is_guide'])) {
                $is_guide = array_values(array_filter($postData['is_guide']));
            }
            $guide_language = array_values(array_filter($postData['guide_language']));
            $guide_cost = array_values(array_filter($postData['guide_cost']));

            $currency_Data = [];
            for ($i = 0; $i < count($currency); $i++) {
                $currency_Data['currency'][$i] = $currency[$i];
                $currency_Data['adult'][$i] = $adult[$i];
                $currency_Data['child'][$i] = $child[$i];
                $currency_Data['infant'][$i] = $infant[$i];
                $currency_Data['senior_citizen'][$i] = $senior_citizen[$i];
                if (isset($is_guide[$i])) {
                    $currency_Data['is_guide_available'][$i] = $is_guide[$i];
                    $currency_Data['guide_lang'][$i] = $guide_language[$i];
                    $currency_Data['guide_cost'][$i] = $guide_cost[$i];
                }
            }


            //Stay More Get More Discount            
            if (isset($postData['stay_get_mor_dis']) && !empty($postData['stay_get_mor_dis'])) {
                $stayingdetails = [];
                $staying_days = array_values(array_filter($postData['staying_days']));
                $more_discount_from = array_values(array_filter($postData['more_discount_from']));
                $more_discount_to = array_values(array_filter($postData['more_discount_to']));
                $stay_more_discount_type = array_values(array_filter($postData['stay_more_discount_type']));
                $staying_amount = array_values(array_filter($postData['staying_amount']));
                for ($i = 0; $i < count($staying_days); $i++) {
                    $stayingdetails['stay_more_week_days'][$i] = $staying_days[$i];
                    $stayingdetails['stay_more_from_date'][$i] = date('Y-m-d', strtotime($more_discount_from[$i]));
                    $stayingdetails['stay_more_to_date'][$i] = date('Y-m-d', strtotime($more_discount_to[$i]));
                    $stayingdetails['stay_more_type'][$i] = $stay_more_discount_type[$i];
                    $stayingdetails['stay_more_value'][$i] = $staying_amount[$i];
                }
            }


            //Seasonal Discount
            if (isset($postData['seasonal_discount']) && !empty($postData['seasonal_discount'])) {
                $SeasonalDetails = [];
                $season_name = array_values(array_filter($postData['season_name']));
                $season_date_from = array_values(array_filter($postData['season_date_from']));
                $season_date_to = array_values(array_filter($postData['season_date_to']));
                $season_dis_type = array_values(array_filter($postData['season_dis_type']));
                $season_amount = array_values(array_filter($postData['season_amount']));

                for ($i = 0; $i < count($season_name); $i++) {
                    $SeasonalDetails['season_name'][$i] = $season_name[$i];
                    $SeasonalDetails['season_from_date'][$i] = date('Y-m-d', strtotime($season_date_from[$i]));
                    $SeasonalDetails['season_to_date'][$i] = date('Y-m-d', strtotime($season_date_to[$i]));
                    $SeasonalDetails['season_discount_type'][$i] = $season_dis_type[$i];
                    $SeasonalDetails['season_discount_value'][$i] = $season_amount[$i];
                }
            }


            //Last Minute Booking
            if (isset($postData['last_minute_booking']) && !empty($postData['last_minute_booking'])) {
                $lastBookingDetails = [];
                $last_minute_booking_hour = array_values(array_filter($postData['last_minute_booking_hour']));
                $last_booking_from = array_values(array_filter($postData['last_booking_from']));
                $last_booking_to = array_values(array_filter($postData['last_booking_to']));
                $last_minute_booking_type = array_values(array_filter($postData['last_minute_booking_type']));
                $last_minute_booking_amount = array_values(array_filter($postData['last_minute_booking_amount']));
                for ($i = 0; $i < count($last_minute_booking_hour); $i++) {
                    $lastBookingDetails['last_min_hour'][$i] = $last_minute_booking_hour[$i];
                    $lastBookingDetails['last_min_from_date'][$i] = date('Y-m-d', strtotime($last_booking_from[$i]));
                    $lastBookingDetails['last_min_to_date'][$i] = date('Y-m-d', strtotime($last_booking_to[$i]));
                    $lastBookingDetails['last_min_discount_type'][$i] = $last_minute_booking_type[$i];
                    $lastBookingDetails['last_min_discount_value'][$i] = $last_minute_booking_amount[$i];
                }
            }


            //Early Booking
            if (isset($postData['early_booking']) && !empty($postData['early_booking'])) {
                $earlyBookingDetails = [];
                $early_booking_days = array_values(array_filter($postData['early_booking_days']));
                $early_booking_from = array_values(array_filter($postData['early_booking_from']));
                $early_booking_to = array_values(array_filter($postData['early_booking_to']));
                $early_booking_type = array_values(array_filter($postData['early_booking_type']));
                $early_booking_amount = array_values(array_filter($postData['early_booking_amount']));
                for ($i = 0; $i < count($early_booking_days); $i++) {
                    $earlyBookingDetails['early_week_days'][$i] = $early_booking_days[$i];
                    $earlyBookingDetails['early_from_date'][$i] = date('Y-m-d', strtotime($early_booking_from[$i]));
                    $earlyBookingDetails['early_to_date'][$i] = date('Y-m-d', strtotime($early_booking_to[$i]));
                    $earlyBookingDetails['early_discount_type'][$i] = $early_booking_type[$i];
                    $earlyBookingDetails['early_discount_value'][$i] = $early_booking_amount[$i];
                }
            }


            //Day Wise Discount
            if (isset($postData['day_wise_discount']) && !empty($postData['day_wise_discount'])) {
                $dayWiseDetails = [];
                $dis_days = array_values(array_filter($postData['dis_days']));
                $day_wise_from = array_values(array_filter($postData['day_wise_from']));
                $day_wise_to = array_values(array_filter($postData['day_wise_to']));
                $day_wise_dis_type = array_values(array_filter($postData['day_wise_dis_type']));
                $day_wise_discount_amount = array_values(array_filter($postData['day_wise_discount_amount']));
                for ($i = 0; $i < count($dis_days); $i++) {
                    $dayWiseDetails['daywise_week_days'][$i] = $dis_days[$i];
                    $dayWiseDetails['daywise_from_date'][$i] = date('Y-m-d', strtotime($day_wise_from[$i]));
                    $dayWiseDetails['daywise_to_date'][$i] = date('Y-m-d', strtotime($day_wise_to[$i]));
                    $dayWiseDetails['daywise_discount_type'][$i] = $day_wise_dis_type[$i];
                    $dayWiseDetails['daywise_discount_value'][$i] = $day_wise_discount_amount[$i];
                }
            }

            if (isset($postData['id']) && !empty($postData['id'])) {
                $url = 'meta-tag?id=' . $postData['sightseeing_name'];
            } else {
                $url = 'meta-tag';
            }
            
            
            if (isset($postData['service_charge']) && !empty($postData['service_charge'])) {
                if($postData['service_charge']=="Yes"){
                    $serviceChargeType = $postData['service_charge_type'];
                    $serviceChargeValue = $postData['service_charge_value'];                    
                }else{
                    $serviceChargeType = "";
                    $serviceChargeValue = "";
                }
            }
            
            
            if (isset($postData['discounttypeofcommission']) && !empty($postData['discounttypeofcommission'])) {
                if($postData['discounttypeofcommission']=="Commissionable Rate"){
    $discountcommissiontype = $postData['discountcommissiontype'];
    $discountcomissionValue = $postData['discount_commission_value'];
    if($postData['discount_valid_from']!=""){
    $discountvalidFrom = date('Y-m-d', strtotime($postData['discount_valid_from']));
    }else{
    $discountvalidFrom = date('Y-m-d', strtotime($postData['valid_from']));    
    }
    
    if($postData['discount_valid_to']!=""){
      $discountvalidTo = date('Y-m-d', strtotime($postData['discount_valid_to']));
    }else{
      $discountvalidTo = date('Y-m-d', strtotime($postData['valid_to']));
    }
                }else{
                    $discountcommissiontype = "";
                    $discountcomissionValue = "";
                    $discountvalidFrom = "";
                    $discountvalidTo = "";
                }
            }


            $finalval = [
                "s_id" => $postData['sightseeing_name'],
                "vendor_id" => $postData['vendor_name'],
                "tour_type" => $postData['ss_type'],
                "passenger" => $vehicleType,
                "from_date" => date('Y-m-d', strtotime($postData['valid_from'])),
                "to_date" => date('Y-m-d', strtotime($postData['valid_to'])),
                "rate_type" => $postData['commissionable_type'],
                "rate_per_fixed" => $commission_Type,
                "rate_value" => $postData['commission_value'],
                "tax_type" => $postData['tax'],
                "tax_per_fixed" => $rate_Type,
                "tax_value" => $postData['tax_value'],
                
        'service_charge' => $postData['service_charge'],
        'service_charge_type' => $serviceChargeType,
        'service_charge_value' => $serviceChargeValue,

        'discount_netrate_commissionrate' => $postData['discounttypeofcommission'],
        'discount_commission_rate_type' => $discountcommissiontype,
        'discount_commission_rate_value' => $discountcomissionValue,
        'discount_valid_from' => $discountvalidFrom,
        'discount_valid_to' => $discountvalidTo,
        'valid_from' => date('Y-m-d', strtotime($postData['valid_from'])),
        'valid_to' => date('Y-m-d', strtotime($postData['valid_to'])),
                
                
                
                "opening_time" => $postData['operating_time_from'],
                "closing_time" => $postData['operating_time_to'],
                "estimated_time" => $postData['duration'],
                "age_from" => $postData['allowed_age_group_from'],
                "age_to" => $postData['allowed_age_group_to'],
                "transfer" => $postData['transfers'],
                "pickup_point" => $postData['pick_up_point'],
                "allocation" => $postData['allocation'],
                "cut_off_days" => $postData['cut_off_days'],
                "price_plan_name" => $postData['name_of_price_plan'],
                "stay_more_status" => !empty($stayingdetails) ? $postData['stay_get_mor_dis'] : 0,
                "seasonal_discount_status" => !empty($SeasonalDetails) ? $postData['seasonal_discount'] : 0,
                "last_min_booking_status" => !empty($lastBookingDetails) ? $postData['last_minute_booking'] : 0,
                "early_booking_status" => !empty($earlyBookingDetails) ? $postData['early_booking'] : 0,
                "daywise_discount_status" => !empty($dayWiseDetails) ? $postData['day_wise_discount'] : 0,
                "user_id" => $userId,
                "created_date" => date('Y-m-d'),
                "week_days" => implode(',', $postData['weekdays']),
                "meal" => implode(',', $postData['meal_plan_id']),
                "bkg_type_id" => $this->config()->getConfig()->masterBookingType->activityId,
                "currency_value" => $currency_Data,
                "stay_more_discount_value" => $stayingdetails,
                "seasonal_discount_value" => $SeasonalDetails,
                "last_min_booking_value" => $lastBookingDetails,
                "early_booking_value" => $earlyBookingDetails,
                "daywise_discount_value" => $dayWiseDetails,
                'auto_id' => $postData['id'],
                "ip" => $_SERVER['REMOTE_ADDR'],
            ];
            //echo "<pre>"; print_r($finalval); die;

            $responseData = $this->updateRatingDetails($finalval);

            if ($responseData['response']['status'] == 'success') {
                $msg = "Details Added Successfully!..";
                $this->flashMessenger()->addMessage(array('success' => $msg));
            } else {
                $msg = "Details Could Not Added!..";
                $color = "red";
                $this->flashMessenger()->addMessage(array('danger' => $msg));
            }
            return $this->redirect()->toUrl($url);
            //}
        }

        $week_days = $this->userModel->getWeekDaysList();
        $getVehType = $this->commonModel->getVehType();

        //echo "<pre>";print_r($meals); die;
        $data = [
            'company_id' => $this->config()->getConfig()->company->companyId,
            'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
        ];
        //$packageListing = $this->commonModel->getSightseeingDetails($data);
        $packageListing = $this->commonModel->getActivityDetailsList($data);
        $viewModel = new ViewModel([
            'form' => $form,
            'week_days' => $week_days,
            'vehicleType' => $getVehType,
            'tab' => 'rate',
            'activityStayMoreDiscountData' => $activityStayMoreDiscountData,
            'activityLastMinuteDiscountData' => $activityLastMinuteDiscountData,
            'activityEarlyDiscountData' => $activityEarlyDiscountData,
            'activityDayWiseDiscountData' => $activityDayWiseDiscountData,
            'activitySeasonDiscountData' => $activitySeasonDiscountData,
            'packageListing' => $packageListing,
            'vehicleData' => $vehicleData,
            'activityMealsData' => $activityMealsData,
            'activityWeekDaysData' => $activityWeekDaysData,
            'activityFareData' => $activityFareData
        ]);
        return $viewModel;
    }

    public function metatagAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        SightseeingMetaTagForm:: $sightseeing_list = $this->commonModel->getSightSeeingList($this->config()->getConfig()->company->companyId);
        $form = new SightseeingMetaTagForm();

        $id = $this->params()->fromQuery('id');

        if (!empty($id)) {
            $sessionSightseeingContainer = new Container('addSightseeingData');
            $sessionSigntseeingId = $sessionSightseeingContainer->s_id;
            if ($sessionSigntseeingId == $id) {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
                ];
            } else {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId
                ];
            }
            $vehicleData = $this->commonModel->getSightseeingDetailsList($data);
            $vehicleData = $vehicleData[0];
            //var_dump($vehicleData); die;
            $form->setData($vehicleData);
            $form->get('id')->setValue($vehicleData['s_id']);
            $form->get('sightseeing_name')->setValue($vehicleData['s_id']);
            $form->get('brochure_title')->setValue($vehicleData['brochure_title']);
            $form->get('brochure_description')->setValue($vehicleData['brochure_desc']);
            $form->get('meta_title')->setValue($vehicleData['meta_title']);
            $form->get('meta_keywords')->setValue($vehicleData['meta_keywords']);
            $form->get('meta_description')->setValue($vehicleData['meta_desc']);
            //$form->get('sightseeing_name')->setAttribute("disabled",[$vehicleData['s_id']]);
            $form->getInputFilter()->get('sightseeing_name')->setRequired(false);
            if (!empty($vehicleData['related_tours'])) {
                $tours = [];
                $toursArray = explode(',', $vehicleData['related_tours']);
                foreach ($toursArray as $realtedTours) {
                    $tours[] = $realtedTours;
                }
                $form->get('related_tours')->setValue($tours);
            }
        }
        $request = $this->getRequest();

        $form->get('activity_image')->setAttribute('data-id', '3');
        $form->get('spots_image')->setAttribute('data-id', '3');
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                if (isset($postData['id']) && !empty($postData['id'])) {
                    $autoId = $postData['id'];
                    $url = 'term-condition?id=' . $postData['id'];
                } else {
                    $autoId = $postData['sightseeing_name'];
                    $url = 'term-condition';
                }
                $finalData = [
                    'related_tours' => implode(",", $postData['related_tours']),
                    'brochure_title' => $postData['brochure_title'],
                    'brochure_desc' => $postData['brochure_description'],
                    'meta_keywords' => $postData['meta_keywords'],
                    'meta_title' => $postData['meta_title'],
                    'meta_desc' => $postData['meta_description'],
                    'user_id' => $userId,
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    's_id' => $autoId
                ];
                //var_dump($finalData); die;
                $responseData = $this->commonModel->updateSightseeingMetaDetails($finalData);
                if ($responseData['responsedata']['status'] == 'success') {
                    $msg = "Details Updated Successfully!..";
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Details Could Not Upated!..";
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
                return $this->redirect()->toUrl($url);
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'meta-tag']);
        return $viewModel;
    }

    public function termConditionAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        SightseeingTermConditionForm::$sightseeing_list = $this->commonModel->getSightSeeingList($this->config()->getConfig()->company->companyId);
        SightseeingTermConditionForm::$payment_structure = $this->commonModel->getPaymentStructureList();
        SightseeingTermConditionForm::$documentation = $this->commonModel->getDocumentationList();
        SightseeingTermConditionForm::$cancellation_policy = $this->commonModel->getCancellationPolicyList();
        SightseeingTermConditionForm::$refund_policy = $this->commonModel->getRefundPolicyList();
        SightseeingTermConditionForm::$term_policy = $this->commonModel->getTermConditionsPolicyList();
        $form = new SightseeingTermConditionForm();

        $id = $this->params()->fromQuery('id');

        if (!empty($id)) {
            $sessionSightseeingContainer = new Container('addSightseeingData');
            $sessionSigntseeingId = $sessionSightseeingContainer->s_id;
            if ($sessionSigntseeingId == $id) {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
                ];
            } else {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId
                ];
            }
            $vehicleData = $this->commonModel->getSightseeingDetailsList($data);
            $vehicleData = $vehicleData[0];
            //var_dump($vehicleData); die;
            $form->setData($vehicleData);
            $form->get('id')->setValue($vehicleData['s_id']);
            $form->get('sightseeing_name')->setValue($vehicleData['s_id']);
            $form->get('payment_structure_id')->setValue($vehicleData['payment_structure']);
            $form->get('document_id')->setValue($vehicleData['payment_documentation']);
            $form->get('cancellation_policy')->setValue($vehicleData['cancellation_policy']);
            $form->get('refund_policy')->setValue($vehicleData['refund_policy']);
            $form->get('term_policy')->setValue($vehicleData['terms_condition_policy']);
            //$form->get('sightseeing_name')->setAttribute("disabled",[$vehicleData['s_id']]);
            $form->getInputFilter()->get('sightseeing_name')->setRequired(false);
        }

        $request = $this->getRequest();

        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $postData = $request->getPost()->toArray();
                $finalData = [];
                if (isset($postData['id']) && !empty($postData['id'])) {
                    $autoId = $postData['id'];
                } else {
                    $autoId = $postData['sightseeing_name'];
                }
                $finalData = [
                    'payment_structure' => $postData['payment_structure_id'],
                    'payment_structure_content' => $postData['payment_structure_content'],
                    'payment_documentation' => $postData['document_id'],
                    'documentation_content' => $postData['documentation_content'],
                    'cancellation_policy' => $postData['cancellation_policy'],
                    'cancellation_policy_content' => $postData['cancellation_policy_content'],
                    'refund_policy' => $postData['refund_policy'],
                    'refund_policy_content' => $postData['refund_policy_content'],
                    'terms_condition_policy' => $postData['term_policy'],
                    'term_policy_content' => $postData['term_policy_content'],
                    'cost_inclusive' => $postData['cost_inclusive'],
                    'cost_exclusive' => $postData['cost_exclusive'],
                    'user_id' => $userId,
                    's_id' => $autoId,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                //var_dump($finalData); die;
                $responseData = $this->commonModel->updateSightseeingTermsPolicyDetails($finalData);
                if ($responseData['response']['status'] == 'success') {
                    $msg = "Details Added Successfully!..";
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Details Could Not Added!..";
                    $this->flashMessenger()->addMessage(array('danger' => $msg));
                }
                $this->redirect()->toRoute('sightseeing', ['action' => 'index']);
            } else {
                var_dump($form->getMessages());
                die;
            }
        }

        $viewModel = new ViewModel(['form' => $form, 'tab' => 'term-condition']);
        return $viewModel;
    }

    public function insertSightseeing($data) {
        $url = $this->apiUrl() . "/sightseeing/addSightseeingGeneralDetail";
        $val = $this->post($url, $data);
        $jsonData = $val->getBody();
        $jsonResponse = Json::decode($jsonData, true);

        return $jsonResponse;
    }

    public function insertRatingDetails($data) {
        $url = $this->apiUrl() . "/sightseeing/addSightseeingRateDetail";
        $val = $this->post($url, $data);
        $jsonData = $val->getBody();
        $jsonResponse = Json::decode($jsonData, true);
        return $jsonResponse;
    }

    public function updateRatingDetails($data) {
        $url = $this->apiUrl() . "/sightseeing/updateSightseeingRateDetail";
        $val = $this->post($url, $data);
        $jsonData = $val->getBody();
        $jsonResponse = Json::decode($jsonData, true);
        return $jsonResponse;
    }

    public function uploadImagesAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $form = new SightseeingImageForm();
        $documentListing = [];
        $id = $this->params()->fromQuery('id');
        if (!empty($id)) {
            //$sessionSightseeingContainer = new Container('addSightseeingData');
            //$sessionSigntseeingId = $sessionSightseeingContainer->s_id;
            
            $sessionSightseeingContainer = new Container('addSightseeingData');
        unset($sessionSightseeingContainer->s_id);
        $sessionSightseeingContainer->s_id = $id;
         $sessionSigntseeingId = $sessionSightseeingContainer->s_id;
            if ($sessionSigntseeingId == $id) {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
                ];
            } else {
                $data = [
                    'auto_id' => $id,
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId
                ];
            }
            $vehicleData = $this->commonModel->getSightseeingDetailsList($data);
            $vehicleData = $vehicleData[0];
            $form->setData($vehicleData);
            $form->get('module_id')->setValue($vehicleData['s_id']);
            $data = [
                'mapping_id' => $vehicleData['s_id'],
                'bkg_type_id' => $this->config()->getConfig()->masterBookingType->activityId
            ];
            $documentListing = $this->commonModel->getActivityUploadImages($data);
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'upload-images',
            'documentListing' => $documentListing,
        ]);
        return $viewModel;
    }

    public function uploadfileAction() {
        $sessionuserData = new Container('userlogin');
        $userId = $sessionuserData->user_id;

        $postData = $this->getRequest()->getPost()->toArray();
        $fileName = $postData['fileuploadname'];
        $type = $postData['type'];
        $module_id = $postData['module_id'];
        $bkg_type_id = $this->config()->getConfig()->masterBookingType->activityId;

        if ($_FILES['file']['name'] != '') {
            $fileNameOfficeAdd = $_FILES['file']['name'];
            $fileTmpNameOfficeAdd = $_FILES['file']['tmp_name'];
            $documentName = $fileName . "_" . time();

            $folderpath = 'activity_image';
            $uploaddir = $this->config()->getConfig()->base_url->file_path; //$_SERVER['DOCUMENT_ROOT'];

            $allowed = array('png', 'jpg', 'gif', 'zip', 'pdf', 'docx', 'doc', 'jpeg', '');
            $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

            if (!in_array(strtolower($extension), $allowed)) {
                $data = array("status" => "error", 'message' => 'Please upload (png,jpg,gif,zip,pdf,docx,doc,jpeg) file only.');
                $view = new JsonModel($data);
                return $view;
            }

            $filepath = $uploaddir . $folderpath;
            $fileUploadName = $documentName . '.' . $extension;
            $targetPath = $filepath . "/" . $fileUploadName;

            $kycFile = file_get_contents($fileTmpNameOfficeAdd);
            $base64string = base64_encode($kycFile);

            $finalData['base64image'] = $base64string;
            $finalData['filepath'] = $targetPath;
            $uploadresp = $this->uploadimageapi($finalData);
            if ($uploadresp['status'] == 'failed') {
                $data = array("status" => "error", "message" => $uploadresp['message']);
                return $view = new JsonModel($data);
            }

            $finalData2 = [
                'user_id' => $userId,
                'mapping_id' => $module_id,
                'bkg_type_id' => $bkg_type_id,
                'image_type' => $fileName,
                'doc_file_upload' => $fileUploadName,
                'status' => 1
            ];
            $responseData = $this->commonModel->uploadActivityImage($finalData2);
            if ($responseData['response']['status'] == 'success') {
                $data = array("status" => "success", 'message' => "File uploaded successfully", "fileUploadName" => $base64string);
            } else {
                $data = array("status" => "error", 'message' => "File not uploaded", "fileUploadName" => $base64string);
            }
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function uploadimageapi($arrval = array()) {
        $url = $this->apiUrl() . "/user/uploadImg";
        $val = $this->post($url, $arrval);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        return $JsonData['responsedata'];
    }

    public function updateImageStatusAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $data = $this->getRequest()->getPost();
        $id = $data['selected'];
        $doc_status = $data['status'];
        $userId = $data['user_id'];
        $data = ['user_id' => $user_id, 'id' => $id, 'status' => $doc_status, 'ip' => $_SERVER['REMOTE_ADDR']];
        $responseData = $this->commonModel->updateActivityImageStatus($data);
        if ($responseData['response']['status'] == 'success') {
            $data = array("status" => "success", 'message' => "Status Changed successfully");
        } else {
            $data = array("status" => "error", 'message' => "Status not Changed");
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function updateImageDefaultStatusAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $data = $this->getRequest()->getPost();
        $id = $data['selected'];
        $doc_status = $data['status'];
        $image_type = $data['image_type'];
        $mapping_id = $data['hotel_id'];

        $data2 = ['image_type' => $image_type, 'user_id' => $userId, 'mapping_id' => $mapping_id, 'ip' => $_SERVER['REMOTE_ADDR']];
        $this->commonModel->resetActivityDefaultImageStatus($data2);

        $data = ['user_id' => $userId, 'id' => $id, 'image_default_status' => $doc_status, 'image_type' => $image_type, 'mapping_id' => $mapping_id, 'ip' => $_SERVER['REMOTE_ADDR']];

        $responseData = $this->commonModel->updateActivityImageDefaultStatus($data);
        if ($responseData['response']['status'] == 'success') {
            $data = array("status" => "success", 'message' => "Status Changed successfully");
        } else {
            $data = array("status" => "error", 'message' => "Status not Changed");
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function sightseeingDetailStatusAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'status' => $status];
        $this->commonModel->updateSightseeingStatus($data);
        $data = [
            'company_id' => $this->config()->getConfig()->company->companyId,
            'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
        ];
        $packageListing = $this->commonModel->getSightseeingDetailsList($data);
        $viewModel = new ViewModel(['packageListing' => $packageListing]);
        $viewModel->setTemplate('/dashboard/sightseeing/sightseeing-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function changeRecordStatusAction() {
        $status = 0;
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            if ($postData['status'] == 0 || $postData['status'] == 2) {
                $status = 1;
            }
            $data = ['user_id' => $user_id, 'id' => $postData['id'], 'status' => $status];
            $this->commonModel->updateSightseeingStatus($data);
        }
        $data = [
            'company_id' => $this->config()->getConfig()->company->companyId,
            'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
        ];
        $packageListing = $this->commonModel->getSightseeingDetailsList($data);
        $viewModel = new ViewModel(['packageListing' => $packageListing]);
        $viewModel->setTemplate('/dashboard/sightseeing/sightseeing-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function deleteSightseeingDetailsAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $id = $this->params()->fromQuery('data');
        $data = ['id' => $id, 'user_id' => $userId, 'status' => 2];
        $this->commonModel->updateSightseeingStatus($data);
        $this->redirect()->toRoute('sightseeing', ['action' => 'index']);
        $this->flashMessenger()->addMessage(array('success' => 'Details Delete Successfully'));
    }

    public function sightseeingRateStatusAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'status' => $status];
        $this->commonModel->updateSightseeingRateStatus($data);
        $data = [
            'company_id' => $this->config()->getConfig()->company->companyId,
            'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
        ];
        $packageListing = $this->commonModel->getActivityDetailsList($data);
        $viewModel = new ViewModel(['packageListing' => $packageListing]);
        $viewModel->setTemplate('/dashboard/sightseeing/sightseeing-rate-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function changeRateRecordStatusAction() {
        $status = 0;
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            if ($postData['status'] == 0 || $postData['status'] == 2) {
                $status = 1;
            }
            $data = ['user_id' => $user_id, 'id' => $postData['id'], 'status' => $status];
            $this->commonModel->updateSightseeingRateStatus($data);
        }
        $data = [
            'company_id' => $this->config()->getConfig()->company->companyId,
            'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
        ];
        $packageListing = $this->commonModel->getActivityDetailsList($data);
        $viewModel = new ViewModel(['packageListing' => $packageListing]);
        $viewModel->setTemplate('/dashboard/sightseeing/sightseeing-rate-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function deleteSightseeingRateDetailsAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $id = $this->params()->fromQuery('data');
        $data = ['id' => $id, 'user_id' => $userId, 'status' => 2];
        $this->commonModel->updateSightseeingRateStatus($data);
        $this->redirect()->toRoute('sightseeing', ['action' => 'rate']);
        $this->flashMessenger()->addMessage(array('success' => 'Details Delete Successfully'));
    }

    public function activityInfoAction() {
        $post = $this->getRequest()->getPost();
        $id = $post['s_id'];
        $activityData = [];
        if (!empty($id)) {
            $data = [
                'mapping_id' => $id,
                'company_id' => $this->config()->getConfig()->company->companyId,
                'master_package_type' => $this->config()->getConfig()->masterBookingType->activityId,
            ];
            $activityData = $this->commonModel->getActivityDetailsList($data);
        }

        $viewModel = new ViewModel(['activityData' => $activityData]);
        $viewModel->setTemplate('/dashboard/sightseeing/activity-info');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function activityFareInfoAction() {
        $post = $this->getRequest()->getPost();
        $id = $post['s_id'];
        $activityFareData = [];
        if (!empty($id)) {
            $data = [
                'mapping_id' => $id,
                'bkg_type_id' => $this->config()->getConfig()->masterBookingType->activityId,
            ];

        $activityFareData = $this->commonModel->getActivityFareList($data);
        $roomServiceData = $this->commonModel->getRoomServiceChargeFareList($data);
        $roomDiscountData = $this->commonModel->getRoomRateDiscountFareList($data);
        }

        $viewModel = new ViewModel([
            'activityFareData' => $activityFareData,
            'roomServiceData' => $roomServiceData, 
            'roomDiscountData'=>$roomDiscountData
        ]);
        $viewModel->setTemplate('/dashboard/sightseeing/activity-fare-info');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    
    public function uploadImageAction() {
        $post = isset($_POST) ? $_POST : array();
        switch ($post['action']) {
            case 'save' :
                $this->saveAvatarTmp();
                break;
            default:
                $this->changeAvatar();
        }
    }
    
    
    function changeAvatar() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $post = isset($_POST) ? $_POST : array();
        $max_width = "500";
        $path = 'images/tmp';
        $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "pdf", "docx", "doc");
        $name = time() . $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];
        if (strlen($name)) {
            list($txt, $ext) = explode(".", $name);
            //Debug::dump($ext);
            //Debug::dump($valid_formats);
            //Debug::dump(in_array($ext, $valid_formats));exit;
            if (in_array($ext, $valid_formats)) {
                if ($size < (1024 * 1024)) { // Image size max 1 MB
                    $actual_image_name = 'avatar' . '_' . $user_id . '.' . $ext;
                    $tmp = $_FILES['photoimg']['tmp_name'];
                    $filePath = PUBLIC_PATH . '/temp/' . $name;
                    $filePreview = '/temp/' . $name;
                    if (move_uploaded_file($tmp, $filePath)) {
                        $width = $this->getWidth($filePath);
                        $height = $this->getHeight($filePath);
                        //Scale the image if it is greater than the width set above
                        if ($width > $max_width) {
                            $scale = $max_width / $width;
                            $uploaded = $this->resizeImage($filePath, $width, $height, $scale);
                        } else {
                            $scale = 1;
                            $uploaded = $this->resizeImage($filePath, $width, $height, $scale);
                        }
                        echo "<img class='photo' file-name='" . $name . "' class='' src='" . $filePreview . '?' . time() . "' class='preview'/>";
                    } else
                        echo "failed";
                } else
                    echo "Image file size max 1 MB";
            } else
                echo "Invalid file format..";
        } else
            echo "Please select image..!";
        exit;
    }
    
    function saveAvatarTmp() {

        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $post = isset($_POST) ? $_POST : array();
        $path = '\\images\uploads\tmp';
        $t_width = 300; // Maximum thumbnail width
        $t_height = 300;    // Maximum thumbnail height

        if (isset($_POST['t']) and $_POST['t'] == "ajax") {
            extract($_POST);

            $crop_enabled = $_POST['crop_enabled'];
            $loc = $_POST['loc'];
            $module_id = $_POST['moduleId'];
            $bkg_type_id = $this->config()->getConfig()->masterBookingType->activityId;
            if ($loc == "main-image" || $loc == "gallery-image") {
                $user_folder = "activity_image";
            }
            $image_quality = '95';
            $imagePath = PUBLIC_PATH . '/upload/' . $user_folder . '/' . $_POST['image_name'];
            $new_image_thumb = PUBLIC_PATH . '/upload/thumb/100x100/' . $user_folder . '/' . $_POST['image_name'];

            $temp_path = PUBLIC_PATH . '/temp/' . $_POST['image_name'];

            if ($crop_enabled == "yes") {

                $ratio = ($t_width / $w1);
                $nw = ceil($w1 * $ratio);
                $nh = ceil($h1 * $ratio);
                $nimg = imagecreatetruecolor($nw, $nh);
                $im_src = imagecreatefromjpeg($temp_path);
                imagecopyresampled($nimg, $im_src, 0, 0, $x1, $y1, $nw, $nh, $w1, $h1);
                $result = imagejpeg($nimg, $imagePath, $image_quality);

                $crop_width = 30;
                $crop_height = 30;
                $thumbNew = imagecreatetruecolor($crop_width, $crop_height);
                imagecopyresampled($thumbNew, $im_src, 0, 0, $x1, $y1, $crop_width, $crop_height, $w1, $h1);
                $thumb = imagejpeg($thumbNew, $new_image_thumb, $image_quality);
            } elseif ($crop_enabled == "no") {
                //echo 'hello';exit;
                $result = copy($temp_path, $imagePath);
                $result1 = copy($temp_path, $new_image_thumb);
                $filename = $new_image_thumb;
                $image = imagecreatefromjpeg($filename);
                list($originalWidth, $originalHeight) = getimagesize($filename);

                // Size of image to create
                $width = 50;
                $height = 50;

                $background = imagecreatetruecolor($width, $height); //create the background 130x130
                $whiteBackground = imagecolorallocate($background, 255, 255, 255);
                imagefill($background, 0, 0, $whiteBackground); // fill the background with white
                imagecopyresampled($background, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight); // copy the image to the background
                header("Content-type: image/jpeg");
                ImageJpeg($background, $new_image_thumb, $image_quality); //display
            }
            //echo '<pre>';print_r();die();
            if ($result) {
                $finalData2 = [
                'user_id' => $userId,
                'mapping_id' => $module_id,
                'bkg_type_id' => $bkg_type_id,
                'image_type' => $loc,
                'doc_file_upload' => $_POST['image_name'],
                'status' => 1
                ];
                $responseData = $this->commonModel->uploadActivityImage($finalData2);
                $image_path_sql = $user_folder . '/' . $_POST['image_name'];
                $response = '/upload/' . $image_path_sql;
            } else {
                $response = "error";
            }
        }
        //echo $imagePath.'?'.time();;
        echo $response;
        exit(0);
    }

}
