  <?php
	include 'header.php';
	require_once('stripe-php-5.7.0/init.php');
 
 
 
	//PODESAVANJE MEJLA
    include 'emailsetting.php'; 
	
	$mail->SetFrom($from_email, "Z-ALS.ch");
	$mail->Subject = "NEUE RESERVIERUNG";

 
	$placanje = 'cashincar';
	$uslovi = '';
	$rezultat = '';
 
	

    if (!empty($_POST["placanje"])) {
        $placanje = $_POST["placanje"];
   }

 

    include 'obrada_podataka.php';

    if ( isset($_POST['submit_payment']) && $placanje != 'creditcard' ) {
        $rezultat .= $prevodRezultatSuccess;
        ?>
        <div class="steps izborauta">
            <div class="steps-box active">
                <?php echo $prevoStepsVehicles;?>
            </div>
             
            <div class="steps-box active">
                <?php echo $prevoStepsPassengers;?>
            </div>
            <div class="steps-box active">
                <?php echo $prevoStepsPayment;?>
            </div>
            <div class="steps-box active">
                <?php echo $prevoStepsEnd;?>
            </div>
        </div>
        <?php
        echo "<div class='success'>".$rezultat."</div>";
        
 

        $sql = "INSERT INTO korisnici (pocetak, kraj, klasa, putnici, childseat, putnici1, putnici12, prtljag, rucniprtljag, specprtljag, sati, vrijemepolazak, distanca, trajanje, povratak, vrijemepovratak, cijena, ime, prezime, firma, email, telefon, zemlja, adresa, grad, postanski, buking, let, letboard, letputnik, lettelefon, placanje, platio, jezik, datum) VALUES ('".$pocetak."','".$kraj."','".$klasa."','".$putnici."','".$childseat."', 0, 0,'".$prtljag."', 0, 0,'".$sati."','".$vrijemepolazak."','".$distanca."','".$trajanje."','".$povratak."','".$vrijemepovratak."','".$cijena_ukupno."','".$ime."', '".$prezime."','".$firma."','".$email."','".$telefon."', '','','','','".$buking."','".$let."','".$letboard."','','','".$placanje."','Nein','".$jezik."', '".time()."')";

        if ($conn->query($sql) === TRUE) {
        
            echo '
            <div class="prikaz_all">
                <div class="colspan50 uspijesa_rezervacija"><a class="link_nova_voznja" href="'.$url_pocetna.'">'.$prevodMainPage.'</a></div>
            </div>';
            include 'uspijesna_rezervacija.php'; 

        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
            
        }

        //echo 'SLANJE MEJLA';
                
        include 'mejl_tijelo.php';        
    }

 

    ?>

	

	<?php

 
	if ( !empty($_POST["stripeToken"]) ) {
        //echo 'token'.$_POST["stripeToken"];

        $token  = $_POST['stripeToken']; 
        $name = $_POST['name']; 
        $email_payment = $_POST['email_payment']; 
         
        
        // Set API key 
        \Stripe\Stripe::setApiKey($key_sk); 
         
        // Add customer to stripe 
        try {  
            $customer = \Stripe\Customer::create(array( 
                'email' => $email_payment, 
                'name' => $name, 
                'source'  => $token 
            )); 
        }catch(Exception $e) {  
            $api_error = $e->getMessage();  
        } 
         
        if(empty($api_error) && $customer){  
             
            // Convert price to cents 
            //$itemPriceCents = ($itemPrice*100); 
             
            // Charge a credit or a debit card 
            try {  
                $charge = \Stripe\Charge::create(array( 
                    'customer' => $customer->id, 
                    'amount'   => $cijena_ukupno*100, 
                    'currency' => 'CHF', 
                    'description' => 'Transfer von: '.$pocetak 
                )); 
            }catch(Exception $e) {  
                $api_error = $e->getMessage();  
            } 
             
            if(empty($api_error) && $charge){ 
             
                // Retrieve charge details 
                $chargeJson = $charge->jsonSerialize(); 
             
                // Check whether the charge is successful 
                if($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1){ 
                     
                    $payment_status = $chargeJson['status'];    
                     
                    // If the order is successful 
                    if($payment_status == 'succeeded'){ 
                        $ordStatus = 'success'; 
                        $statusMsg = 'Your Payment has been Successful!'; 

                        ?>

                        <div class="steps izborauta">
                            <div class="steps-box active">
                                <?php echo $prevoStepsVehicles;?>
                            </div>
                             
                            <div class="steps-box active">
                                <?php echo $prevoStepsPassengers;?>
                            </div>
                            <div class="steps-box active">
                                <?php echo $prevoStepsPayment;?>
                            </div>
                            <div class="steps-box active">
                                <?php echo $prevoStepsEnd;?>
                            </div>
                        </div>

                        <?php

                        //echo $statusMsg; 

                        $rezultat .= $prevodRezultatSuccess;
                        echo "<div class='success' style=''>".$rezultat."</div>";
 
                  
                        //UPIS U BAZU
                        // $sql = "INSERT INTO korisnici (pocetak, kraj, klasa, putnici, sati, vrijemepolazak, distanca, trajanje, povratak, vrijemepovratak, cijena, ime, prezime, firma, email, telefon, zemlja, adresa, grad, postanski, buking, let, letboard,  placanje, platio, jezik, datum) VALUES ('".$pocetak."','".$kraj."','".$klasa."','".$putnici."','".$sati."','".$vrijemepolazak."','".$distanca."','".$trajanje."','".$povratak."','".$vrijemepovratak."','".$cijena."','".$ime."', '".$prezime."','".$firma."','".$email."','".$telefon."','".$zemlja."','".$adresa."','".$grad."','".$postanski."','".$buking."','".$let."','".$letboard."','".$placanje."','Nein','".$jezik."','".time()."')";

                        $sql = "INSERT INTO korisnici (pocetak, kraj, klasa, putnici, childseat, putnici1, putnici12, prtljag, rucniprtljag, specprtljag, sati, vrijemepolazak, distanca, trajanje, povratak, vrijemepovratak, cijena, ime, prezime, firma, email, telefon, zemlja, adresa, grad, postanski, buking, let, letboard, letputnik, lettelefon, placanje, platio, jezik, datum) VALUES ('".$pocetak."','".$kraj."','".$klasa."','".$putnici."','".$childseat."', 0, 0,'".$prtljag."', 0, 0,'".$sati."','".$vrijemepolazak."','".$distanca."','".$trajanje."','".$povratak."','".$vrijemepovratak."','".$cijena_ukupno."','".$ime."', '".$prezime."','".$firma."','".$email."','".$telefon."', '','','','','".$buking."','".$let."','".$letboard."','','','".$placanje."','Ja','".$jezik."', '".time()."')";

                        if ($conn->query($sql) === TRUE) {
                        
                            echo '
                            <div class="prikaz_all">
                                <div class="colspan50 uspijesa_rezervacija"><a class="link_nova_voznja" href="'.$url_pocetna.'">'.$prevodMainPage.'</a></div>
                            </div>';
                            include 'uspijesna_rezervacija.php'; 

                        } else {
                            echo "Error: " . $sql . "<br>" . $conn->error;
                            
                        }

                   
                        include 'mejl_tijelo.php';     
 


                    }else{ 
                        $statusMsg = "Your Payment has Failed!"; 
                        echo "<div class='decline' style=''>".$statusMsg."</div>";
                    } 
                }else{ 
                    $statusMsg = "Transaction has been failed!"; 
                    echo "<div class='decline' style=''>".$statusMsg."</div>";
                } 
            }else{ 
                $statusMsg = "Charge creation failed! $api_error";
                echo "<div class='decline' style=''>".$statusMsg."</div>";

            } 
        }else{  
            $statusMsg = "Invalid card details! $api_error"; 
            echo "<div class='decline' style=''>".$statusMsg."</div>"; 
        } 
         
 
    } 







    

    if($placanje == 'creditcard' && empty($_POST["stripeToken"]) ) { ?>

        <div class="steps izborauta">
            <div class="steps-box active">
                <?php echo $prevoStepsVehicles;?>
            </div>
             
            <div class="steps-box active">
                <?php echo $prevoStepsPassengers;?>
            </div>
            <div class="steps-box active">
                <?php echo $prevoStepsPayment;?>
            </div>
            <div class="steps-box">
                <?php echo $prevoStepsEnd;?>
            </div>
        </div>

        <form id="paymentFrm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
            <div class="prikaz_all ride">
                <div class="prikaz_lijevo colspan40 choosecar_left">
                    <?php include 'view_trenutnavoznja.php'; ?>                 
                </div>
                
                <div class="prikaz_desno colspan60 choosecar_right">
                    <div class="panel">
                       
                        <div class="panel-body">
                            <div class="podnaslov"><?php echo $prevodPaymentDetails; ?></div>
                            <!-- Display errors returned by createToken -->
                            <div id="paymentResponse"></div>
                            
                            <!-- Payment form -->
                            <form action="" method="POST" id="paymentFrm">
                                <div class="form-group">
                                    <label><?php echo $prevodCardName; ?></label>
                                    <input type="text" name="name" id="name" class="field" placeholder="Enter name" required="" autofocus="">
                                </div>
                                <div class="form-group">
                                    <label>E-mail</label>
                                    <input type="email" name="email_payment" id="email" class="field" placeholder="Enter email" required="">
                                </div>
                                <div class="form-group">
                                    <label><?php echo $prevodCardNumber; ?> </label>
                                    <div id="card_number" class="field"></div>
                                </div>
                                <div class="row">
                                    <div class="left">
                                        <div class="form-group">
                                            <label><?php echo $prevodCardExpiryDate; ?></label>
                                            <div id="card_expiry" class="field"></div>
                                        </div>
                                    </div>
                                    <div class="right">
                                        <div class="form-group">
                                            <label><?php echo $prevodCardCvc; ?></label>
                                            <div id="card_cvc" class="field"></div>
                                        </div>
                                    </div>
                                </div>

                                 <?php include 'inputi_trenutnavoznja.php'; ?>

                                <input type="text" name="klasa" value="<?php echo $klasa;?>" style="display:none;">
                                <input type="text" name="cijena" value="<?php echo $cijena;?>" style="display:none;">
                                <input type="text" name="ime" value="<?php echo $ime;?>" style="display:none;">
                                <input type="text" name="prezime" value="<?php echo $prezime;?>" style="display:none;">   
                                <input type="text" name="firma" value="<?php echo $firma;?>" style="display:none;">  
                                <input type="text" name="email" value="<?php echo $email;?>" style="display:none;">  
                                <input type="text" name="telefon" value="<?php echo $telefon;?>" style="display:none;">  
                                <input type="text" name="let" value="<?php echo $let;?>"style=" display:none;">  
                                <input type="text" name="letboard" value="<?php echo $letboard;?>" style="display:none;">  
                                <input type="text" name="buking" value="<?php echo $buking;?>" style="display:none;"> 
                                <input type="text" name="putnici" value="<?php echo $putnici;?>" style="display:none;">  
                                <input type="text" name="prtljag" value="<?php echo $prtljag;?>" style="display:none;">
                                <input type="text" name="childseat" value="<?php echo $childseat;?>" style="display:none;"> 
                                <input type="text" name="childseat_select" value="<?php echo $childseat_select;?>" style="display:none;">

                                <input type="text" name="placanje" value="<?php echo $placanje;?>"style="display:none;">

                                <div class="prikaz_all"> <?php include 'uslovi.php'; ?> </div>

                                <div class="submit_button">
                                    <input  type="submit" name="submit_payment" value="<?php echo $prevodPlaceOrder;?>" /> 
                                </div>
                                <!-- <button type="submit" class="btn btn-success" id="payBtn">Submit Payment</button> -->
                            </form>
                        </div>
                    </div>


                    <script src="https://js.stripe.com/v3/"></script>

                    <script type="text/javascript">
                        // Create an instance of the Stripe object
                        // Set your publishable API key
                        var stripe = Stripe('<?php echo $key_pk; ?>');

                        // Create an instance of elements
                        var elements = stripe.elements();

                        var style = {
                            base: {
                                fontWeight: 400,
                                fontFamily: 'Roboto, Open Sans, Segoe UI, sans-serif',
                                fontSize: '16px',
                                lineHeight: '24px',
                                padding:'10px',
                                borderRadius:'10px',
                                color: '#111',
                                backgroundColor: '#fff',
                                '::placeholder': {
                                    color: '#888',
                                },
                            },
                            invalid: {
                                color: '#eb1c26',
                            }
                        };

                        var cardElement = elements.create('cardNumber', {
                            style: style
                        });
                        cardElement.mount('#card_number');

                        var exp = elements.create('cardExpiry', {
                            'style': style
                        });
                        exp.mount('#card_expiry');

                        var cvc = elements.create('cardCvc', {
                            'style': style
                        });
                        cvc.mount('#card_cvc');

                        // Validate input of the card elements
                        var resultContainer = document.getElementById('paymentResponse');
                        cardElement.addEventListener('change', function(event) {
                            if (event.error) {
                                resultContainer.innerHTML = '<div>'+event.error.message+'</div>';
                            } else {
                                resultContainer.innerHTML = '';
                            }
                        });

                        // Get payment form element
                        var form = document.getElementById('paymentFrm');
         

                        // Create a token when the form is submitted.
                        form.addEventListener('submit', function(e) {


                            e.preventDefault();
 
                            createToken();
                           
                        });

                        // Create single-use token to charge the user
                        function createToken() {
                            stripe.createToken(cardElement).then(function(result) {
                                if (result.error) {
                                    // Inform the user if there was an error
                                    resultContainer.innerHTML = '<p>'+result.error.message+'</p>';
                                } else {
                                    // Send the token to your server
                                    stripeTokenHandler(result.token);
                                }
                            });
                        }

                        // Callback to handle the response from stripe
                        function stripeTokenHandler(token) {
                            // Insert the token ID into the form so it gets submitted to the server
                            var hiddenInput = document.createElement('input');
                            hiddenInput.setAttribute('type', 'hidden');
                            hiddenInput.setAttribute('name', 'stripeToken');
                            hiddenInput.setAttribute('value', token.id);
                            form.appendChild(hiddenInput);
                            
                            // Submit the form
                            form.submit();
                        }
                    </script>

 
                   

 
                </div>
 
            </div>
        </form>



    <?php
    }

 
	if ($placanje != 'creditcard' ) {
        if(!isset($_POST['submit_payment'])){ 
            if(isset($_POST['ime'])){
        ?>
                <div class="steps izborauta">
                    <div class="steps-box active">
                        <?php echo $prevoStepsVehicles;?>
                    </div>
                     
                    <div class="steps-box active">
                        <?php echo $prevoStepsPassengers;?>
                    </div>
                    <div class="steps-box active">
                        <?php echo $prevoStepsPayment;?>
                    </div>
                    <div class="steps-box">
                        <?php echo $prevoStepsEnd;?>
                    </div>
                </div>
    	       
            	<form  method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
            		<div class="prikaz_all ride">
            			<div class="prikaz_lijevo colspan40 choosecar_left">
            				<?php include 'view_trenutnavoznja.php'; ?>					
            			</div>
            			
            			<div class="prikaz_desno colspan60 choosecar_right">

            				<div class="placanje">  <?php include 'placanje.php'; ?> </div>

            			 	<div class="prikaz_all"> <?php include 'uslovi.php'; ?> </div>


            				<?php include 'inputi_trenutnavoznja.php'; ?>

            				<input type="text" name="klasa" value="<?php echo $klasa;?>" style="display:none;">
                            <input type="text" name="cijena" value="<?php echo $cijena;?>" style="display:none;">
                            <input type="text" name="ime" value="<?php echo $ime;?>" style="display:none;">
                            <input type="text" name="prezime" value="<?php echo $prezime;?>" style="display:none;">   
                            <input type="text" name="firma" value="<?php echo $firma;?>" style="display:none;">  
                            <input type="text" name="email" value="<?php echo $email;?>" style="display:none;">  
                            <input type="text" name="telefon" value="<?php echo $telefon;?>" style="display:none;">  
                            <input type="text" name="let" value="<?php echo $let;?>" style="display:none;">  
                            <input type="text" name="letboard" value="<?php echo $letboard;?>" style="display:none;">  
                            <input type="text" name="buking" value="<?php echo $buking;?>" style="display:none;"> 
                            <input type="text" name="putnici" value="<?php echo $putnici;?>" style="display:none;">  
                            <input type="text" name="prtljag" value="<?php echo $prtljag;?>" style="display:none;">
                            <input type="text" name="childseat" value="<?php echo $childseat;?>" style="display:none;"> 
                            <input type="text" name="childseat_select" value="<?php echo $childseat_select;?>" style="display:none;"> 


                            <div class="submit_button">
                                <input  type="submit" name="submit_payment" value="<?php echo $prevodPlaceOrder;?>" />
                            </div>
             
            			</div>

            			

            		</div>
            	</form>
 
		
    <?php
            }else{
                echo '
                <div class="prikaz_all">
                    <div class="colspan50 uspijesa_rezervacija"><a class="link_nova_voznja" href="'.$url_pocetna.'">STARTSEITE</a></div>
                </div>';
            }
           
        }
    } 
    ?>
	

</div>




<?php $conn->close(); ?>

<script type="text/javascript"> 
$("document").ready(function(){
    if ( window.history.replaceState ) {
      window.history.replaceState( null, null, window.location.href );
    }
});
</script>

<?php  include 'footer.php'; ?>

