<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Reservation extends CI_Controller {

	public function index()
	{

/*
<a href="/lang/turkish">Türkçe</a>
*/		
		redirect("/");
	}

		public function search()
	{

if($_GET){
$gelen=$_GET;   
}else{
$gelen=$_POST;       
}
if(!$gelen){

exit();
}	
$hata=0;
$hata_aciklama="";
//print_r($gelen);
if(!isset($gelen["fiyat_id"]) || $gelen["fiyat_id"]==0 ){
$hata=1;
$hata_aciklama="Paket Seçimi Yapmalısınız.";

echo '<div class="alert alert alert-border-bottom alert-danger dark bg-gradient alert-dismissable">
<i class="fa fa-check pr10"></i><strong>Hata! </strong> Paket Seçimi Yapmalısınız.</a>
</div>

';
return false;
exit();        
}                 
//print_r($gelen);

$eccbilgi=Genel::get_company_info();
//print_r($eccbilgi);
$grup_detay=genel::grup_detay($gelen["paket_id"]);
//print_r($grup_detay);

 $link = genel::sistem_ayarlari(23).'api/mice/search/'.genel::get_apikey()."/tr/".$grup_detay->group_id."/".$gelen["paket_id"]."/".$gelen["fiyat_id"]."/?";

    $link.='satis_tarihi='.date("Y-m-d");
    
    $link.='&iptal_voucher=';
    $link.='&roomCount=1';
    $link.='&adult[]='.$gelen['adult'];
    $link.='&child1age[]='.$gelen['child1age'];
    $link.='&child2age[]='.$gelen['child2age'];
    $link.='&child3age[]=0';
    $link.='&child4age[]=0';

   
//echo $link;

    $sonuclar=file_get_contents($link);
  $sonuclar=json_decode($sonuclar,true);

//print_r($sonuclar);

$data["hata"]=$hata;
$data["hata_aciklama"]=$hata_aciklama;
$data["grup_id"]=$gelen["paket_id"];
$sonuclar=$data["sonuclar"]=$sonuclar;


		$this->lang->load('information',$this->session->userdata('site_lang'));
		$this->load->view('reservation/search_result',isset($data) ? $data : NULL);
	}




function guest_info($grup_id=0,$token=NULL){

$eccbilgi=Genel::get_company_info();


$data["token"]=$token;

    if(!isset($_GET['package_token'])){
        redirect($this->agent->referrer());
    }

    $this->db->where('token',$token)->delete('booking_products_mice_selected_packages');;

    $data["token"]=$token;
    foreach ($_GET['package_token'] AS $roomToken => $PackageToken){
        $datass=[
            "token"=>$token,
            "roomToken"=>$roomToken,
            "packageToken"=>$PackageToken
        ];
        $this->db->insert('booking_products_mice_selected_packages',$datass);
        /*
            echo $roomToken." - ".$PackageToken;
            echo "<br>";
            */
    }

    ;
    $this->db->group_start();
    $sira=0;
    foreach ($_GET['package_token'] AS $roomToken => $PackageToken){
        $sira=$sira+1;
        if($sira==1){
            $this->db->where('package_token',$PackageToken);
        }else{
            $this->db->or_where('package_token',$PackageToken);
        }

    }
    $this->db->group_end();
    $package_details=$data['package_details']=$this->db->where('token',$token)->get("booking_products_mice")->result();



$package_token=$data['package_token']=$PackageToken;
    $room_token=$data['room_token']=$roomToken;




$data["token"]=$token;
$data["grup_id"]=$grup_id;

$data["grup_detay"]=$grup_detay=genel::grup_detay($grup_id);

$data["mudurler"]=$this->db->order_by('manager',"ASC")->get("mices_groups_packages_managers")->result();;

//print_r($detay);
$data["criterias"]=$criteries=$this->db->where('token',$token)->get("booking_products_mice_criteries")->row();






$this->lang->load('information',$this->session->userdata('site_lang'));
$this->load->view('reservation/guest_info',isset($data) ? $data : NULL);
}



function update_passengers($grup_id=0,$token=NULL){
//print_r($_POST);

$package_token=$this->input->post('package_token',true);

$bilgiler="";
$bilgiler.="token=".$token;
$bilgiler.="&contact[name]=".$_POST["iletisim_isim"];
$bilgiler.="&contact[surname]=".$_POST["iletisim_soyisim"];
$bilgiler.="&contact[year_of_birth]=".$_POST["iletisim_d_yili"];
$bilgiler.="&contact[tc_id_number]=".$_POST["iletisim_tckimlik"];

$bilgiler.="&contact[email]=".$_POST["iletisim_mail"];
$bilgiler.="&contact[phone]=".$_POST["iletisim_telefon"];
$bilgiler.="&contact[country]=TR";
$bilgiler.="&contact[city]=";
$bilgiler.="&contact[address]=";
$bilgiler.="&contact[customer_note]=".$_POST["tb_fatura_ozelistekler"];
$bilgiler.="&contact[operation_note]=";


$bilgiler.="&invoice[name]=".$_POST["iletisim_isim"]." ".$_POST["iletisim_soyisim"];
$bilgiler.="&invoice[email]=".$_POST["iletisim_mail"];
$bilgiler.="&invoice[tax_office]=";
$bilgiler.="&invoice[tax_number]=";
$bilgiler.="&invoice[address]=";
$bilgiler.="&invoice[city]=";

    $bilgiler.="&packageToken[".$this->input->post('roomToken',true)."]=".$package_token;
foreach ($_POST["guesttype"] as $key => $value) {


$bilgiler.="&kisiler[kisi_token][]=".$key;
$bilgiler.="&guesttype[".$this->input->post('roomToken',true)."][]=".$_POST["guesttype"][$key];
$bilgiler.="&gender[".$this->input->post('roomToken',true)."][]=".$_POST["gender"][$key];
$bilgiler.="&name_surname[".$this->input->post('roomToken',true)."][]=".$_POST["name_surname"][$key];
$bilgiler.="&manager[".$this->input->post('roomToken',true)."][]=".$_POST["manager"][$key];
$bilgiler.="&city[".$this->input->post('roomToken',true)."][]=".$_POST["city"][$key];
$bilgiler.="&age[".$this->input->post('roomToken',true)."][]=".$_POST["age"][$key];





}


$adres= genel::sistem_ayarlari(23).'api/mice/update-customer/'.genel::get_apikey()."/tr/".$token."/".$package_token;

$curl = curl_init($adres);
$data_string=$bilgiler;
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
   
    'Content-Length: ' . strlen($data_string))
    );

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string); 

    
    $result = curl_exec($curl);
    curl_close($curl);

  //print_r($result);
$result=json_decode($result,true);

//print_r($result);

 

if($result["error"]==0){
redirect("/reservation/checkout/".$grup_id."/".$token);
}else{
redirect($this->agent->referrer());
}

}




function checkout($grup_id=0,$token=NULL){

$data["eccbilgi"]=$eccbilgi=Genel::get_company_info();
//print_r($eccbilgi);

$url=genel::sistem_ayarlari(23)."api/get-reservation-details/".genel::get_apikey()."/tr/".$token;
$detay=file_get_contents($url);
$detay=$data["detay"]=json_decode($detay,true);
//print_r($detay);

$data["grup_id"]=$grup_id;
$data["grup_detay"]=$grup_detay=genel::grup_detay($grup_id);




if($detay['general']["remaining_payment"]<1){
redirect("reservation/summary/".$grup_id."/".$token);	
}
$data["token"]=$token;
$this->lang->load('information',$this->session->userdata('site_lang'));
$this->load->view('reservation/odeme',isset($data) ? $data : NULL);
}

function make_cc_payment(){
//print_r($_POST);

$KartInfo=explode("_",$_POST['taksit_id']);
    $GroupId=isset($KartInfo[0]) ? $KartInfo[0] : 0;
    $posId=isset($KartInfo[1]) ? $KartInfo[1] : 0;
    $installment=isset($KartInfo[2]) ? $KartInfo[2] : 0;
    $extra_installment=isset($KartInfo[3]) ? $KartInfo[3] : 0;

    $grup_id=$_POST["grup_id"];
    $token=$_POST["token"];
    $Currency=$_POST["kur"];
    $Amount=$_POST["amount"];
$CardHolder=isset($_POST["name"]) ? $_POST["name"] : null;
$CardNo=isset($_POST["number"]) ? $_POST["number"] : null;
$ExpiryDate=isset($_POST["expiry"]) ? $_POST["expiry"] : null;
$CvvNo=isset($_POST["cvc"]) ? $_POST["cvc"] : null;
    $ExpiryDates=explode('/',$ExpiryDate);
$ExpiryMonth=isset($ExpiryDates[0]) ? $ExpiryDates[0] : null;
$ExpiryYear=isset($ExpiryDates[1]) ? $ExpiryDates[1] : null;
    $ExpiryYear=trim($ExpiryYear);
    if(strlen($ExpiryYear)==2){
        $ExpiryYear="20".$ExpiryYear;
    }
$dataForPost=[
    "token"=>$token,
    "Amount"=>$Amount,
    "Currency"=>$Currency,
    "PaymentType"=>2,
    "Options"=>[
            "PosId"=>$posId,
            "PosGroupId"=>$GroupId,
            "Installment"=>$installment,
            "ExtraInstallment"=>$extra_installment,
            "CardHolder"=>$CardHolder,
            "CardNo"=>$CardNo,
            "ExpiryMonth"=>trim($ExpiryMonth),
            "ExpiryYear"=>trim($ExpiryYear),
            "CvvNo"=>$CvvNo
    ],
    "SuccessUrl"=>config_item('site_adresi')."reservation/payment-result-success/".$token."/".$grup_id,
    "ErrorUrl"=>config_item('site_adresi')."reservation/payment-result-fail/".$token."/".$grup_id,
];

    $this->load->model('api');

    $RequestUrl="Reservations/PaymentServices/BeginTransaction";


    $Apikey=genel::get_apikey();

    $PaymentTypes=api::curlPost($Apikey,$RequestUrl, "POST", $dataForPost);
    $Response=json_decode($PaymentTypes);

    //print_r($PaymentTypes);



    if (!isset($Response->success)) {

        redirect('/reservation/payment-result-fail/' . $token.'/'.$grup_id.'?ErrorMessage='.lang('Main.__there_is_an_unknown_error'));
       exit();

    }
    // print_r($Response);
    if (!$Response->success) {

        $ErrorDescription = $Response->errorCode . " - " . $Response->description;
        redirect('/reservation/payment-result-fail/' . $token.'/'.$grup_id.'?ErrorMessage='.$ErrorDescription);
        exit();
       // return redirect()->to('/reservation/payment-result-fail/' . $token.'?ErrorMessage='.$ErrorDescription);


    }

    $ResponseData = $Response->data;
    $FormContent = '<form method="POST" action="' . $ResponseData->postUrl . '" id="paymentForm">';

    $FormContent .= $ResponseData->html;

    $FormContent .= '</form>';
    echo $FormContent;
    echo '<script
			  src="https://code.jquery.com/jquery-3.6.0.min.js"
			  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
			  crossorigin="anonymous"></script>
<script>
$("#paymentForm").submit();
</script>			  
			  
			  ';


}

    public function payment_result_fail($Token,$GrupId){
        //print_r($_GET);

        $data['description']=$_GET['ErrorMessage'];
        $data['reloadtime']=5;
        $this->load->view('reservation/payment_includes/fail',isset($data) ? $data : NULL);
    }

    public function payment_result_success($Token,$GrupId){
        $this->load->view('reservation/payment_includes/success',isset($data) ? $data : NULL);
    }



function make_cc_payment1(){

$token=$_GET["token"];
$data["eccbilgi"]=$eccbilgi=Genel::get_company_info();
//print_r($_POST);
$grup_id=$_POST["grup_id"];
$token=$_POST["token"];
$card_number=$_POST["number"];
$card_number=str_replace(" ","",$card_number);
$skt=$_POST["expiry"];
list($skt_ay,$skt_yil)=explode("/",$skt);

$skt_ay=trim($skt_ay);
$skt_yil=trim($skt_yil);
$card_holder=$_POST["name"];
$instalment=$_POST["taksit_id"];


list($Group_id,$card_id,$installment,$extrainstallment)=explode("_",$instalment);


$bilgiler="";

$bilgiler.="token=".$token;
$bilgiler.="&card_number=".$card_number;
$bilgiler.="&skt_ay=".$skt_ay;
$bilgiler.="&skt_yil=".$skt_yil;
$bilgiler.="&card_holder=".$card_holder;
$bilgiler.="&instalment=".$instalment;
$bilgiler.="&cvc=".$_POST["cvc"];
$bilgiler.="&amount=".$_POST["amount"];
$bilgiler.="&kur=".$_POST["kur"];
$bilgiler.="&user_id=".genel::site_bilgi()->user_id;
$bilgiler.="&return_url=".config_item('site_adresi')."reservation/payment-result/".$token."/".$grup_id;



$year=substr($this->input->post('ccyear',true), -2,2);



$postData="pos_id=".$card_id;
$postData.="&bank_program=".$Group_id."_".$card_id;
$postData.="&installment=".$installment."_".$extrainstallment;
$postData.="&amount=".$_POST["amount"];
$postData.="&number=".$card_number;
$postData.="&expiry=".$skt_ay."/".$skt_yil;
$postData.="&cvc=".$this->input->post('cvc',true);
$postData.="&token=".$token;
$postData.="&currency=TRY";
$postData.="&return_url=".config_item('site_adresi')."reservation/payment-result/";
$postData.="&name=".$card_holder;
$postData.="&user_id=".genel::site_bilgi()->user_id;



//print_r($postData);

$app_url=genel::sistem_ayarlari(23);
$url=$app_url."reservation/payments/cc-payment/tr";

$ch = curl_init();


curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
    curl_setopt($ch,CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_POST, strlen($postData));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    
    $output=curl_exec($ch); 

    curl_close($ch); 
    
    print_r($output);

}

function payment_result($result=NULL){
//print_r($_GET);

$this->lang->load('information',$this->session->userdata('site_lang'));
if($result=="fail"){
$this->load->view('reservation/payment_includes/fail',isset($data) ? $data : NULL); 
}elseif($result=="success"){
$this->load->view('reservation/payment_includes/success',isset($data) ? $data : NULL);     
}

}



function summary($grup_id=0,$token=NULL){


$data["grup_id"]=$grup_id;

$data["grup_detay"]=$grup_detay=genel::grup_detay($grup_id);

$data["eccbilgi"]=$eccbilgi=Genel::get_company_info();

$url=genel::sistem_ayarlari(23)."api/get-reservation-details/".genel::get_apikey()."/tr/".$token;
$detay=file_get_contents($url);
$detay=$data["detay"]=json_decode($detay,true);


//print_r($detay);

if($detay['general']["remaining_payment"]>=1){
redirect("reservation/checkout/".$grup_id."/".$token);	
}
$data["token"]=$token;
$this->lang->load('information',$this->session->userdata('site_lang'));
$this->load->view('reservation/summary',isset($data) ? $data : NULL);


}



}
