<?php

session_start();

include('config/dbcon.php');



function getAllActive($table)

{

    global $con;

    $query = "SELECT * FROM $table WHERE status='0' ";

    return $query_run = mysqli_query($con, $query);

}

function logPaymentResponse($data, $trackingNo = null) {
    $logEntry = [
        'timestamp' => date('Y-m-d H:i:s'),
        'tracking_no' => $trackingNo,
        'data' => $data
    ];
    
    $logMessage = json_encode($logEntry, JSON_PRETTY_PRINT);
    
    // Ensure directory exists
    if (!file_exists('payment_logs')) {
        mkdir('payment_logs', 0755, true);
    }
    
    // Log to daily file
    file_put_contents(
        'payment_logs/payment_response_'.date('Y-m-d').'.log', 
        $logMessage.PHP_EOL, 
        FILE_APPEND
    );
    
    // Optional: Also log to database if needed
    /*
    global $con;
    $escapedData = mysqli_real_escape_string($con, json_encode($data));
    $query = "INSERT INTO payment_logs (tracking_no, response_data) 
              VALUES ('$trackingNo', '$escapedData')";
    mysqli_query($con, $query);
    */
}

function redirect($url,$message)

{

    $_SESSION['message'] = $message;
    return $url . 'test1';

    header('Location: '.$url);

    exit();

}

function getProdByCategory($category_id)

{

    global $con;

    $query = "SELECT * FROM products WHERE category_id='$category_id' AND status='0' ";

    return $query_run = mysqli_query($con, $query);

}

function getIDActive($table, $id)

{

    global $con;

    $query = "SELECT * FROM $table WHERE id='$id' AND status='0' ";

    return $query_run = mysqli_query($con, $query);

}

function getSlugActive($table, $slug)

{

    global $con;

    $query = "SELECT * FROM $table WHERE slug='$slug' AND status='0' LIMIT 1";

    return $query_run = mysqli_query($con, $query);

}



function getCartItems()

{

    global $con;

    $userId = $_SESSION['auth_user']['user_id'];

    $query = "SELECT c.id as cid, c.prod_id, c.prod_qty, p.id as pid, p.name, p.image, p.selling_price  FROM carts c, products p WHERE c.prod_id=p.id AND c.user_id='$userId' ORDER BY c.id DESC";

    return $query_run = mysqli_query($con, $query);

}

function getAllProd($table)

{

    global $con;

    $query = "SELECT * FROM $table";

    return $query_run = mysqli_query($con, $query);

}

function getOrders()

{

    global $con;

    $userId = $_SESSION['auth_user']['user_id'];

    $query = "SELECT * FROM orders WHERE user_id='$userId' ORDER BY id DESC";

    return $query_run = mysqli_query($con, $query);

}



function checkTrackingNoValid($trackingNo)

{

    global $con;

    $userId = $_SESSION['auth_user']['user_id'];

    $query = "SELECT * FROM orders WHERE tracking_no='$trackingNo' AND user_id='$userId' ";

    return $query_run = mysqli_query($con, $query);

}

function getAllProdTrend($table)

{

    global $con;

    $query = "SELECT * FROM $table where trending='1' ";

    return $query_run = mysqli_query($con, $query);

}

function getCategoryName($category_id) {

    global $con;

    // Assuming you have a database connection available

    // Replace 'your_table_name' with the actual name of your categories table

    $query = "SELECT name FROM categories WHERE id = $category_id";

    

    // Execute the query to fetch category name

    $result = mysqli_query($con, $query);

    

    if ($result) {

        $row = mysqli_fetch_assoc($result);

        return $row['name'];

    } else {

        return "Category Not Found";

    }

}

function GenerateSecurityData($terminalId)
{
    $password = "Exelsiorhotel22."; // Şifre
    $provisionPassword = $password . '0'; // Ek karakter ekleme


    // SHA-1 hash oluşturma
    $shaData = sha1($provisionPassword . $terminalId);
    
    // Hash değerini büyük harflerle döndürme
    return strtoupper($shaData);
}


function GenerateHashData($terminalId, $orderId, $amount, $currencyCode, $successUrl, $errorUrl, $type, $installmentCount, $storeKey, $hashedPassword)
{
    $storeKey = "69736d65744578656c73696f72343869736d655434383438"; // Mağaza anahtarı
    $hashedPassword = GenerateSecurityData($terminalId);
    
    // Append '00' to the end of the amount (assuming $amount is a numeric value)
    
    
    // Concatenate parameters and store key, then hash using SHA-512
    $hashData = strtoupper(hash('sha512', 
        $terminalId .
        $orderId .
        $amount .
        $currencyCode .
        $successUrl .
        $errorUrl .
        $type .
        $installmentCount .
        $storeKey .
        $hashedPassword
    ));

    return $hashData;
}

function enSifre($password) {
    $key = '122748';
    $cipher = "aes-256-cbc";
    $iv_length = openssl_cipher_iv_length($cipher);
    $fixed_iv = "245FCFVC245FCFVC"; // Use a fixed IV (16 bytes for AES-256-CBC)

    // Use the fixed IV in encryption
    $encrypted = openssl_encrypt($password, $cipher, $key, OPENSSL_RAW_DATA, $fixed_iv);
    if ($encrypted === false) {
        die('Encryption failed');
    }
    return base64_encode($fixed_iv . $encrypted);
}

function deSifre($encryptedPassword) {
    $key = '122748';
    $cipher = "aes-256-cbc";
    $iv_length = openssl_cipher_iv_length($cipher);
    $fixed_iv = "245FCFVC245FCFVC"; // Use the same fixed IV used for encryption

    // Decode the base64-encoded encrypted password
    $decoded = base64_decode($encryptedPassword);
    if ($decoded === false) {
        die('Failed to base64 decode the encrypted password');
    }

    // Check if the decoded data has the correct length
    if (strlen($decoded) < $iv_length) {
        die('Invalid encrypted data format');
    }

    // Extract the IV and encrypted data
    $iv = substr($decoded, 0, $iv_length);
    $encrypted = substr($decoded, $iv_length);

    // Attempt to decrypt the encrypted data using the extracted IV
    $decrypted = openssl_decrypt($encrypted, $cipher, $key, OPENSSL_RAW_DATA, $iv);
    if ($decrypted === false) {
        die('Decryption failed');
    }
    return $decrypted;
}


?>