<?php
include "database/database.php"; // Include your database connection
include "database/data.php"; // Include your database connection

session_start();

if (isset($_SESSION['browser_id'])) {
    $browserId = $_SESSION['browser_id'];
} else {
    // Generate a new browser ID
    $browserId = generateUniqueBrowserId();

    // Store the browser ID in the session for future use
    $_SESSION['browser_id'] = $browserId;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Fetch and sanitize inputs


    $b_id = $browserId;

    $sql = "SELECT * FROM " . $user_database . " WHERE browser_id='$b_id'";
    $result = $connection->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {

            $user_id = $row['user_name_LL'];
            $user_name = $row['user_name'];
            $voucher = $_POST['voucher'];
            $payment_data = $_POST['bankingData'];

            // $rate = $_POST['rate'];
            $sql = "SELECT currency FROM " . $banking . " WHERE type='$payment_data'";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $currency = $row['currency'];

                    $sql = "SELECT * FROM " .$rate . "";
                    $result = $connection->query($sql);
                    if ($result && $result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            $baht = $row['baht'];
                            $yuan = $row['yuan'];
                            $dollar = $row['dollar'];
                            $kyat = $row['kyat'];
                            $profit = $row['profit'];

                            if ($currency == 'kyat') {

                                $rate = '1';
                            } else if ($currency == 'baht') {

                                $rate = $baht;
                            } else if ($currency == 'yuan') {

                                $rate = $yuan;
                            } else if ($currency_buy == 'dollar') {

                                $rate = $dollar;
                            }
                        }
                    }
                }
            } else {
                // Default rate if no matching record in the first query
                $rate = 1;
            }




            //update user sell database
            $query = "UPDATE " . $user_id . " set voucher='$voucher',banking='$payment_data',rate='$rate' where seller='$user_name'";
            if (!$connection->query($query)) {
                die("ERROR: Query failed. " . $connection->error);
            }

            


            //convert into original price
            $sql = "SELECT u.*, p.round_package_price, p.round_unit_price, p.round_pieces_price 
        FROM $user_1_ll u
        JOIN $product p ON u.product_name = p.product_name
        WHERE u.seller = '$user_name'";
$result = $connection->query($sql);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $price = match ($row['type']) {
            'ဖာ' => $row['round_package_price'],
            'ကဒ်' => $row['round_unit_price'],
            'ဗူး/ခု' => $row['round_pieces_price'],
            default => 0
        };

        $total = $price * $row['qty'];

        $query1 = "UPDATE $user_1_ll SET discount='0',price='$price', total='$total' WHERE tra_id='{$row['tra_id']}'";
        if (!$connection->query($query1)) {
            die("ERROR: Query failed. " . $connection->error);
        }

        $query2 = "UPDATE $sell_data SET discount='0',price='$price', total='$total' WHERE tra_id='{$row['tra_id']}'";
        if (!$connection->query($query2)) {
            die("ERROR: Query failed. " . $connection->error);
        }
    }
} else {
    die("ERROR: Query failed. SQL: $sql - Error: " . $connection->error);
}

$query = "UPDATE " . $user_id . " set price=round(price/rate),total=round(qty*price)-round(qty*discount) where seller='$user_name'";
            if (!$connection->query($query)) {
                die("ERROR: Query failed. " . $connection->error);
            }


            //update sell database
            $sql = "SELECT tra_id,voucher FROM " . $user_id . "";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $tra_id = $row['tra_id'];
                    $voucher = $row['voucher'];

                    $query = "UPDATE " . $sell_data . " set voucher='$voucher',banking='$payment_data',rate='$rate' where tra_id='$tra_id'";
                    if (!$connection->query($query)) {
                        die("ERROR: Query failed. " . $connection->error);
                    }

                    $query = "UPDATE " . $sell_data . " set price=round(price/rate),total=round(qty*price)-round(qty*discount) where tra_id='$tra_id'";
                    if (!$connection->query($query)) {
                        die("ERROR: Query failed. " . $connection->error);
                    }
                }
            }
        }
    }


} else {
    echo "<span style='color: red;'>Invalid request method.</span>";
}

function generateUniqueBrowserId()
{
    $randomString = bin2hex(random_bytes(16));
    $timestamp = time();

    return $randomString . $timestamp;
}
?>
