<?php

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;
}

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



if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $barcode = $_POST['barcode'];
    $product_name = $_POST['product_name'];
    echo $barcode;

    if ($barcode != '' || $product_name != '') {

        $bankingData = $_POST['bankingData'];
        $typeData = $_POST['typeData'];
        $qtyData = $_POST['qtyData'];

        if ($barcode != '') {
            $sql = "SELECT * FROM " . $product . " WHERE (barcode='$barcode' OR barcode_1='$barcode') AND delete_d='0'";
        } else {
            $sql = "SELECT * FROM " . $product . " WHERE product_name='$product_name' AND delete_d='0'";
        }

        $result = $connection->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {

                $tra_id_data = new DateTime();
                $rn = rand(0, 1000);

                if ($barcode == '') {
                    $barcode = $row['barcode']; // If barcode is empty, fill it from DB
                }
                $product_name = $row['product_name'];

                $package_price = $row["round_package_price"];
                $unit_price = $row["round_unit_price"];
                $pieces_price = $row["round_pieces_price"];
                $package_exist = $row['package_exist'];
                $unit_exist = $row['unit_exist'];
                $pieces_exist = $row['pieces_exist'];
                $pieces_exist = $row['pieces_exist'];
                $type = $row['type'];
                $type = $row['type'];
                $customer = '-';

                $voucher = 'လက်လီ';
                $buy_type = 'လက်ငင်း';
                $tra_id = $tra_id_data->format('YmdHis') . '' . $rn;
                $today_date = date('Y-m-d');
                $exp_debt = date('Y-m-d');
                $total = $pieces_price;
                $discount = '0';
                $rate = '1';


                $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_lk'];
                        $user_name = $row['user_name'];


                        $is_stock_sufficient = true; // Flag to check stock availability

                        // Check stock based on type
                        if ($typeData == "ဖာ") {
                            if (
                                $package_exist < 1 || $package_exist < $qtyData
                            ) {
                                echo "<script>alert('လက်ကျန်ဖာ မလုံလောက်ပါ');</script>";
                            
                                $is_stock_sufficient = false;
                            } else {
                                $total_f = $package_price * $qtyData;
                                $price = $package_price;
                            }
                        } else if ($typeData == "ကဒ်") {
                            if (
                                $unit_exist < 1 || $unit_exist < $qtyData
                            ) {
                                echo "<script>alert('လက်ကျန်ကဒ် မလုံလောက်ပါ');</script>";
                              
                                $is_stock_sufficient = false;
                            } else {
                                $total_f = $unit_price * $qtyData;
                                $price = $unit_price;
                            }
                        } else if ($typeData == "ဗူး/ခု") {
                            if ($pieces_exist < 1 || $pieces_exist < $qtyData) {
                                echo "<script>alert('လက်ကျန်ဗူး မလုံလောက်ပါ');</script>";
      
                                $is_stock_sufficient = false;
                            } else {
                                $total_f = $pieces_price * $qtyData;
                                $price = $pieces_price;
                            }
                        }

                        // Proceed only if stock is sufficient
                        if ($is_stock_sufficient) {
                            // Insert data into user table
                            $insert_sql_user = "INSERT INTO " . $user_id . "(date, barcode, product_name, price, qty, total, tra_id, customer, type, exp_debt, voucher, discount, buy_type, seller, banking, rate)
                                        VALUES ('$today_date', '$barcode', '$product_name', '$price', '$qtyData', '$total_f', '$tra_id', '$customer', '$typeData', '$exp_debt', '$voucher', '$discount', '$buy_type', '$user_name', '$bankingData', '$rate')";
                            mysqli_query($connection, $insert_sql_user);

                            // Insert data into sell data table
                            $insert_sql_sell = "INSERT INTO " . $sell_data . "(date, barcode, product_name,item_type, price, qty, total, tra_id, customer, type, exp_debt, voucher, discount, buy_type, seller, banking, rate)
                                        VALUES ('$today_date', '$barcode', '$product_name','$type', '$price', '$qtyData', '$total_f', '$tra_id', '$customer', '$typeData', '$exp_debt', '$voucher', '$discount', '$buy_type', '$user_name', '$bankingData', '$rate')";
                            mysqli_query($connection, $insert_sql_sell);

                            // Update product exist
                            $query = "UPDATE $product p
                            LEFT JOIN (SELECT product_name, 
                                                SUM(CASE WHEN type='ဗူး/ခု' THEN qty ELSE 0 END) AS pieces_sell,
                                                SUM(CASE WHEN type='ကဒ်' THEN qty ELSE 0 END) AS unit_sell,
                                                SUM(CASE WHEN type='ဖာ' THEN qty ELSE 0 END) AS package_sell
                                        FROM $sell_data 
                                        WHERE product_name='$product_name'
                                        GROUP BY product_name) s 
                            ON p.product_name = s.product_name
                            SET p.pieces_sell = COALESCE(s.pieces_sell, 0),
                                p.unit_sell = COALESCE(s.unit_sell, 0),
                                p.package_sell = COALESCE(s.package_sell, 0)";
                            $connection->query($query);

                            // Final update query
                            $final_update_query = "UPDATE $product SET 
                                        package_exist = (package_remain+package_trans) - (package_sell + package_damage + unit_change),
                                        unit_exist = (unit_remain+unit_trans) - (unit_sell + unit_damage) + (unit_change * unit) - pieces_change,
                                        pieces_exist = (pieces_remain+pieces_trans) - (pieces_sell + pieces_damage) + (pieces_change * pieces)
                                        WHERE product_name='$product_name'";
                            if (!$connection->query($final_update_query)) {
                                $connection->rollback();
                                die("ERROR: Query failed. " . $connection->error);
                            }

                            // echo "<script>window.location.href = 'sell_lk.php';</script>";
                        }
                    }
                }
            }
        }
    }
} else {
    echo "<span style='color: red;'>Invalid request method.</span>";
}

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

    return $randomString . $timestamp;
}
?>


