<?php
//error_reporting(E_ALL); 
//ini_set('display_errors', 1);
session_start();
ob_start();
include('functions/userfunctions.php');
include('config/dbcon.php');
include('authenticate.php');
include('includes/header.php');



// Retrieve POST data
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$phone = mysqli_real_escape_string($con, $_POST['phone']);
$pincode = mysqli_real_escape_string($con, $_POST['pincode']);
$address = mysqli_real_escape_string($con, $_POST['address']);
$payment_mode = mysqli_real_escape_string($con, $_POST['payment_mode']);
$totalPrice = mysqli_real_escape_string($con, $_POST['totalprice']);
$payment_id = mysqli_real_escape_string($con, $_POST['payment_id']);
$backupuser_id = mysqli_real_escape_string($con, $_POST['suid']);

// Generate unique tracking number
$tracking_no = "EX" . rand(1111, 9999) . substr($phone, 2);
$user_id = $_SESSION['auth_user']['user_id'];
//$userIP = $_SERVER['REMOTE_ADDR'];
// Generate hash data for payment
$orderId = $tracking_no;

//$terminalId = 30691297; // demo
$terminalId = 10238638; // Example terminal ID (must be integer)


$currencyCode = 826; // Example currency code (e.g., 949 for Turkish Lira)
$successUrl = "https://order.exelsiorhotels.com/successfulpayment.php";
$errorUrl = "https://order.exelsiorhotels.com/paymentfailed.php";
$type = "sales";
$installmentCount = "";
$storeKey = "69736d65744578656c73696f72343869736d655434383438";
                

setcookie('name', $name, time() + (86400 * 30), "/"); // Cookie expires in 30 days
setcookie('email', $email, time() + (86400 * 30), "/");
setcookie('phone', $phone, time() + (86400 * 30), "/");
setcookie('pincode', $pincode, time() + (86400 * 30), "/");
setcookie('address', $address, time() + (86400 * 30), "/");
setcookie('payment_mode', $payment_mode, time() + (86400 * 30), "/");
setcookie('totalPrice', $totalPrice, time() + (86400 * 30), "/");
setcookie('payment_id', $payment_id, time() + (86400 * 30), "/");
setcookie('tracking_no', $tracking_no, time() + (86400 * 30), "/");
setcookie('user_id', $user_id, time() + (86400 * 30), "/");

// Generate hash data using the function
$shaData2 = GenerateSecurityData($terminalId);
$hashData2 = $terminalId . $orderId . $amount . $currencyCode . $successUrl . $errorUrl . $type . $installmentCount . $storeKey . $shaData2;


// Initialize cURL session
$curl = curl_init();
$url = 'https://www.tcmb.gov.tr/kurlar/today.xml';

// Set cURL options
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// Execute cURL session
$response = curl_exec($curl);

// Check for cURL errors
if (curl_errno($curl)) {
    echo 'cURL Error: ' . curl_error($curl);
} else {
    // Parse XML data from response
    $kur = simplexml_load_string($response);

    // Check if XML parsing was successful
    if ($kur !== false) {
        // Process currency data
        foreach ($kur->Currency as $cur) {
            if ($cur["Kod"] == "USD") {
                $usdAlis = $cur->ForexBuying;
                $usdSatis = $cur->ForexSelling;
            }

            if ($cur["Kod"] == "EUR") {
                $eurAlis = $cur->ForexBuying;
                $eurSatis = $cur->ForexSelling;
            }
            if ($cur["Kod"] == "GBP") {
                $gbpAlis = $cur->ForexBuying;
                $gbpSatis = $cur->ForexSelling;
            }
        }

    } else {
        echo "Failed to parse XML data";
    }
}

// Close cURL session
curl_close($curl);
$amount2 = $totalPrice / $gbpAlis;

$amount2 = round($amount2, 2);
$amount2 = number_format($amount2, 2);

$amountString = (string) $amount2;
list($integerPart, $fractionalPart) = explode('.', $amountString);

$amount = $integerPart . $fractionalPart;
$hashData = GenerateHashData($terminalId, $orderId, $amount, $currencyCode, $successUrl, $errorUrl, $type, $installmentCount, $storeKey, $shaData2);
// Check if required fields are empty
if ($name == "" || $email == "" || $phone == "" || $pincode == "" || $address == "") {
    $_SESSION['message'] = "All fields are required";
    header('Location: ../checkout.php');
    exit(0);
}

?>
<div class="container py-5">
    <div class="card">
        <div class="card-body shadow">
            <form method="post" action="https://sanalposprov.garanti.com.tr/servlet/gt3dengine">
                <div class="row">
                    <div class="col-12">
                        <h5>Card Information</h5>
                        <hr>
                        <div class="row">
                            <!-- Hidden input fields for payment form -->
                            <input type="hidden" name="mode" value="PROD" />
                            <input type="hidden" name="apiversion" value="512" />
                            <input type="hidden" name="secure3dsecuritylevel" value="3D_PAY" />
                            <input type="hidden" name="terminalprovuserid" value="PROVAUT" />
                            <input type="hidden" name="terminaluserid" value="SEMIH" />
                            <input type="hidden" name="terminalmerchantid" value="1917966" />
                            <input type="hidden" name="terminalid" value="<?php echo $terminalId;?>" />
                            <input type="hidden" name="orderid" value="<?php echo $tracking_no; ?>" />
                            <input type="hidden" name="successurl" value="<?php echo $successUrl; ?>" />
                            <input type="hidden" name="errorurl" value="<?php echo $errorUrl; ?>" />
                            <input type="hidden" name="customeremailaddress" value="<?php echo $email;?>" />
                            <input type="hidden" name="customeripaddress" value="192.168.0.1" />
                            <input type="hidden" name="companyname" value="Exelsior Hotels" />
                            <input type="hidden" name="lang" value="tr" />
                            <input type="hidden" name="txntimestamp" value="<?php echo date("Y-m-d H:i:s"); ?>" />
                            <input type="hidden" name="refreshtime" value="1" />
                            <input type="hidden" name="secure3dhash" value="<?php echo $hashData; ?>" />
                            <input type="hidden" name="txnamount" value="<?php echo $amount; ?>" />
                            <input type="hidden" name="txntype" value="sales" />
                            <input type="hidden" name="txncurrencycode" value="<?php echo $currencyCode;?>" />
                            <input type="hidden" name="txninstallmentcount" value="" />

                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Name</label>
                                <input type="text" name="cardholdername" required placeholder="Name on card" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Card Number</label>
                                <input type="number" name="cardnumber" required placeholder="Card number" class="form-control">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Month</label>
                                <input type="number" name="cardexpiredatemonth" required placeholder="Month" class="form-control">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Year</label>
                                <input type="number" name="cardexpiredateyear" required placeholder="Year" class="form-control">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">CVV</label>
                                <input type="number" name="cardcvv2" required placeholder="CVV" class="form-control">
                            </div>
                                    <?php
                                     $cartItems = getCartItems();
                                    $insert_query = "INSERT INTO `orders`(tracking_no, user_id, name, email, phone, address, pincode, total_price, payment_mode, payment_id) VALUES ('$tracking_no', '$user_id', '$name', '$email', '$phone', '$address', '$pincode', '$totalPrice', '$payment_mode', '$payment_id' )";

                                    $insert_query_run = mysqli_query($con, $insert_query);



                                    if($insert_query_run)

                                    {

                                        
                                        $order_id = mysqli_insert_id($con);

                                        foreach($cartItems as $citem)

                                        {

                                            

                                            $prod_id = $citem['prod_id'];

                                            $prod_qty = $citem['prod_qty'];

                                            $price = $citem['selling_price'];

                                        $insert_items_query = "INSERT INTO order_items (order_id, prod_id, qty, price) VALUES ('$order_id', '$prod_id', '$prod_qty', '$price')";

                                        $insert_items_query_run = mysqli_query($con, $insert_items_query);
                                        }



                                        $deleteCartQuery = "DELETE FROM carts WHERE user_id = '$user_id'";

                                        $deleteCartQueryRun = mysqli_query($con, $deleteCartQuery);
                                    }
                                         ?>
                            <div class="col-12">
                                <button type="submit" name="placeOrderBtn23" class="btn btn-primary mt-3 w-100">Proceed to Payment</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<?php ob_end_flush();?>

<?php include('includes/footer.php'); ?>
