<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\CancellationDeadlineForm;
use Zend\View\Model\ViewModel;
use Zend\Json\Json;
use Zend\Debug\Debug;
use Dashboard\Model\Booking;
use Dashboard\Model\CommonModel;
use User\Model\Registration;
use Zend\Session\Container;

class CancellationDeadlineController extends RestAPIClientController {

    public function __construct() {
        $this->bookingModel = new Booking();
        $this->CommonModel = new CommonModel();
        $this->registrationModel = new Registration();
    }
    /**
     * index
     * @return ViewModel
     */
    public function indexAction(){
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $data=[];
        $data = ['user_id'=>$user_id];
        CancellationDeadlineForm::$bookingType = $this->CommonModel->getPackageTypeList();
        CancellationDeadlineForm:: $bookingstatus = $this->bookingModel->getCabStatusList();
        $form = new CancellationDeadlineForm();
        $cancellationListing = $this->bookingModel->getCancelBookings($data);
        $viewModel = new ViewModel(['form'=>$form, 'cancellationListing'=>$cancellationListing]);
        return $viewModel;
    }


        /* Release booking popup */
    public function releaseBookingAction(){
        $data = $this->params()->fromQuery();
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /* Send opt to client for confirm cancel */
    public function sendsmsAction(){
        $postData = $this->getRequest()->getPost();
        $data = $postData->toArray();
        $booking_id = $data['bookingId'];

        if($booking_id!=''){
            $param = ['id' => $booking_id];
            $cancellationListing = $this->bookingModel->getRecentBookings($param);
             if(isset($cancellationListing) && $cancellationListing[0]['user_mobile']!=''){
                $user_id = $cancellationListing[0]['user_id'];
                $resp = $this->registrationModel->resentOtp($user_id);
                if($resp['responsedata']['status']=='success'){
                     $viewModel = new ViewModel(['message' => 'Please enter otp','flag'=>'display-block','flag2'=>'display-none']);
                     $viewModel->setTerminal(true);
                     return $viewModel;
                }
            }
        }
         $viewModel->setTerminal(true);
        $viewModel = new ViewModel(['message' => '','flag'=>'display-block','flag2'=>'display-none']);
        return $viewModel;

    }

    /** @CreatedBY   : Mohit Verma
     *  @Description : Cancel Booking by users {}
     *
    public function cancelbookingAction(){
        $postData = $this->getRequest()->getPost();
        $data = $postData->toArray();
        $booking_id  = $data['booking_id'];
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        $cancellationAmt = 0;
        if($booking_id>0){
            $param  = ['id'=>$booking_id];
            $bookingDetails = $this->bookingModel->getRecentBookings($param);

            if(!empty($bookingDetails)){
                $bookingDetails   = $bookingDetails[0];
                $cancellationRule = json_decode($bookingDetails['booking_cancellation_rule'],true);
                $pickup_date      = $bookingDetails['ordertime'];
                $totalPrice       = $bookingDetails['estimated_final_price'];
                $cgst_tax         = $bookingDetails['cgst_tax'];
                $igst_tax         = $bookingDetails['igst_tax'];
                $sgst_tax         = $bookingDetails['sgst_tax'];

                $date1 = date('Y-m-d H:i:s');
                $date2 = date('Y-m-d H:i:s',strtotime($pickup_date));

                $diff = abs(strtotime($date2) - strtotime($date1));

                $years = floor($diff / (365*60*60*24));
                $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
                    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
                    $hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));

                  foreach($cancellationRule as $key=>$val){
                      $packgeid              = $val['cancellation_master_id'];
                      $cancellation_days     = $val['days'];
                      $cancellation_hours    = $val['hours'];

                    if($days==0 && $hours<=2){
                        $cancelRuleData = $val;
                        break;
                    }
                    if($days==0 && $hours > 2 && $hours<=$cancellation_hours){
                         $cancelRuleData = $val;
                         break;
                    }
                     if($days==0 && $hours>6 && $hours<=$cancellation_hours){
                        $cancelRuleData = $val;
                         break;
                    }
                     if($days>=1 && $days<=$cancellation_days){
                        $cancelRuleData = $val;
                         break;
                    }
                     if($days>=8 && $days<=$cancellation_days){
                        $cancelRuleData = $val;
                          break;
                    }
                     if($days> 1 && $days==$cancellation_days){
                          $cancelRuleData = $val;
                       break;
                    }
                     if($days> 16 && $days <=$cancellation_days){
                         $cancelRuleData = $val;
                        break;
                    }

                }

                if(isset($cancelRuleData) && !empty($cancelRuleData)){
                    if($cancelRuleData['cancellation_type'] == 'Rs') {
                        $cancellationAmt = $cancelRuleData['cancellation_value'];
                    } else {
                        $cancellationAmt = $totalPrice * $cancelRuleData['cancellation_value'] / 100;
                    }

                    if($cgst_tax>0){
                         $cgst_tax_amt  = round($cancellationAmt * $cgst_tax/100,2);
                    }
                    if($igst_tax>0){
                         $igst_tax_amt  = round($cancellationAmt * $igst_tax/100,2);
                    }
                    if($sgst_tax>0){
                        $sgst_tax_amt  = round($cancellationAmt  * $sgst_tax/100,2);
                    }

                    $total_tax_price = $cgst_tax_amt + $igst_tax_amt + $sgst_tax_amt;
                    $cancellationAmt = $cancellationAmt + $total_tax_price;
                    $cancellationCharge = $totalPrice - $cancellationAmt;

                    $markupurl = $this->apiUrl() . "/Booking/bookingmarkup?bookingid=$booking_id";
                    $resp = $this->get($markupurl);
                    $response = Json::decode($resp->getBody(), true);

                    if($response['responsedata']['status']=='success'){
                       $marskupDataArr  = $response['responsedata']['data'];
                       $marskupData     = $marskupDataArr[0];
                       $markuptype      = $marskupData['mark_amt_type'];
                       $markupamt       = $marskupData['basic_amt'];
                       if($markuptype == 'Rs') {
                            $markupamt = $markupamt;
                        } else {
                            $markupAmt = round($totalPrice * $markupamt / 100,2);
                        }

                       $markupwithtax  = round($markupAmt * ($cgst_tax_amt + $igst_tax_amt + $sgst_tax_amt)/100,2);
                       $bookingDetails['markup_type']   = $markuptype;
                       $bookingDetails['markup_value']  = $markupamt;
                       $bookingDetails['markup_price']  = $markupwithtax;
                    }


                    $bookingCancelInvoiceNO = $this->getCancelInvoiceNo();

                    $cancellation_rule_id = $cancelRuleData['cancellation_master_id'];
                    $data['user_id'] = $user_id;
                    $data['booking_id'] = $booking_id;
                    $data['booking_transaction_no'] = '';
                    $data['amount'] = $cancellationCharge;
                    $data['current_balance'] = '';
                    $data['payment_response_id'] = '';
                    $data['payment_type_id'] = '';
                    $data['payment_status'] = 1;
                    $data['action_type'] = 'Credit';
                    $data['created_date'] = date('Y-m-d');
                    $data['created_by'] = $user_id;

                    $url  = $this->apiUrl() . "/payment/userTransaction";
                   // $resp = $this->post($url, $data);
                    //$response = Json::decode($resp->getBody(), true);

                    $data2 = [
                        'booking_id' => $booking_id,
                        'status_c'   => 21
                    ];

                    $url1 = $this->apiUrl() . "/Booking/updatebookingstatus";
                   //$resp = $this->post($url1, $data2);

                    $bookingDetails['cancellation_charge']  = $cancellationAmt;
                    $bookingDetails['cancellation_rule_id'] = $cancellation_rule_id;

                    $bookingDetails['cgst_amount'] = $cgst_tax_amt;
                    $bookingDetails['igst_amount'] = $igst_tax_amt;
                    $bookingDetails['sgst_amount'] = $sgst_tax_amt;
                    $bookingDetails['total_tax_price'] = $total_tax_price;
                    $bookingDetails['invoice_no'] = $bookingCancelInvoiceNO;

                    $url1 = $this->apiUrl() . "/Booking/bookingRefund";
                    $resp = $this->post($url1, $bookingDetails);

                }

                $this->redirect()->toRoute('cancellationdeadline', ['action' => 'index']);
            }

            //echo '<pre>';print_r($cancellationRule);die();
        }


    } /* END */

  public function cancelbookingAction(){
        $postData = $this->getRequest()->getPost();
        $data = $postData->toArray();
        $booking_id  = $data['booking_id'];
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        $cancellationAmt = 0;
        if($booking_id>0){
               $params = [
                   'booking_id'=>$booking_id,
                   'user_id'=>$user_id];
              $url1 = $this->apiUrl() . "/Booking/bookingRelease";
              $resp = $this->post($url1, $params);
echo '<pre>';print_r($resp);die();
        }
  }


    /**
     * Get User cancellation invoice no
     * @return JSON
     */
    public function getCancelInvoiceNo() {
        $year = date('Y');
        $month = date('m');
        if ($month <= 03) {
            $year = $year - 1;
        }
        $url = $this->apiUrl() . "/booking/cancelInvoiceNo";
        $resp = $this->get($url);
        $invoiceData = Json::decode($resp->getBody(), true);
        if ($invoiceData['responsedata'][0]['invoice_number'] != "") {
            $invoiceNo = $invoiceData['responsedata'][0]['invoice_number'];
        } else {
            $invoiceNo = $this->config()->getConfig()->invoice->cancelinvoiceStart;
        }
        $invoiceNo = $this->config()->getConfig()->invoice->cancelinvoicePrefix . substr($year, 2) . '/' . $invoiceNo;
        return $invoiceNo;
    }
    
    
    public function searchCancellationRecordAction(){
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        
        $data = [];
        if($this->getRequest()->getPost()){
            $postData = $this->getRequest()->getPost();
            $data = $postData->toArray();            
            $data['status'] =  isset($data['booking_status'])?$data['booking_status']:'';
            $data['from_date'] =  isset($data['from_date'])?date('Y-m-d',strtotime($data['from_date'])):'';
            $data['to_date'] =  isset($data['to_date'])?date('Y-m-d',strtotime($data['to_date'])):'';
        }
        $data['user_id'] = $user_id;
       
        $data = array_filter($data);
        $bookingHistory = $this->bookingModel->getRecentBookings($data);
        $bookingHistoryListing = $bookingHistory;
        $viewModel = new ViewModel(['cancellationListing' => $bookingHistoryListing]);
        $viewModel->setTemplate('dashboard/cancellation-deadline/cancellation-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

}
