<?php
 namespace GARANTI;

 class GARANTI{
     public $strPayMode = '3D';
     public $strMode = "PROD";
     public $strVersion = "v0.01";
     public $strTerminalID;
     public $strTerminalID_;
     public $strProvUserID = "PROVAUT";
     public $strProvisionPassword;
     public $strUserID;
     public $strMerchantID;
     public $strIPAddress;
     public $strEmailAddress;
     public $strFirstName = '';
     public $strLastName = '';
     public $strTelephone = '';
     public $strOrderID;
     public $strInstallmentCnt = 0;
     public $strNumber;
     public $strExpireMonth;
     public $strExpireYear;
     public $strCVV2;
     public $strAmount = 0;
     public $strType = "sales"; // garanti pay için : gpdatarequest ,  normal pos için  : sales
     public $strSubType = ""; // sadece garanti pay için kullanılmakta
     public $strCurrencyCode = "949";
     public $strCardholderPresentCode = "0";
     public $strMotoInd = "N";
     public $strHostAddress = "https://sanalposprov.garanti.com.tr/VPServlet";
     public $str3dPostUrl = 'https://sanalposprov.garanti.com.tr/servlet/gt3dengine';
     public $str3dPostTestUrl = 'https://sanalposprovtest.garanti.com.tr/servlet/gt3dengine';
     public $strProvTestUrl = 'https://sanalposprovtest.garanti.com.tr/VPServlet';
     public $strSecurityData;
     public $strHashData;
     public $strStoreKey;
     public $strSecure3dsecuritylevel='3D_PAY'; // garanti pay için CUSTOM_PAY, normal ödeme için 3D_PAY
     public $strSuccessUrl = '';
     public $strFailedUrl = '';
     public $strCompanyName = '';
/*
     public function isGarantiPay($status=false){
         if($status){
             $this->strType = 'gpdatarequest';
             $this->strSubType = 'sales';
             $this->strSecure3dsecuritylevel = 'CUSTOM_PAY';
         }
     }
*/
     public function setPayMode($mode){
         $this->strPayMode = $mode;
     }

     public function setMode($mode){
         $this->strMode = $mode;
     }
     public function setTerminalId($terminalId){
         $this->strTerminalID  = $terminalId;
         $this->strTerminalID_ = '0'.$terminalId;
     }
     public function setProvisionPassword($provisionPassword){
         $this->strProvisionPassword = $provisionPassword;
     }
     public function setUserId($userId){
         $this->strUserID = $userId;
     }
     public function setStrStoreKey($key){
         $this->strStoreKey = $key;
     }
     public function getIpAddres(){
         $ipaddress = '';
         if (isset($_SERVER['HTTP_CLIENT_IP']))
             $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
         else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
             $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
         else if(isset($_SERVER['HTTP_X_FORWARDED']))
             $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
         else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
             $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
         else if(isset($_SERVER['HTTP_FORWARDED']))
             $ipaddress = $_SERVER['HTTP_FORWARDED'];
         else if(isset($_SERVER['REMOTE_ADDR']))
             $ipaddress = $_SERVER['REMOTE_ADDR'];
         else
             $ipaddress = 'UNKNOWN';

         $this->strIPAddress = $ipaddress;
         return $ipaddress;
     }
     public function setMerchantID($merchantID){
         $this->strMerchantID = $merchantID;
     }
     public function setEmailAddress($email){
         $this->strEmailAddress = $email;
     }
     public function setFirstName($name){
         $this->strFirstName = $name;
     }
     public function setLastName($lastName){
         $this->strLastName = $lastName;
     }
     public function setTelephone($telephone){
         $this->strTelephone = $telephone;
     }
     public function setOrderID($orderId){
         $this->strOrderID = $orderId;
     }
     public function setInstallmentCnt($installment){
         $this->strInstallmentCnt = $installment;
     }
     public function setNumber($cartNumber){
         $cartNumber = str_replace(' ','',trim($cartNumber));
         $this->strNumber = $cartNumber;
     }
     public function setExpireMonth($date){
         $this->strExpireMonth = $date;
     }
     public function setExpireYear($date){

         $this->strExpireYear = strlen($date)==4?substr($date,2,2):$date;
     }
     public function getExpireDate(){
         $date = $this->strExpireMonth.$this->strExpireYear;
         $date = strlen($date)==3?'0'.$date:$date;
         return $date;
     }
     public function setCVV2($ccv){
         $this->strCVV2 = $ccv;
     }
     public function setAmount($amount){
         $this->strAmount = $amount * 100;
     }
     public function setCurrencyCode($currency){
         $this->strCurrencyCode = $currency;
     }
     public function setSecurityData(){
         $this->strSecurityData = strtoupper(sha1($this->strProvisionPassword . $this->strTerminalID_));
     }
     public function setHashData($type='3D'){
         if($type=='3D') {
             $HashData = strtoupper(sha1($this->strTerminalID . $this->strOrderID . $this->strAmount . $this->strSuccuessUrl . $this->strFailedUrl . $this->strType . $this->strInstallmentCnt . $this->strStoreKey . $this->strSecurityData));
         }else{
             $HashData = strtoupper(sha1($this->strOrderID . $this->strTerminalID . $this->strNumber.$this->strAmount . $this->strSecurityData));
         }
         $this->strHashData = $HashData;
     }
     public function setSecure3dsecuritylevel($level){
         $this->strSecure3dsecuritylevel = $level;
     }
     public function setSuccessUrl($url){
         $this->strSuccuessUrl = $url;
     }
     public function setFailedUrl($url){
         $this->strFailedUrl = $url;
     }
     public function pay(){

         $this->setSecurityData();
         $this->setHashData($this->strPayMode);

         if($this->strPayMode == '3D'){
            $this->pay3D();
         }else if($this->strPayMode == 'GARANTI_PAY'){
             return $this->garantiPay();
         }else{
             return $this->payStandart();
         }

     }
     public function get3dPostUrl(){
         return $this->strMode == 'TEST'?$this->str3dPostTestUrl:$this->str3dPostUrl;
     }

     public function getApiPostUrl(){
         return $this->strMode == 'TEST'?$this->strProvTestUrl:$this->strHostAddress;
     }
     protected function pay3D(){

         $form = "";
         $form .= "<form action=\"".$this->get3dPostUrl()."\" method=\"post\" name=\"FormGarantiOdeme\" id=\"FormGarantiOdeme\" >\r
					<input type=\"hidden\" name=\"secure3dsecuritylevel\" value=\"" . $this->strSecure3dsecuritylevel . "\"  />\r
					<input type=\"hidden\" name=\"cardnumber\" value=\"" . $this->strNumber . "\" />\r
					<input type=\"hidden\" name=\"cardexpiredatemonth\" value=\"" . $this->strExpireMonth . "\" />\r
					<input type=\"hidden\" name=\"cardexpiredateyear\" value=\"" . $this->strExpireYear . "\" />\r
					<input type=\"hidden\" name=\"cardcvv2\" value=\"" . $this->strCVV2 . "\"/>\r
					<input type=\"hidden\" name=\"mode\" value=\"" . $this->strMode . "\" />\r
					<input type=\"hidden\" name=\"apiversion\" value=\"" . $this->strVersion . "\" />\r
					<input type=\"hidden\" name=\"terminalprovuserid\" value=\"" . $this->strProvUserID . "\" />\r
					<input type=\"hidden\" name=\"terminaluserid\" value=\"" . $this->strUserID . "\" />\r
					<input type=\"hidden\" name=\"terminalmerchantid\" value=\"" . $this->strMerchantID . "\" />\r
					<input type=\"hidden\" name=\"txntype\" value=\"" . $this->strType . "\" />\r
					<input type=\"hidden\" name=\"txnamount\" value=\"" . $this->strAmount . "\" />\r
					<input type=\"hidden\" name=\"txncurrencycode\" value=\"" . $this->strCurrencyCode . "\" />\r
					<input type=\"hidden\" name=\"txninstallmentcount\" value=\"" . $this->strInstallmentCnt . "\" />\r
					<input type=\"hidden\" name=\"orderid\" value=\"" . $this->strOrderID . "\" />\r
					<input type=\"hidden\" name=\"terminalid\" value=\"" . $this->strTerminalID . "\" />\r
					<input type=\"hidden\" name=\"successurl\" value=\"" . $this->strSuccuessUrl . "\" />\r
					<input type=\"hidden\" name=\"errorurl\" value=\"" . $this->strFailedUrl . "\" />\r
					<input type=\"hidden\" name=\"customeripaddress\" value=\"" . $this->getIpAddres() . "\" />\r
					<input type=\"hidden\" name=\"customeremailaddress\" value=\"" . $this->strEmailAddress . "\" />\r
					<input type=\"hidden\" name=\"secure3dhash\" value=\"" . $this->strHashData . "\" />\r
					\r
					\r
				</form>";
         //$form .= '<script type="text/javascript">document.getElementById("FormGarantiOdeme").submit();$("#FormGarantiOdeme").submit();</script>';
         echo $form;
         exit;

     }

     protected function payStandart(){

         $xml = '' . "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r
        <GVPSRequest>\r
            <Mode>" . $this->strMode . "</Mode>
            <Version>" . $this->strVersion . "</Version>\r
            <Terminal>
                <ProvUserID>" . $this->strProvUserID . "</ProvUserID>
                <HashData>" . $this->strHashData . "</HashData>
                <UserID>" . $this->strUserID . "</UserID>
                <ID>" . $this->strTerminalID . "</ID>
                <MerchantID>" . $this->strMerchantID . "</MerchantID>
            </Terminal>\r
            <Customer>
                <IPAddress>" . $this->getIpAddres() . "</IPAddress>
                <EmailAddress>" . $this->strEmailAddress . "</EmailAddress>
            </Customer>\r
            <Card>
                <Number>" . $this->strNumber . "</Number>
                <ExpireDate>" . $this->getExpireDate() . "</ExpireDate>
                <CVV2>" . $this->strCVV2 . "</CVV2>
            </Card>\r
            <Order>
                <OrderID>" . $this->strOrderID . "</OrderID>
                <GroupID></GroupID>
                <AddressList><Address>
                <Type>S</Type>
                <Name>" . $this->strFirstName . "</Name>
                <LastName>" . $this->strLastName . "</LastName>
                <Company></Company>
                <Text></Text>
                <District></District>
                <City></City>
                <PostalCode></PostalCode>
                <Country></Country>
                <PhoneNumber>" . $this->strTelephone . "</PhoneNumber>
                </Address></AddressList>
            </Order>
            <Transaction>
                <Type>" . $this->strType . "</Type>
                <InstallmentCnt>" . $this->strInstallmentCnt . "</InstallmentCnt>
                <Amount>" . $this->strAmount . "</Amount>
                <CurrencyCode>" . $this->strCurrencyCode . "</CurrencyCode>
                <CardholderPresentCode>" . $this->strCardholderPresentCode . "</CardholderPresentCode>
                <MotoInd>" . $this->strMotoInd . "</MotoInd>
                <Description></Description>
                <OriginalRetrefNum></OriginalRetrefNum>
            </Transaction>\r
        </GVPSRequest>";
         //	print_r($xml);die();
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $this->getApiPostUrl());
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, "data=" . $xml);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         $results = curl_exec($ch);
         curl_close($ch);
         if($results !== false) {
             $return = simplexml_load_string($results);
             $return = $return->Transaction;
         }else{
             $return = false;
         }
         return $return;
     }

     protected function garantiPay(){

         $this->strType = 'gpdatarequest';
         $this->strSubType = 'sales';
         $this->strSecure3dsecuritylevel = 'CUSTOM_PAY';

         $xml = '' . "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r
        <GVPSRequest>\r
            <Mode>" . $this->strMode . "</Mode>
            <Version>" . $this->strVersion . "</Version>\r
            <ChannelCode></ChannelCode>\r
            <Terminal>
                <ProvUserID>" . $this->strProvUserID . "</ProvUserID>
                <HashData>" . $this->strHashData . "</HashData>
                <UserID>" . $this->strUserID . "</UserID>
                <ID>" . $this->strTerminalID . "</ID>
                <MerchantID>" . $this->strMerchantID . "</MerchantID>
            </Terminal>\r
            <Customer>
                <IPAddress>" . $this->getIpAddres() . "</IPAddress>
                <EmailAddress>" . $this->strEmailAddress . "</EmailAddress>
            </Customer>\r
            <Card>
                <Number>" . $this->strNumber . "</Number>
                <ExpireDate>" . $this->getExpireDate() . "</ExpireDate>
                <CVV2>" . $this->strCVV2 . "</CVV2>
            </Card>\r
            <Order>
                <OrderID>" . $this->strOrderID . "</OrderID>
                <GroupID></GroupID>
                <AddressList>
                    <Address>
                    <Type>S</Type>
                    <Name>" . $this->strFirstName . "</Name>
                    <LastName>" . $this->strLastName . "</LastName>
                    <Company></Company>
                    <Text></Text>
                    <District></District>
                    <City></City>
                    <PostalCode></PostalCode>
                    <Country></Country>
                    <PhoneNumber>" . $this->strTelephone . "</PhoneNumber>
                    </Address>
                </AddressList>
            </Order>
            <Transaction>
                <Type>" . $this->strType . "</Type>
                <SubType>" . $this->strSubType . "</SubType>
                <InstallmentCnt>" . $this->strInstallmentCnt . "</InstallmentCnt>
                <Amount>" . $this->strAmount . "</Amount>
                <CurrencyCode>" . $this->strCurrencyCode . "</CurrencyCode>
                <CardholderPresentCode>" . $this->strCardholderPresentCode . "</CardholderPresentCode>
                <MotoInd>" . $this->strMotoInd . "</MotoInd>
                <Secure3D>
                    <AuthenticationCode></AuthenticationCode>
                    <SecurityLevel></SecurityLevel>
                    <TxnID></TxnID>
                    <Md></Md>
                </Secure3D>
                <GarantiPaY>
                    <bnsuseflag>N</bnsuseflag>    
                    <fbbuseflag>N</fbbuseflag >   
                    <chequeuseflag>N</chequeuseflag> 
                    <mileuseflag>N</mileuseflag >  
                    <CompanyName>Ozgur and Associates</CompanyName>
                    <ReturnUrl></ReturnUrl>
                    <TCKN>21731114538</TCKN>
                    <GSMNumber>5375277715</GSMNumber>
                    <TotalInstallmentCount>2</TotalInstallmentCount>
                    <AddCampaingInstallment></AddCampaingInstallment>
                    <GPInstallments>
                        <Installment>
                            <Installmentnumber>1</Installmentnumber>
                            <Installmentamount>2234</Installmentamount>
                            <Installmentratewithreward>TTTTKK</Installmentratewithreward>
                        </Installment>
                        <Installment>
                            <Installmentnumber>2</Installmentnumber>
                            <Installmentamount>1522</Installmentamount>
                            <Installmentratewithreward>TTTTKK</Installmentratewithreward>
                        </Installment>
                    </GPInstallments>
                </GarantiPaY> 
            </Transaction>\r
        </GVPSRequest>";
         //	print_r($xml);die();
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $this->getApiPostUrl());
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, "data=" . $xml);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         $results = curl_exec($ch);
         curl_close($ch);
         if($results !== false) {
             $return = simplexml_load_string($results);
             $return = $return->Transaction;
         }else{
             $return = false;
         }
         //echo '<pre>';print_r($return);die();
         return $return;
     }
 }
