<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ပစ္စည်းအသစ်ထည့်ရန်</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css">
    <script src="https://kit.fontawesome.com/ae360af17e.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="css/style.css">
    <link rel="icon" href="image/logo.png" type="image/png">
</head>
<style>
    video {
        width: 100%;
        height: 200px;

        object-fit: cover;
        /* Ensures the video fills the container */
        display: block;
    }

    .product-image {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        /* Makes the image circular */
        object-fit: cover;
        /* Ensures the image fits inside the circle */
    }
</style>

<script>
    function formatNumber(input) {
        // Remove all non-digit characters
        let value = input.value.replace(/\D/g, '');

        // Format the number with commas
        let formattedValue = new Intl.NumberFormat().format(value);

        // Update the input value
        input.value = formattedValue;
    }

    document.addEventListener('DOMContentLoaded', function() {
        const formattedInput = document.getElementById('formatted');
        formattedInput.addEventListener('input', function() {
            formatNumber(this);
        });
    });
</script>


<?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 "database/data.php";
// include "cal_pro_remain.php";
include "login_check.php";


if (isset($_POST['add'])) {
    $barcode = $_POST['barcode'];
    $barcode_1 = $_POST['barcode_1'];
    $barcode_2 = $_POST['barcode_2'];
    $product_name = $_POST['product_name'];
    $note = $_POST['note'];
    $trans = $_POST['trans'];

    $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'];


            if ($barcode == '' && $product_name == '') {
                // echo "<script>alert('Need Barcode')</script>";
            } else {

                $product_type = $_POST['product_type'];


                $unit = !empty($_POST['unit']) ? $_POST['unit'] : 1;
                $pieces = !empty($_POST['pieces']) ? $_POST['pieces'] : 1;

                $buy = $_POST['buy'];


                $currency_rate = '0';
                $currency_buy = $_POST['currency_buy'];
                $profit = '0';

                function roundUpToNearestHundred($number)
                {
                    return ceil($number / 1) * 1;
                }

                if ($currency_buy == 'kyat') {
                    $rate = '1';
                } else if ($currency_buy == 'baht') {
                    $rate = $baht;
                } else if ($currency_buy == 'yuan') {

                    $rate = $yuan;
                } else if ($currency_buy == 'dollar') {
                    $rate = $dollar;
                }
                $package_price = ($profit + $buy + $trans);

                //Image



                // Check if a file was uploaded
                $productName = trim($_POST['product_name']); // Get the product name

                // Check if a file was uploaded
                if (isset($_FILES["image"]) && $_FILES["image"]["error"] === UPLOAD_ERR_OK) {
                    // Define the target directory
                    $targetDir = "uploads/";

                    // Ensure the directory exists
                    if (!is_dir($targetDir)) {
                        mkdir($targetDir, 0777, true); // Create the directory if it doesn't exist
                    }

                    // Get the file extension
                    $fileType = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));

                    // Construct the target file path with the product name
                    $targetFilePath = $targetDir . $productName . '.' . $fileType;

                    // Validate allowed file types
                    $allowedTypes = array("jpg", "jpeg", "png", "gif");
                    if (in_array($fileType, $allowedTypes)) {
                        // Check file size and reduce if necessary
                        $maxFileSize = 2 * 1024 * 1024; // 2MB
                        $desiredFileSize = 100 * 1024; // 100KB

                        // Temporary file path
                        $tempPath = $_FILES["image"]["tmp_name"];

                        // Reduce image size
                        if ($_FILES["image"]["size"] > $maxFileSize) {
                            // Load the image
                            switch ($fileType) {
                                case 'jpg':
                                case 'jpeg':
                                    $image = imagecreatefromjpeg($tempPath);
                                    break;
                                case 'png':
                                    $image = imagecreatefrompng($tempPath);
                                    break;
                                case 'gif':
                                    $image = imagecreatefromgif($tempPath);
                                    break;
                                default:
                                    $image = null;
                                    break;
                            }

                            if ($image) {
                                // Resize the image
                                $originalWidth = imagesx($image);
                                $originalHeight = imagesy($image);
                                $newWidth = 800; // Set a new width (you can adjust)
                                $newHeight = ($originalHeight / $originalWidth) * $newWidth;

                                $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
                                imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

                                // Save the resized image with reduced quality
                                if ($fileType === 'jpg' || $fileType === 'jpeg') {
                                    imagejpeg($resizedImage, $targetFilePath, 75); // 75% quality
                                } elseif ($fileType === 'png') {
                                    imagepng($resizedImage, $targetFilePath, 6); // Compression level 6
                                } elseif ($fileType === 'gif') {
                                    imagegif($resizedImage, $targetFilePath);
                                }

                                // Free memory
                                imagedestroy($image);
                                imagedestroy($resizedImage);

                                // echo "The image for <strong>" . htmlspecialchars($productName) . "</strong> has been uploaded and resized successfully.";
                                // echo "<br><a href='$targetFilePath'>View Uploaded image</a>";
                            } else {
                                // echo "Unsupported image type.";
                            }
                        } else {
                            // Move the file to the target directory if size is already acceptable
                            if (move_uploaded_file($tempPath, $targetFilePath)) {
                                // echo "The image for <strong>" . htmlspecialchars($productName) . "</strong> has been uploaded successfully.";
                                // echo "<br><a href='$targetFilePath'>View Uploaded image</a>";
                            } else {
                                // echo "Sorry, there was an error uploading your file.";
                            }
                        }
                    } else {
                        // echo "Invalid file format. Only JPG, JPEG, PNG, and GIF files are allowed.";
                    }
                } else {
                    // echo "No file was uploaded or there was an error during the upload.";
                }


                // $package_price = ($buy*($profit/100))+$buy+$trans;
                if ($unit > 0) {
                    $unit_price = $package_price / $unit;
                } else {
                    $unit_price = 0; // or handle the zero case as needed
                }

                if ($pieces > 0 && $unit_price > 0) {
                    $pieces_price = $unit_price / $pieces;
                } else {
                    $pieces_price = 0; // or handle the zero case as needed
                }

                $round_package_price = roundUpToNearestHundred($package_price);
                $round_unit_price = roundUpToNearestHundred($unit_price);
                $round_pieces_price = roundUpToNearestHundred($pieces_price);

                $package_remain = '0';
                $pieces_remain = '0';
                $unit_remain = '0';



                $sql = "SELECT * FROM " . $product . " where barcode='$barcode' or product_name='$product_name'";
                $result = $connection->query($sql);
                if ($result && $result->num_rows > 0) {
                    echo '<script>alert("Product Already Exist") ;</script>';
                } else {

                    $expire_date = date('Y-m-d');
                    $sql = "INSERT INTO " . $product . " (
                barcode, 
                barcode_1,
                barcode_2,
                product_name, 
                type, 
                unit, 
                pieces, 
                buy, 
                currency_buy, 
                rate, 
                currency_rate, 
                trans, 
                profit, 
                round_package_price, 
                round_unit_price, 
                round_pieces_price, 
                package_price, 
                unit_price, 
                pieces_price, 
                package_remain, 
                unit_remain, 
                pieces_remain, 
                package_sell, 
                unit_sell, 
                pieces_sell,
                package_damage,
                unit_damage,
                pieces_damage, 
                package_change,
                unit_change,
                pieces_change, 
                package_trans,
                unit_trans,
                pieces_trans, 
                package_exist, 
                unit_exist, 
                pieces_exist, 
                exp_date, 
                image,
                package_order_remain,
                unit_order_remain,
                pieces_order_remain,
                note,
                delete_d
            ) VALUES (
                '$barcode',
                '$barcode_1',
                '$barcode_2',
                '$product_name',
                '$product_type',
                '$unit',
                '$pieces',
                '$buy',
                '$currency_buy',
                '$rate',
                '$currency_rate',
                '$trans',
                '$profit',
                '$round_package_price',
                '$round_unit_price',
                '$round_pieces_price',
                '0',
                '0',
                '0',
                '$package_remain',
                '$unit_remain',
                '$pieces_remain',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '$expire_date',
                '0',
                '0',
                '0',
                '0',
                '$note',
                '0'
            )";

                    if ($connection->query($sql) === TRUE) {
                        echo "Record inserted successfully into $product<br>";
                    } else {
                        echo "Error inserting record into $product: " . $connection->error . "<br>";
                    }

                    $expire_date = date('Y-m-d');
                    $sql = "INSERT INTO " . $cargo_1 . " (
                barcode, 
                barcode_1,
                barcode_2,
                product_name, 
                type, 
                unit, 
                pieces, 
                buy, 
                currency_buy, 
                rate, 
                currency_rate, 
                trans, 
                profit, 
                round_package_price, 
                round_unit_price, 
                round_pieces_price, 
                package_price, 
                unit_price, 
                pieces_price, 
                package_remain, 
                unit_remain, 
                pieces_remain, 
                package_sell, 
                unit_sell, 
                pieces_sell,
                package_damage,
                unit_damage,
                pieces_damage, 
                package_change,
                unit_change,
                pieces_change, 
                package_trans,
                unit_trans,
                pieces_trans, 
                package_exist, 
                unit_exist, 
                pieces_exist, 
                exp_date, 
                image,
                package_order_remain,
                unit_order_remain,
                pieces_order_remain,
                note,
                delete_d
            ) VALUES (
                '$barcode',
                '$barcode_1',
                '$barcode_2',
                '$product_name',
                '$product_type',
                '$unit',
                '$pieces',
                '$buy',
                '$currency_buy',
                '$rate',
                '$currency_rate',
                '$trans',
                '$profit',
                '$round_package_price',
                '$round_unit_price',
                '$round_pieces_price',
                '0',
                '0',
                '0',
                '$package_remain',
                '$unit_remain',
                '$pieces_remain',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '$expire_date',
                '0',
                '0',
                '0',
                '0','
                '$note',
                '0'
            )";

                    if ($connection->query($sql) === TRUE) {
                        echo "Record inserted successfully into $product<br>";
                    } else {
                        echo "Error inserting record into $product: " . $connection->error . "<br>";
                    }



                    header('location:product_add_new.php');



                    // if (mysqli_query($connection, $sql_cargo)) {
                    //     header('location:product_add_new.php');
                    // } else {
                    //     // echo "Error: " . $sql . " " . mysqli_error($connection);
                    //     echo "<script>alert('Something Wrong!')</script>";
                    //     header('location:product_add_new.php');
                    // }
                }
            }
        }
    }
}



if (isset($_POST['change_image'])) {
    $barcode = $_POST['barcode'];
    $barcode_1 = $_POST['barcode_1'];
    $product_name = $_POST['product_name'];

    if ($barcode == '' && $product_name == '') {
        echo "<script>alert('Need Barcode or Product Name')</script>";
    } else {
        $sql = "SELECT * FROM " . $product . " WHERE product_name='$product_name' OR barcode='$barcode' OR barcode_1='$barcode_1'";
        $result = $connection->query($sql);

        // Check for query execution
        if (!$result) {
            die("Query failed: " . $connection->error);
        }

        // Fetch results if query succeeds
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();


            $productName = trim($row["product_name"]); // Get the product name

            // Check if a file was uploaded
            if (isset($_FILES["image"]) && $_FILES["image"]["error"] === UPLOAD_ERR_OK) {
                // Define the target directory
                $targetDir = "uploads/";

                // Ensure the directory exists
                if (!is_dir($targetDir)) {
                    mkdir($targetDir, 0777, true); // Create the directory if it doesn't exist
                }

                // Get the file extension
                $fileType = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));

                // Construct the target file path with the product name
                $targetFilePath = $targetDir . $productName . '.' . $fileType;

                // Validate allowed file types
                $allowedTypes = array("jpg", "jpeg", "png", "gif");
                if (in_array($fileType, $allowedTypes)) {
                    // Check file size and reduce if necessary
                    $maxFileSize = 2 * 1024 * 1024; // 2MB
                    $desiredFileSize = 100 * 1024; // 100KB

                    // Temporary file path
                    $tempPath = $_FILES["image"]["tmp_name"];

                    // Reduce image size
                    if ($_FILES["image"]["size"] > $maxFileSize) {
                        // Load the image
                        switch ($fileType) {
                            case 'jpg':
                            case 'jpeg':
                                $image = imagecreatefromjpeg($tempPath);
                                break;
                            case 'png':
                                $image = imagecreatefrompng($tempPath);
                                break;
                            case 'gif':
                                $image = imagecreatefromgif($tempPath);
                                break;
                            default:
                                $image = null;
                                break;
                        }

                        if ($image) {
                            // Resize the image
                            $originalWidth = imagesx($image);
                            $originalHeight = imagesy($image);
                            $newWidth = 800; // Set a new width (you can adjust)
                            $newHeight = ($originalHeight / $originalWidth) * $newWidth;

                            $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
                            imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

                            // Save the resized image with reduced quality
                            if ($fileType === 'jpg' || $fileType === 'jpeg') {
                                imagejpeg($resizedImage, $targetFilePath, 75); // 75% quality
                            } elseif ($fileType === 'png') {
                                imagepng($resizedImage, $targetFilePath, 6); // Compression level 6
                            } elseif ($fileType === 'gif') {
                                imagegif($resizedImage, $targetFilePath);
                            }

                            // Free memory
                            imagedestroy($image);
                            imagedestroy($resizedImage);

                            // echo "The image for <strong>" . htmlspecialchars($productName) . "</strong> has been uploaded and resized successfully.";
                            // echo "<br><a href='$targetFilePath'>View Uploaded image</a>";
                        } else {
                            // echo "Unsupported image type.";
                        }
                    } else {
                        // Move the file to the target directory if size is already acceptable
                        if (move_uploaded_file($tempPath, $targetFilePath)) {
                            // echo "The image for <strong>" . htmlspecialchars($productName) . "</strong> has been uploaded successfully.";
                            // echo "<br><a href='$targetFilePath'>View Uploaded image</a>";
                        } else {
                            // echo "Sorry, there was an error uploading your file.";
                        }
                    }
                } else {
                    // echo "Invalid file format. Only JPG, JPEG, PNG, and GIF files are allowed.";
                }
            } else {
                // echo "No file was uploaded or there was an error during the upload.";
            }
        } else {
            // echo "No matching product found.";
        }
    }
}


if (isset($_POST['update'])) {
    $barcode = $_POST['barcode'];
    $barcode_1 = $_POST['barcode_1'];
    $product_name = $_POST['product_name'];

    if ($barcode == '' && $product_name == '') {
        // echo "<script>alert('Need Barcode')</script>";
    } else {

        $sql = "SELECT * FROM " . $product . " 
        WHERE (barcode='$barcode' OR barcode_1='$barcode_1' OR barcode='$barcode_1' OR barcode_1='$barcode') 
        AND delete_d='0'
        AND product_name != '" . $product_name . "'";
        $result = $connection->query($sql);
        if ($result && $result->num_rows > 0) {
            echo '<script>alert("Product code already Exist") ;</script>';
        } else {

            $product_tables = [$product, $cargo_1];
            foreach ($product_tables as $product_data) {
                //update barcode,name.....
                $sql = "UPDATE " . $product_data . " SET barcode='$barcode',barcode_1='$barcode_1' WHERE product_name='$product_name'";
                //$sql = "UPDATE product SET barcode='$barcode' WHERE id='$no'";
                if ($connection->query($sql) === TRUE) {
                    // echo json_encode(['status' => 'success', 'message' => 'Record updated successfully']);
                } else {
                    // echo json_encode(['status' => 'error', 'message' => 'Error updating record: ' . $connection->error]);
                }
            }
        }
    }
}

if (isset($_POST['update_data'])) {
    $barcode = $_POST['barcode'];
    $trans = $_POST['trans'];
    $buy = '1';
    $unit = '1';
    $pieces = '1';
    $currency_buy = 'kyat';
    $profit = '0';

    // Function to round up to the nearest hundred
    function roundUpToNearestHundred($number)
    {
        return ceil($number / 100) * 100;
    }

    // Array of product tables to update
    $product_tables = [$product, $cargo_1];

    // Update barcode, trans, buy, unit, pieces for both tables
    foreach ($product_tables as $product_data) {
        $sql = "UPDATE $product_data SET profit='$profit',trans='$trans', buy='$buy', unit='$unit', pieces='$pieces' WHERE barcode='$barcode'";
        if (!$connection->query($sql)) {
            // Log error or handle it appropriately
            error_log("Error updating $product_data: " . $connection->error);
        }
    }

    // Query product table to get current values
    // Fetch product details
    $sql = "SELECT * FROM $product WHERE barcode = ?";
    $stmt = $connection->prepare($sql);
    $stmt->bind_param('s', $barcode);
    $stmt->execute();
    $product_result = $stmt->get_result();

    if ($product_result && $product_result->num_rows > 0) {
        $row = $product_result->fetch_assoc();
        $unit = $row['unit'];
        $pieces = $row['pieces'];
        $buy = $row['buy'];
        $trans = $row['trans'];
        $profit = $row['profit'];

        // Query rate table (once)
        $sql_rate = "SELECT * FROM $rate";
        $rate_result = $connection->query($sql_rate);

        if ($rate_result && $rate_result->num_rows > 0) {
            $rate_row = $rate_result->fetch_assoc();
            $baht = $rate_row['baht'];
            $yuan = $rate_row['yuan'];
            $dollar = $rate_row['dollar'];

            // Calculate prices based on the currency
            if ($currency_buy == 'kyat') {
                $rate = '1';
            } else if ($currency_buy == 'baht') {
                $rate = $baht;
            } else if ($currency_buy == 'yuan') {

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

                $rate = $dollar;
            }
            $package_price = ($profit + $buy + $trans) * $rate;


            if ($unit > 0) {
                $unit_price = $package_price / $unit;
            } else {
                $unit_price = 0; // or handle the zero case as needed
            }

            if ($pieces > 0 && $unit_price > 0) {
                $pieces_price = $unit_price / $pieces;
            } else {
                $pieces_price = 0; // or handle the zero case as needed
            }

            // Round prices
            $round_package_price = roundUpToNearestHundred($package_price);
            $round_unit_price = roundUpToNearestHundred($unit_price);
            $round_pieces_price = roundUpToNearestHundred($pieces_price);

            // Prepare SQL for updating tables
            foreach ($product_tables as $product_data) {
                $sql_update = "UPDATE $product_data 
                           SET package_price = ?, 
                            unit_price = ?, 
                               pieces_price = ?, 
                               round_package_price = ?, 
                               round_unit_price = ?, 
                               round_pieces_price = ? 
                           WHERE barcode = ?";
                $stmt_update = $connection->prepare($sql_update);
                $stmt_update->bind_param('dddddds', $package_price, $unit_price, $pieces_price, $round_package_price, $round_unit_price, $round_pieces_price, $barcode);

                if (!$stmt_update->execute()) {
                    // Log error or handle it appropriately
                    error_log("Error updating prices in $product_data: " . $stmt_update->error);
                }
            }

            // Redirect after successful update
            header('Location: product_add_new.php');
            exit;
        } else {
            // Log error if no rates are found
            error_log("No rates found in $rate");
        }
    } else {
        // Log error if no product is found
        error_log("No product found with barcode: $barcode");
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $id = isset($_POST['id']) ? $_POST['id'] : null;
    $action = isset($_POST['action']) ? $_POST['action'] : null;

    switch ($action) {
        case 'info':
            $sql = "SELECT * FROM " . $product . " WHERE id = '$id'";
            $result = $connection->query($sql);
            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $imageData = $row['image'];

                echo ' 
                    <div class="modal fade" id="infoModal" tabindex="-1" aria-labelledby="infoModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header bg-info text-white">
                                <h5 class="modal-title" id="infoModalLabel">' . $row["product_name"] . '</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="refreshPage()">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <!-- Dynamically inserted Image -->
                                <div class="text-center">';


                // Define the possible file extensions
                $extensions = ['jpg', 'jpeg', 'png', 'gif'];
                $imagePath = '';

                // Check for the correct file extension
                foreach ($extensions as $ext) {
                    $potentialPath = 'uploads/' . $row["product_name"] . '.' . $ext;
                    if (file_exists($potentialPath)) {
                        $imagePath = $potentialPath;
                        break;
                    }
                }

                // If the image path is found, display the image
                if ($imagePath) {
                    echo '<img src="' . $imagePath . '" class="img-fluid mb-3" alt="Sample Image" style="margin-left:auto;margin-right:auto;width:200px;">';
                } else {
                    echo 'Image not found.';
                }



                echo '</div>
                                    <form action="product_add_new.php" method="POST">
                                    <table style="font-size:15px;">
                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">barcode:</label></th>
                                        <th><input type="text" tyle="font-size: 15px;" class="form-control"  name="barcode" value="' . $row["barcode"] . '"></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">သယ်ဆောင်ခ:</label></th>
                                        <th><input type="text" tyle="font-size: 15px;" class="form-control"  name="trans" value="' . $row["trans"] . '"></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">ငွေအမျိုးအစား:</label></th>
                                        <th>
                                            <select name="currency_buy" id="bankingInput" class="form-control">
                                            <option value="' . $row['currency_buy'] . '">' . $row['currency_buy'] . '</option>
                                            <option value="kyat">ကျပ်</option>
                                            <option value="baht">ဘတ်</option>
                                            <option value="yuan">ယွမ်</option>
                                            </select>
                                        </th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">ဖာလိုက်ဝယ်ဈေး:</label></th>
                                        <th><input type="text" tyle="font-size: 15px;" class="form-control"  name="buy" value="' . $row["buy"] . '"></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">မူရင်းကဒ်:</label></th>
                                        <th><input type="text" tyle="font-size: 15px;" class="form-control"  name="unit" value="' . $row["unit"] . '"></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">မူရင်းဗူး:</label></th>
                                        <th><input type="text" tyle="font-size: 15px;" class="form-control"  name="pieces" value="' . $row["pieces"] . '"></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">မူရင်းဗူး:</label></th>
                                        <th><input type="text" tyle="font-size: 15px;" class="form-control"  name="profit" value="' . $row["profit"] . '"></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">ရောင်းဈေးဖာ:</label></th>
                                        <th><input type="text" style="font-size: 15px;" class="form-control" value="' . $row["round_package_price"] . '" readonly></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">ရောင်းဈေးကဒ်:</label></th>
                                        <th><input type="text" style="font-size: 15px;" class="form-control" value="' . $row["round_unit_price"] . '" readonly></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">ရောင်းဈေးဗူး:</label></th>
                                        <th><input type="text" style="font-size: 15px;" class="form-control" value="' . $row["round_pieces_price"] . '" readonly></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">လက်ကျန်ဖာ:</label></th>
                                        <th><input type="text" style="font-size: 15px;" class="form-control" value="' . $row["package_exist"] . '" readonly></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">လက်ကျန်ကဒ်:</label></th>
                                        <th><input type="text" style="font-size: 15px;" class="form-control" value="' . $row["unit_exist"] . '" readonly></th>
                                    </tr>

                                    <tr style="height: 25px;">
                                        <th> <label for="pwd" alt="hi" style="font-size: 15px;">လက်ကျန်ဗူး:</label></th>
                                        <th><input type="text" style="font-size: 15px;" class="form-control" value="' . $row["pieces_exist"] . '" readonly></th>
                                    </tr>

                                    <tr>
                                    <th scope="col" colspan="3"> <button type="submit" name="update_data" class="btn btn-outline-success" style="margin: 10px;width:90%" data-toggle="modal" data-target="#infoModal">ပြင်ရန်</button></th>
                                    </tr>
                                </table>
                                </form>
                                   
                                    </div>
                                </div>
                                </div>
                            </div>
                            ';
            } else {
                echo "Image not found.";
            }
            echo '
                    ';



            break;

        case 'upload':

            break;


        case 'delete':

            $sql = "SELECT product_name FROM " . $product . " WHERE id ='$id'";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $product_name = $row['product_name'];

                    //Delete Photo
                    $extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                    // Loop through the extensions to find the existing file
                    $fileToDelete = '';
                    foreach ($extensions as $ext) {
                        $potentialFile = 'uploads/' . $product_name . '.' . $ext;
                        if (file_exists($potentialFile)) {
                            $fileToDelete = $potentialFile;
                            break;
                        }
                    }

                    // Check if a matching file was found
                    if ($fileToDelete) {
                        // Attempt to delete the file
                        if (unlink($fileToDelete)) {
                            // echo "File deleted successfully: $fileToDelete";
                        } else {
                            // echo "Error: Unable to delete the file.";
                        }
                    } else {
                        // echo "Error: File does not exist with any of the expected extensions.";
                    }

                    //Update Data
                    $product_tables = [$product, $cargo_1];

                    foreach ($product_tables as $product_data) {
                        $query = "DELETE FROM " . $product_data . " WHERE product_name = '$product_name'";
                        if ($connection->query($query)) {
                            echo 'Deleted successfully.';
                        } else {
                            echo 'alert("Update failed!");';
                        }
                    }

                    // Get the file name dynamically (e.g., from a form input)





                }
            }
            break;

        default:
    }
} else {
}


?>

<script>
    function refreshPage() {
        location.reload();
    }
</script>


<body>
    <div class="wrapper">
        <?php
        include "sidebar.php";
        include "database/database.php";
        include "database/data.php";
        ?>

        <div class="main">
            <nav class="navbar navbar-expand px-3 border-bottom">
                <button class="btn" id="sidebar-toggle" type="button">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse navbar">
                    <ul class="navbar-nav">
                        <div class="mb-3" style="margin-right:30px">
                            <h4 style="font-size:25px">ပစ္စည်းအသစ်ထည့်ရန်</h4>
                        </div>

                        <li class="nav-item dropdown">
                            <a href="#" data-bs-toggle="dropdown" class="nav-icon pe-md-0">
                                <img src="image/logo.png" class="avatar img-fluid rounded" alt="">
                            </a>
                            <?php include "logo_profile.php"; ?>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="content px-3 py-2">
                <div class="container-fluid">


                    <div class="row">

                        <div class="col-sm-4" style="background-color:#19242e;border-radius:20px;color:orange;margin-bottom:20px">


                            <form id="myForm" action="product_add_new.php" method="POST" style="margin-top:20px;margin-left:20px" enctype="multipart/form-data">

                                <table style="border:none;">



                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi">ဗူး/ခု:</label></th>
                                        <th>
                                            <div style="display:flex;">
                                                <input type="text" class="form-control" name="barcode" id="barcodeInput" placeholder="Barcode" style="width:80%" autofocus>
                                                <button type="button" id="start-scan-btn" class="btn btn-outline-warning" style="margin-left:10px">Scan</button>
                                            </div>
                                        </th>
                                        <!-- <th><button type="button" name="print" id="print" class="btn btn-outline-warning">Print</button></th> -->
                                    </tr>

                                    <script>
                                        document.addEventListener('DOMContentLoaded', () => {
                                            const video = document.getElementById('barcode-scanner');
                                            const barcodeInput = document.getElementById('barcodeInput');
                                            const startScanButton = document.getElementById('start-scan-btn');
                                            let stream = null; // To store the camera stream

                                            startScanButton.addEventListener('click', async () => {
                                                try {
                                                    stream = await navigator.mediaDevices.getUserMedia({
                                                        video: {
                                                            facingMode: 'environment'
                                                        }
                                                    });
                                                    video.srcObject = stream;

                                                    video.addEventListener('loadedmetadata', () => {
                                                        video.play();
                                                        detectBarcode();
                                                    });
                                                } catch (error) {
                                                    console.error('Error accessing camera:', error);
                                                }
                                            });

                                            async function detectBarcode() {
                                                const barcodeDetector = new BarcodeDetector();

                                                try {
                                                    const barcodes = await barcodeDetector.detect(video);
                                                    if (barcodes.length > 0) {
                                                        const detectedBarcode = barcodes[0].rawValue;
                                                        barcodeInput.value = detectedBarcode;
                                                        // Close the camera stream
                                                        closeCamera();
                                                    } else {
                                                        setTimeout(detectBarcode, 200); // Check again after 200ms
                                                    }
                                                } catch (error) {
                                                    console.error('Barcode detection error:', error);
                                                }
                                            }

                                            function closeCamera() {
                                                if (stream) {
                                                    const tracks = stream.getTracks();
                                                    tracks.forEach(track => track.stop());
                                                    video.srcObject = null;
                                                }
                                            }
                                        });
                                    </script>

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi">ကဒ်:</label></th>
                                        <th>
                                            <div style="display:flex;">
                                                <input type="text" class="form-control" name="barcode_1" id="barcodeInput_1" placeholder="Barcode" style="width:80%" autofocus>
                                                <button type="button" id="start-scan-btn_1" class="btn btn-outline-warning" style="margin-left:10px">Scan</button>
                                            </div>
                                        </th>
                                        <!-- <th><button type="button" name="print" id="print" class="btn btn-outline-warning">Print</button></th> -->
                                    </tr>

                                    <script>
                                        document.addEventListener('DOMContentLoaded', () => {
                                            const video_1 = document.getElementById('barcode-scanner_1');
                                            const barcodeInput_1 = document.getElementById('barcodeInput_1');
                                            const startScanButton_1 = document.getElementById('start-scan-btn_1');
                                            let stream = null; // To store the camera stream

                                            startScanButton_1.addEventListener('click', async () => {
                                                try {
                                                    stream = await navigator.mediaDevices.getUserMedia({
                                                        video: {
                                                            facingMode: 'environment'
                                                        }
                                                    });
                                                    video_1.srcObject = stream;

                                                    video_1.addEventListener('loadedmetadata', () => {
                                                        video_1.play();
                                                        detectBarcode();
                                                    });
                                                } catch (error) {
                                                    console.error('Error accessing camera:', error);
                                                }
                                            });

                                            async function detectBarcode() {
                                                const barcodeDetector = new BarcodeDetector();

                                                try {
                                                    const barcodes = await barcodeDetector.detect(video_1);
                                                    if (barcodes.length > 0) {
                                                        const detectedBarcode = barcodes[0].rawValue;
                                                        barcodeInput_1.value = detectedBarcode;
                                                        // Close the camera stream
                                                        closeCamera();
                                                    } else {
                                                        setTimeout(detectBarcode, 200); // Check again after 200ms
                                                    }
                                                } catch (error) {
                                                    console.error('Barcode detection error:', error);
                                                }
                                            }

                                            function closeCamera() {
                                                if (stream) {
                                                    const tracks = stream.getTracks();
                                                    tracks.forEach(track => track.stop());
                                                    video_1.srcObject = null;
                                                }
                                            }
                                        });
                                    </script>

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi">ဖာ:</label></th>
                                        <th>
                                            <div style="display:flex;">
                                                <input type="text" class="form-control" name="barcode_2" id="barcodeInput_2" placeholder="Barcode" style="width:80%" autofocus>
                                                <button type="button" id="start-scan-btn_2" class="btn btn-outline-warning" style="margin-left:10px">Scan</button>
                                            </div>
                                        </th>
                                        <!-- <th><button type="button" name="print" id="print" class="btn btn-outline-warning">Print</button></th> -->
                                    </tr>

                                    <script>
                                        document.addEventListener('DOMContentLoaded', () => {
                                            const video_2 = document.getElementById('barcode-scanner_2');
                                            const barcodeInput_2 = document.getElementById('barcodeInput_2');
                                            const startScanButton_2 = document.getElementById('start-scan-btn_2');
                                            let stream = null; // To store the camera stream

                                            startScanButton_2.addEventListener('click', async () => {
                                                try {
                                                    stream = await navigator.mediaDevices.getUserMedia({
                                                        video: {
                                                            facingMode: 'environment'
                                                        }
                                                    });
                                                    video_2.srcObject = stream;

                                                    video_2.addEventListener('loadedmetadata', () => {
                                                        video_2.play();
                                                        detectBarcode();
                                                    });
                                                } catch (error) {
                                                    console.error('Error accessing camera:', error);
                                                }
                                            });

                                            async function detectBarcode() {
                                                const barcodeDetector = new BarcodeDetector();

                                                try {
                                                    const barcodes = await barcodeDetector.detect(video_2);
                                                    if (barcodes.length > 0) {
                                                        const detectedBarcode = barcodes[0].rawValue;
                                                        barcodeInput_2.value = detectedBarcode;
                                                        // Close the camera stream
                                                        closeCamera();
                                                    } else {
                                                        setTimeout(detectBarcode, 200); // Check again after 200ms
                                                    }
                                                } catch (error) {
                                                    console.error('Barcode detection error:', error);
                                                }
                                            }

                                            function closeCamera() {
                                                if (stream) {
                                                    const tracks = stream.getTracks();
                                                    tracks.forEach(track => track.stop());
                                                    video_2.srcObject = null;
                                                }
                                            }
                                        });
                                    </script>


                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi"> ပစ္စည်းအမည်:</label></th>
                                        <th><input type="text" class="form-control" name="product_name" placeholder=""></th>
                                    </tr>

                                    <tr style="height: 50px;">
                                        <th><label for="pwd">အမျိုးအစား:</label></th>
                                        <th>
                                            <div style="display: flex; align-items: center; gap: 10px;">
                                                <select name="product_type" id="bankingInput" class="form-control">
                                                    <?php
                                                    $sql = "SELECT * FROM " . $catagories . "";
                                                    $result = $connection->query($sql);
                                                    if ($result && $result->num_rows > 0) {
                                                        while ($row = $result->fetch_assoc()) {
                                                            $name = $row['type'];
                                                            echo '<option value="' . $name . '">' . $name . '</option>';
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                                <a href="product_catagories.php"><i class="fa-solid fa-square-plus fa-2xl" style="color: #ffffff; cursor: pointer;"></i></a>
                                            </div>
                                        </th>
                                    </tr>

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi"> ကားခ:</label></th>
                                        <th><input type="text" class="form-control" name="trans" value="0"></th>
                                    </tr>

                                    <tr style="height: 50px;">
                                        <th>
                                            <label for="pwd" alt="hi"> ကဒ်ပမာဏ</label>
                                        </th>
                                        <th>
                                            <input type="text" class="form-control" name="unit" id="unitInput"
                                                placeholder="ဖာအတွင်းရှိ ကဒ်အရေတွက်"
                                                onfocus="this.dataset.defaultValue = this.value; this.value='';"
                                                onblur="if(this.value==='') this.value = this.dataset.defaultValue || '1';">
                                        </th>
                                    </tr>

                                    <tr style="height: 50px;">
                                        <th>
                                            <label for="pwd" alt="hi"> ဗူးပမာဏ</label>
                                        </th>
                                        <th>
                                            <input type="text" class="form-control" name="pieces" id="unitInput"
                                                placeholder="ကဒ်အတွင်းရှိ ဗူး/ခု အရေတွက်"
                                                onfocus="this.dataset.defaultValue = this.value; this.value='';"
                                                onblur="if(this.value==='') this.value = this.dataset.defaultValue || '1';">
                                        </th>
                                    </tr>

                                    <!-- <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> ဖာဝယ်ဈေး:</label></th>
                            <th>    <input type="text" class="form-control" id="formatted" name="buy" placeholder="" value="1"></th>
                        </tr> -->

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi">ဖာဝယ်ဈေး:</label></th>
                                        <div>
                                            <th style="display:flex;">
                                                <input type="text" class="form-control" name="buy" placeholder="" value="1">
                                                <select name="currency_buy" id="bankingInput" class="form-control ms-3">
                                                    <option value="kyat">ကျပ်</option>
                                                    <option value="baht">ဘတ်</option>
                                                    <option value="yuan">ယွမ်</option>
                                                </select>
                                            </th>
                                        </div>
                                    </tr>

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi"> ဓာတ်ပုံ:</label></th>
                                        <th><input type="file" class="form-control" name="image" id="image"></th>
                                    </tr>

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi"> မှတ်စု:</label></th>
                                        <th><input type="text" class="form-control" name="note"></th>
                                    </tr>
                                </table>


                                <!-- <div style="margin-top: 20px; display: flex; justify-content: center;" class="container-fluid">
                        <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;">ပေါင်းထည့်</button>
                        <button type="submit" name="change_currency" class="btn btn-outline-danger" style="margin: 10px;">ငွေဈေးပြောင်း</button>
                        <button type="submit" name="change_image" class="btn btn-outline-success" style="margin: 10px;" data-toggle="modal" data-target="#infoModal">ပုံပြောင်းရန်</button>
                    </div> -->
                                <table class="table table-borderless">

                                    <tr>
                                        <th style="background-color:#19242e"> <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 5px;width:100%" data-toggle="modal" data-target="#infoModal">ပေါင်းထည့်</button></th>
                                        <th style="background-color:#19242e"> <button type="submit" name="change_image" class="btn btn-outline-warning" style="margin: 5px;width:100%" data-toggle="modal" data-target="#infoModal">ပုံပြောင်း</button></th>
                                    </tr>

                                    <tr>
                                        <th colspan="2" style="background-color:#19242e"> <button type="submit" name="update" class="btn btn-outline-warning" style="margin: 5px;width:100%" data-toggle="modal" data-target="#infoModal">Update Barcode</button></th>
                                    </tr>

                                    <tr>
                                        <th colspan="2" style="background-color:#19242e"> <button type="submit" name="change_image" class="btn btn-outline-warning" style="margin: 5px;width:100%" data-toggle="modal" data-target="#infoModal" id="generateBarcodeBtn">Generate barcode</button></th>
                                    </tr>

                                    <tr>
                                        <th colspan="2" style="background-color:#19242e"> <button type="submit" name="refresh" class="btn btn-outline-success" style="margin: 5px;width:100%" data-toggle="modal" data-target="#infoModal" onclick="refreshPage()">Refresh</button></th>
                                    </tr>


                                </table>


                            </form>

                            <script>
                                document.getElementById("generateBarcodeBtn").addEventListener("click", function(event) {
                                    // Prevent the form from submitting
                                    event.preventDefault();

                                    // Generate the current date and time in the specified format
                                    const now = new Date();
                                    const day = String(now.getDate()).padStart(2, '0');
                                    const month = String(now.getMonth() + 1).padStart(2, '0'); // Months are zero-indexed
                                    const year = now.getFullYear();
                                    const hours = String(now.getHours()).padStart(2, '0');
                                    const minutes = String(now.getMinutes()).padStart(2, '0');
                                    const seconds = String(now.getSeconds()).padStart(2, '0');

                                    // Format barcode as day-month-year-hours-minutes-seconds
                                    const barcode = `${day}${month}${year}${hours}${minutes}${seconds}`;
                                    const barcode_1 = `${day}${month}${year}${hours}${minutes}${seconds}${1}`;
                                    const barcode_2 = `${day}${month}${year}${hours}${minutes}${seconds}${2}`;

                                    // Insert the barcode into the input field
                                    document.getElementById("barcodeInput").value = barcode;
                                    document.getElementById("barcodeInput_1").value = barcode_1;
                                    document.getElementById("barcodeInput_2").value = barcode_2;
                                });
                            </script>

                            <script>
                                document.getElementById('myForm').addEventListener('keydown', function(event) {
                                    if (event.key === 'Enter') {
                                        event.preventDefault(); // Prevent the default action (form submission)
                                    }
                                });
                            </script>

                        </div>

                        <!-- Table Element -->
                        <div class="col-sm-8">

                            <div class="card-header gx-5">

                                <form class="d-flex flex-row-reverse" method="GET">
                                    <div class="col-auto" style="margin-left:10px">
                                        <input type="text" class="form-control" id="searchInput" name="search" value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>" placeholder="Search">
                                    </div>
                                    <div class="col-auto">
                                        <button type="submit" class="btn btn-primary mb-3"><i class="fa-solid fa-magnifying-glass"></i></button>
                                    </div>
                                </form>

                            </div>

                            <?php
                            $sql_rate = "SELECT * FROM ".$rate." LIMIT 1"; // Add LIMIT 1 to ensure only one row is fetched
            $result = $connection->query($sql_rate);
            
            if ($result && $result->num_rows > 0) {
                $row_rate = $result->fetch_assoc();
                $baht = $row_rate['baht']; 
                $yuan = $row_rate['yuan']; 
                $profit_percent = $row_rate['profit']; 
            } else {
                // Handle case where no rows are returned
                $baht = null;
                $yuan = null;
            }

                            $limit = 100;
                            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                            $start = ($page - 1) * $limit;

                            $search = isset($_GET['search']) ? mysqli_real_escape_string($connection, $_GET['search']) : '';

                            // Total Records
                            $totalQuery = "SELECT COUNT(*) as total FROM $product WHERE delete_d='0'";
                            if (!empty($search)) {
                                $totalQuery .= " AND (product_name LIKE '%$search%' OR type LIKE '%$search%' OR barcode LIKE '%$search%' OR barcode_1 LIKE '%$search%' OR barcode_2 LIKE '%$search%')";
                            }
                            $totalResult = mysqli_query($connection, $totalQuery);
                            $totalRow = mysqli_fetch_assoc($totalResult);
                            $totalRecords = $totalRow['total'];
                            $totalPages = ceil($totalRecords / $limit);

                            // Fetch Data with Search and Pagination
                            $sql = "SELECT * FROM $product WHERE delete_d='0'";
                            if (!empty($search)) {
                                $sql .= " AND (product_name LIKE '%$search%' OR type LIKE '%$search%' OR barcode LIKE '%$search%' OR barcode_1 LIKE '%$search%' OR barcode_2 LIKE '%$search%')";
                            }
                            $sql .= " ORDER BY id DESC LIMIT $start, $limit";
                            $result = mysqli_query($connection, $sql);
                            ?>
                            <div class="container mt-4">

                                <div class="scrollable-table" style="height:60vh; overflow-y: auto;">
                                    <table class="table table-bordered table-hover text-white" style="font-size:18px;" id="dataTable">
                                        <thead style="background-color:#19242e;" class="text-center">
                                            <tr>
                                                <th>no</th>
                                                <th>ဓာတ်ပုံ</th>
                                                <th>Update</th>
                                                <th>ဖြည့်ရန်</th>

                                                <th>ပစ္စည်းအမည်</th>
                                                <th>အမျိုးစား</th>
                                                <th>ကားခ(ကျပ်)</th>
                                                <th>ဗူးဖွဲ့စည်းပုံ</th>
                                                <th>ကဒ်ဖွဲ့စည်းပုံ</th>

                                                <th style="color:#FFA62F">ရောင်းဈေး (ဖာ)</th>
                                                <th style="color:#FFA62F">ရောင်းဈေး (ကဒ်)</th>
                                                <th style="color:#FFA62F">ရောင်းဈေး (ဗူး)</th>

                                                <th>ဗူး</th>
                                                <th>ကဒ်</th>
                                                <th>ဖာ</th>

                                                <th>Barcode (ဗူး)</th>
                                                <th>Barcode (ကဒ်)</th>
                                                <th>Barcode (ဖာ)</th>

                                                <th style="color:#ACE1AF">Delete</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($result): ?>
                                                <?php
                                                $totalRows = mysqli_num_rows($result); // Get total number of rows
                                                $no = $totalRows; ?>
                                                <?php while ($row = mysqli_fetch_assoc($result)): ?>

                                                    <?php
                                                    $imagePath = 'uploads/'; // Your image directory
                                                    $productName = htmlspecialchars($row['product_name']); // Product name

                                                    // Find image with any of the allowed extensions
                                                    $imageExtensions = ['jpg', 'jpeg', 'png', 'gif']; // Allowed formats
                                                    $imageFile = '';

                                                    foreach ($imageExtensions as $ext) {
                                                        if (file_exists($imagePath . $productName . '.' . $ext)) {
                                                            $imageFile = $imagePath . $productName . '.' . $ext;
                                                            break; // Stop searching once the first match is found
                                                        }
                                                    }

                                                    $product_name = $row['product_name'];
                            $type = $row['type'];
                            $buy = $row['buy'];
                            $currency_buy = $row['currency_buy'];
                            $unit = $row['unit'];
                            $pieces = $row['pieces'];

                            $trans = $row['trans'];
                            $package_price = $row['package_price'];
                            $unit_price = $row['unit_price'];
                            $pieces_price = $row['pieces_price'];

                            $unit = is_numeric($unit) ? (float)$unit : 0;
                            $pieces = is_numeric($pieces) ? (float)$pieces : 0;

                            if (!function_exists('forkyat')) {
                                function forkyat($number)
                                {
                                    return ceil($number / 100) * 100;
                                }
                            }

                            $product_name_data = $row['product_name'];
                            $id_data = $row['id'];
                            $barcode_data = $row['barcode'];
                            $barcode_1_data = $row['barcode_1'];
                            $barcode_2_data = $row['barcode_2'];
                            $type_data = $row['type'];
                            $rate_data = $row['rate'];
                            $currency_buy_data = $row['currency_buy'];
                            $trans_data = $row['trans'];
                            $buy_data = $row['buy'];
                            $unit_data = $row['unit'];
                            $pieces_data = $row['pieces'];

                            $package_price_data = $row['package_price'];
                            $unit_price_data = $row['unit_price'];
                            $pieces_price_data = $row['pieces_price'];

                            $package_exist_data = $row['package_exist'];
                            $unit_exist_data = $row['unit_exist'];
                            $pieces_exist_data = $row['pieces_exist'];

                            $profit_percent = 0; // default value in case no category found
                            $sql_cat = "SELECT sell FROM $catagories WHERE type='$type' LIMIT 1";
                            $result_cat = mysqli_query($connection, $sql_cat);

                            if ($result_cat) {
                                $cat = mysqli_fetch_assoc($result_cat);
                                if ($cat) {
                                    $profit_percent = $cat['sell'];
                                }
                            }
                            include "cal_sell_price_ll.php";

                                                    ?> 

                                                    <?php
                                                    echo '<tr>
                        <td class="fixed-column" style="display:none;">' . htmlspecialchars($id_data) . '</td>       
                        <td class="fixed-column">' . htmlspecialchars($no) . '</td> ';



                                                    // Display image if found, else show a default placeholder
                                                    $imageTag = $imageFile
                                                        ? '<img src="' . $imageFile . '" class="product-image" />'
                                                        : '<img src="uploads/logo.png" class="product-image" />';

                                                    echo '
                            <td class="fixed-column-2">
                                ' . $imageTag . '
                            </td>';

                                                    echo '

                                                       <td>
        <form action="product_photo_view.php" method="POST"  target="_blank">
            <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
            <input type="hidden" name="action" value="info">
            <button type="submit" class="btn btn-success" name="info_button">Update</button>
        </form>                                                
        </td>      

        <td>
        <form action="product_add_new_refill.php" method="POST"  target="_blank">
            <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
            <input type="hidden" name="action" value="info">
            <button type="submit" class="btn btn-primary" name="info_button">Refill</button>
        </form>                                                
        </td>   
 
 
        <th scope="row" class="fixed-column-2">' . htmlspecialchars($product_name_data) . '</th>
        <td class="fixed-column-3">' . htmlspecialchars($type_data) . '</td>  
        <td class="fixed-column-3">' . htmlspecialchars($trans_data) . '</td>  
      

        <td class="fixed-column-2">' . htmlspecialchars($unit_data) . '</td>
        <td class="fixed-column-2">' . htmlspecialchars($pieces_data) . '</td>

        <td class="fixed-column-2">' . htmlspecialchars($kyat_package_price) . '</td>
                        <td class="fixed-column-2">' . htmlspecialchars($kyat_unit_price) . '</td>
                        <td class="fixed-column-2">' . htmlspecialchars($kyat_pieces_price) . '</td>

        
        <td>
        <form action="print_barcode_unit.php" method="POST"  target="_blank">
            <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
            <input type="hidden" name="action" value="info">
            <button type="submit" class="btn btn-warning" name="info_button">Print</button>
        </form>                                                
        </td> 

        <td>
        <form action="print_barcode_package.php" method="POST"  target="_blank">
            <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
            <input type="hidden" name="action" value="info">
            <button type="submit" class="btn btn-warning" name="info_button">Print</button>
        </form>                                                
        </td> 



        <td>
        <form action="print_barcode.php" method="POST"  target="_blank">
            <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
            <input type="hidden" name="action" value="info">
            <button type="submit" class="btn btn-warning" name="info_button">Print</button>
        </form>                                                
        </td>  
                       

                        <td class="fixed-column-2">' . htmlspecialchars($barcode_data) . '</td>
                        <td class="fixed-column-2">' . htmlspecialchars($barcode_1_data) . '</td>
                        <td class="fixed-column-2">' . htmlspecialchars($barcode_2_data) . '</td>
                      

                        

                        ';


                                                    echo '                                                                                        
                        <td><button type="submit" class="btn btn-danger" data-action="delete">Delete</button></td>                            
                        </tr>';
                                                    $no--;


                                                    ?>

                                                <?php endwhile; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <nav>
                                    <ul class="pagination justify-content-center mt-3 custom-pagination">
                                        <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">Previous</a>
                                            </li>
                                        <?php endif; ?>

                                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                            <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                                                <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                                            </li>
                                        <?php endfor; ?>

                                        <?php if ($page < $totalPages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Next</a>
                                            </li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>
                            </div>

                        </div>


                    </div>
                </div>
                <video id="barcode-scanner" autoplay playsinline></video>

                <video id="barcode-scanner_1" autoplay playsinline></video>

                <video id="barcode-scanner_2" autoplay playsinline></video>
            </main>



            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    document.getElementById('dataTable').addEventListener('click', function(event) {
                        if (event.target.tagName === 'BUTTON') {
                            const action = event.target.getAttribute('data-action');
                            const row = event.target.closest('tr');
                            const id = row.cells[0].innerText;

                            // Create a FormData object and append the necessary data
                            const formData = new FormData();
                            formData.append('id', id);
                            formData.append('action', action);

                            // Send the form data using Fetch API
                            fetch('product_add_new.php', {
                                    method: 'POST',
                                    body: formData
                                })
                                .then(response => response.text())
                                .then(data => {
                                    if (action === 'delete') {
                                        // Refresh the page if the delete action is performed
                                        location.reload();
                                    } else {
                                        // Insert the returned HTML into a container element
                                        const modalContainer = document.createElement('div');
                                        modalContainer.innerHTML = data;
                                        document.body.appendChild(modalContainer);

                                        // Display the modal
                                        const modal = new bootstrap.Modal(modalContainer.querySelector('.modal'));
                                        modal.show();

                                        // Add event listener to refresh the page when the modal is hidden
                                        modalContainer.querySelector('.modal').addEventListener('hidden.bs.modal', function() {
                                            location.reload();
                                        });
                                    }
                                })
                                .catch(error => {
                                    console.error('Error:', error);
                                });
                        }
                    });
                });
            </script>


            <script>
                $(document).ready(function() {
                    $('#infoModal').on('hidden.bs.modal', function() {
                        location.reload();
                    });
                });
            </script>

            <!-- Search for js code -->

            <script>
                $(document).ready(function() {
                    $("#searchInput").on("keyup", function() {
                        var value = $(this).val().toLowerCase();

                        $("#dataTable tbody tr").filter(function() {
                            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                        });
                    });
                });
            </script>
            <?php
            if ($_SERVER["REQUEST_METHOD"] == "POST") {
                $data = json_decode(file_get_contents('php://input'), true);

                // Assuming 'no' is the primary key for your product table
                if (isset($data['no'])) {
                    $no = $connection->real_escape_string($data['no']);
                    $barcode = $connection->real_escape_string($data['barcode']);
                    $product_name = $connection->real_escape_string($data['ပစ္စည်းအမည်']);

                    $type = $connection->real_escape_string($data['အမျိုးအစား']);
                    $unit = $connection->real_escape_string($data['မူရင်းကဒ်']);
                    $pieces = $connection->real_escape_string($data['မူရင်းဗူး']);
                    $buy_data = $connection->real_escape_string($data['ဖာလိုက်ဝယ်ဈေး']);
                    $profit = $connection->real_escape_string($data['PF']);
                    $trans = $connection->real_escape_string($data['သယ်ဆောင်ခ']);
                    $currency_buy = $connection->real_escape_string($data['ငွေအမျိုးစား']);

                    // Remove commas
                    $buy_data_1 = str_replace(",", "", $buy_data);

                    // Convert to integer or float
                    $buy = intval($buy_data_1);

                    $product_tables = [$product, $cargo_1];

                    foreach ($product_tables as $product_data) {

                        //update barcode,name.....
                        $sql = "UPDATE " . $product_data . " SET profit='$profit',type='$type',unit='$unit',pieces='$pieces',buy='$buy',trans='$trans',currency_buy='$currency_buy' WHERE product_name='$product_name'";
                        //$sql = "UPDATE product SET barcode='$barcode' WHERE id='$no'";
                        if ($connection->query($sql) === TRUE) {
                            // echo json_encode(['status' => 'success', 'message' => 'Record updated successfully']);
                        } else {
                            // echo json_encode(['status' => 'error', 'message' => 'Error updating record: ' . $connection->error]);
                        }
                    }

                    function roundUpToNearestHundred($number)
                    {
                        return ceil($number / 100) * 100;
                    }

                    // include "../cal_pro_remain.php";
                    $sql = "SELECT * FROM $product WHERE product_name = ?";
                    $stmt = $connection->prepare($sql);
                    $stmt->bind_param('s', $product_name);
                    $stmt->execute();
                    $product_result = $stmt->get_result();

                    if ($product_result && $product_result->num_rows > 0) {
                        $product_row = $product_result->fetch_assoc();
                        $unit = $product_row['unit'];
                        $pieces = $product_row['pieces'];
                        $buy = $product_row['buy'];
                        $trans = $product_row['trans'];
                        $currency_buy = $product_row['currency_buy'];
                        $profit = $product_row['profit'];

                        // Fetch rate details (assumed to be a single record)
                        $sql_rate = "SELECT * FROM $rate";
                        $rate_result = $connection->query($sql_rate);

                        if ($rate_result && $rate_result->num_rows > 0) {
                            $rate_row = $rate_result->fetch_assoc();

                            $baht = $rate_row['baht'];
                            $yuan = $rate_row['yuan'];
                            $dollar = $rate_row['dollar'];

                            // Calculate package price based on currency
                            if ($currency_buy == 'kyat') {
                                $rate = '1';
                            } else if ($currency_buy == 'baht') {
                                $rate = $baht;
                            } else if ($currency_buy == 'yuan') {

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

                                $rate = $dollar;
                            }
                            $package_price = ($profit + $buy + $trans) * $rate;


                            // Calculate unit and pieces price
                            if ($unit > 0) {
                                $unit_price = $package_price / $unit;
                            } else {
                                $unit_price = 0; // or handle the zero case as needed
                            }

                            if ($pieces > 0 && $unit_price > 0) {
                                $pieces_price = $unit_price / $pieces;
                            } else {
                                $pieces_price = 0; // or handle the zero case as needed
                            }

                            // Round prices
                            $round_package_price = roundUpToNearestHundred($package_price);
                            $round_unit_price = roundUpToNearestHundred($unit_price);
                            $round_pieces_price = roundUpToNearestHundred($pieces_price);

                            // Update product tables
                            $product_tables = [$product, $cargo_1];
                            foreach ($product_tables as $product_data) {
                                $sql_update = "UPDATE $product_data 
                                        SET package_price = ?, 
                                            unit_price = ?, 
                                            pieces_price = ?, 
                                            round_package_price = ?, 
                                            round_unit_price = ?, 
                                            round_pieces_price = ? 
                                        WHERE product_name = ?";
                                $stmt_update = $connection->prepare($sql_update);
                                $stmt_update->bind_param('dddddds', $package_price, $unit_price, $pieces_price, $round_package_price, $round_unit_price, $round_pieces_price, $product_name);

                                if ($stmt_update->execute()) {
                                    echo json_encode(['status' => 'success', 'message' => 'Record updated successfully']);
                                    echo "<script>location.reload();</script>";
                                } else {
                                    echo json_encode(['status' => 'error', 'message' => 'Error updating record: ' . $connection->error]);
                                }
                            }
                        }
                    }
                } else {
                    // echo json_encode(['status' => 'error', 'message' => 'Invalid data format.']);
                }
            }
            ?>




            <!-- ရောင်းဈေးကို check ပြန်လုပ်ရန် -->
            <!-- Edit Data by click -->



            <script>
                //get colspan data
                function getFlattenedHeaders(headerRow) {
                    const headers = [];
                    let colIndex = 0;

                    for (let i = 0; i < headerRow.cells.length; i++) {
                        const cell = headerRow.cells[i];
                        const colspan = cell.colSpan || 1;
                        const headerText = cell.textContent.trim();

                        for (let j = 0; j < colspan; j++) {
                            headers[colIndex] = headerText;
                            colIndex++;
                        }
                    }

                    console.log('Flattened Headers:', headers);
                    return headers;
                }

                function saveChangesForRow(row) {
                    const data = {};
                    console.log('Row being processed:', row);

                    const headerRow = document.getElementById('dataTable').rows[0];
                    const headers = getFlattenedHeaders(headerRow);

                    for (let j = 0; j < row.cells.length; j++) {
                        const cell = row.cells[j];

                        if (j >= headers.length) {
                            console.warn(`Skipping cell ${j} as it exceeds header length`);
                            continue; // Skip if there are more cells in the row than in the headers
                        }

                        const headerText = headers[j];
                        console.log(`Processing cell ${j}: Header=${headerText}, Cell=`, cell);

                        if (cell && cell.hasAttribute('contenteditable')) {
                            data[headerText] = cell.textContent.trim();
                        }

                        // Handle select dropdowns separately
                        if (cell.querySelector('select')) {
                            data[headerText] = cell.querySelector('select').value;
                        }
                    }

                    console.log('Data to be sent:', data);

                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', 'product_add_new.php', true);
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                                console.log('Data updated successfully!');
                            } else {
                                // alert('Error updating data. Please try again!');
                            }
                        }
                    };
                    xhr.send(JSON.stringify(data));
                }

                const editableCells = document.querySelectorAll('#dataTable td[contenteditable="true"]');
                editableCells.forEach(cell => {
                    cell.addEventListener('input', function() {
                        saveChangesForRow(this.parentElement); // this.parentElement refers to the row
                    });
                });

                const dropdowns = document.querySelectorAll('#dataTable select');
                dropdowns.forEach(dropdown => {
                    dropdown.addEventListener('change', function() {
                        saveChangesForRow(this.closest('tr')); // 'closest' gets the nearest parent row element
                    });
                });
            </script>


            <a href="#" class="theme-toggle">
                <i class="fa-regular fa-moon"></i>
                <i class="fa-regular fa-sun"></i>
            </a>
            <footer class="footer">
                <div class="container-fluid">
                    <div class="row text-muted">
                        <div class="col-6 text-start">
                            <p class="mb-0">
                                <a href="#" class="text-muted">
                                    <?php
                                    include "version.php";
                                    ?>
                                </a>
                            </p>
                        </div>
                        <div class="col-6 text-end">
                            <ul class="list-inline">
                                <li class="list-inline-item">
                                    <a href="#" class="text-muted">Contact</a>
                                </li>
                                <li class="list-inline-item">
                                    <a href="#" class="text-muted">About Us</a>
                                </li>
                                <li class="list-inline-item">
                                    <a href="#" class="text-muted">Terms</a>
                                </li>
                                <li class="list-inline-item">
                                    <a href="#" class="text-muted">Booking</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </footer>
        </div>
    </div>

    <!-- Number Format -->
    <script>
        function formatNumber() {
            const inputField = document.getElementById('package_price');
            let value = inputField.value;

            // Remove any non-numeric characters (except for decimal points)
            value = value.replace(/[^0-9.]/g, '');

            // Format the number
            const formattedValue = new Intl.NumberFormat().format(value);

            // Set the formatted value back to the input field
            inputField.value = formattedValue;
        }
    </script>


    <!-- <script src="lat_li.js"></script> -->
    <!-- get data auto from input barcode/banking -->
    <!-- <script>
    document.addEventListener('DOMContentLoaded', (event) => {
const barcodeInput = document.getElementById('barcodeInput');
const bankingInput = document.getElementById('bankingInput');
const outputDiv = document.getElementById('output');

// Simulate a barcode scanner by listening for input events
barcodeInput.addEventListener('input', handleBarcodeInput);

let barcode = '';
let timeout;

function handleBarcodeInput(event) {
    clearTimeout(timeout);
    
    // Check for input data and append to barcode
    barcode += event.data || event.target.value; 
    
    // Clear the input field
    event.target.value = '';

    // Wait for a short period to determine if input is complete
    timeout = setTimeout(() => {
        processBarcode(barcode);
        barcode = ''; // Reset barcode
    }, 100); // Adjust timeout as needed
}

async function processBarcode(barcode) {
    // Get banking input value
    const bankingData = bankingInput.value;

    // Display the processed barcode and banking data on the page
    outputDiv.innerHTML = `Processed Barcode: ${barcode} <br> Banking Data: ${bankingData}`;
    console.log(`Processed Barcode: ${barcode}`);
    console.log(`Banking Data: ${bankingData}`);

    // Send the barcode and banking data to the server
    try {
        const response = await fetch('lat_li.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                barcode: barcode,
                bankingData: bankingData
            })
        });

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        const responseData = await response.json();
        console.log('Server response:', responseData);
    } catch (error) {
        console.error('Error sending data:', error);
    }
}
});
</script>
<div id="output"></div>


<?php
// header('Content-Type: application/json');
// $input = file_get_contents('php://input');
// $data = json_decode($input, true);

// if ($data && isset($data['barcode']) && isset($data['bankingData'])) {
//     // Process the barcode and banking data here
//     $barcode = $data['barcode'];
//     $bankingData = $data['bankingData'];

//     include 'database/database.php';

//     // Log received data for debugging purposes
//     error_log("Received barcode: " . $barcode);
//     error_log("Received bankingData: " . $bankingData);

//     $query = "UPDATE imv_account SET account='$barcode', amount='$bankingData' WHERE id='1'";
//     if ($connection->query($query)) {
//         // Example response
//         echo json_encode([
//             'status' => 'success', 
//             'receivedBarcode' => $barcode,
//             'receivedBankingData' => $bankingData
//         ]);
//     } else {
//         die("ERROR: Query failed. " . $connection->error);
//     }
// } else {
//     echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
// }


?> -->


    <?php

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

        return $randomString . $timestamp;
    }

    ?>





    <script src="js/script.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>

</html>