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

</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['update_data'])) {
    $barcode = $_POST['barcode'];
    $trans = $_POST['trans'];
    $buy = $_POST['buy'];
    $unit = $_POST['unit'];
    $pieces = $_POST['pieces'];
    $currency_buy = $_POST['currency_buy'];

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

    // 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();
        $profit = $rate_row['profit'];
        $baht = $rate_row['baht'];
        $yuan = $rate_row['yuan'];
        $dollar = $rate_row['dollar'];

        // Calculate prices based on the currency
        switch ($currency_buy) {
            case 'kyat':
                $package_price = ($buy * ($profit / 100)) + $buy + $trans;
                break;
            case 'baht':
                $package_price = (($buy * $baht) * ($profit / 100)) + ($buy * $baht) + $trans;
                break;
            case 'yuan':
                $package_price = (($buy * $yuan) * ($profit / 100)) + ($buy * $yuan) + $trans;
                break;
            case 'dollar':
                $package_price = (($buy * $dollar) * ($profit / 100)) + ($buy * $dollar) + $trans;
                break;
            default:
                echo json_encode(['status' => 'error', 'message' => 'Invalid currency']);
                exit;
        }

        $unit_price = $package_price / $unit;
        $pieces_price = $unit_price / $pieces;

        // 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_view.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 ".$cargo_1." 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">
                                <img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" class="img-fluid mb-3" alt="Sample Image" style="margin-left:auto;margin-right:auto;">
                                    </div>
                                    <form action="product_view.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" 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 ".$cargo_1." WHERE id ='$id'";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $product_name = $row['product_name'];

                    $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!");';
                                }
                        }

                
                }
            }


            


            break;

        default:
            
    }
} else {
  
}

if (isset($_POST['search'])) {
    $product_type = $_POST['product_type'];
    

    $sql = "UPDATE $catagories SET active='1' WHERE type='$product_type'";
    if (!$connection->query($sql)) {
  
    }

    $sql = "UPDATE $catagories SET active='0' WHERE type!='$product_type'";
    if (!$connection->query($sql)) {
        // Log error or handle it appropriately
       
    }
   

}


?>

<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">

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

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

                    <form class="d-flex flex-row-reverse" action="product_view.php" method="POST" >

                    <div class="col-auto" style="margin-left:10px;margin-right:10px">
                        <input type="text" class="form-control" id="searchInput" placeholder="Search">
                    </div>

                    <div class="col-auto" style="margin-left:10px">
                    <!-- <select name="product_type" id="accountInput" onchange="filterTable()" class="form-control"> -->
                    <select name="product_type" id="accountInput" class="form-control">
                                <?php
                                $sql = "SELECT * FROM ".$catagories."";
                                $result = $connection->query($sql);
                                if ($result && $result->num_rows > 0) {
                                    while ($row = $result->fetch_assoc()){
                                        $account = $row['type']; // Database
                                        echo '<option value="' . $account . '">' . $account . '</option>';
                                    }
                                }
                                ?>
                            </select>
               
                    </div>

                    <div class="col-auto" style="margin-left:10px">
                        <button type="submit" class="btn btn-primary mb-3"  name="search">Search</button>
                    </div>

                    <div class="col-auto" style="margin-left:10px">
                        <button type="submit" class="btn btn-success mb-3" onclick="refreshPage()">Refresh</button>
                    </div>

                    

                    </form> 
                    </div>

                    <div class="scrollable-table" style="height:60vh;">
                        <table class="table table-bordered table-hover" style="color:white;font-size:18px;"  id="dataTable">
                        <thead style="background-color:#19242e" class="text-center align-middle">
                        <tr>
                            <th rowspan="2" scope="col">no</th>
                            <th rowspan="2" scope="col">update</th>
                            <th rowspan="2" scope="col">barcode</th>
                            <!-- <th rowspan="2" scope="col" style="display:none;">barcode_2</th> -->
                            <th rowspan="2" scope="col">barcode_2</th>
                            <th rowspan="2" scope="col">ပစ္စည်းအမည်</th>
                            <th rowspan="2" scope="col">အမျိုးအစား</th>
                            <th rowspan="2" scope="col">သယ်ဆောင်ခ</th>
                   
                            
                            <th rowspan="2" scope="col" style="color:#ACE1AF">မူရင်းကဒ်</th>
                            <th rowspan="2" scope="col" style="color:#ACE1AF">မူရင်းဗူး</th>
                            <th rowspan="2" scope="col">ဖာလိုက်ဝယ်ဈေး</th>

                            <!-- <th rowspan="2" scope="col" style="color:#ACE1AF">ငွေဈေး</th> -->
                            <th rowspan="2" scope="col" >ငွေအမျိုးစား</th>

                            <th colspan="3" scope="col" style="color:#FFA62F">ရောင်းဈေး</th>
                            <th colspan="3" scope="col" style="color:#42f560">လက်ကျန်</th>
                            <th colspan="3" scope="col" style="color:#00ffbb">ပစ္စည်းဖြည့်</th>
                            <th colspan="3" scope="col" style="color:#fff41c">လက်ခံ</th>
                            <th colspan="3" scope="col" style="color:#0866ff">ရောင်းပီး</th>
                            <th colspan="3" scope="col" style="color:#ff0d41">ပျက်စီး</th>
                            <th rowspan="2" scope="col" style="color:red">Delete</th>
                        </tr>
                        <tr>
                            <th scope="col" style="color:#FFA62F">ဖာ</th>
                            <th scope="col" style="color:#FFA62F">ကဒ်</th>
                            <th scope="col" style="color:#FFA62F">ဗူး</th>
                       
                            <th scope="col" style="color:#42f560">ဖာ</th>
                            <th scope="col" style="color:#42f560">ကဒ်</th>
                            <th scope="col" style="color:#42f560">ဗူး</th>

                            <th scope="col" style="color:#00ffbb">ဖာ</th>
                            <th scope="col" style="color:#00ffbb">ကဒ်</th>
                            <th scope="col" style="color:#00ffbb">ဗူး</th>

                            <th scope="col" style="color:#fff41c">ဖာ</th>
                            <th scope="col" style="color:#fff41c">ကဒ်</th>
                            <th scope="col" style="color:#fff41c">ဗူး</th>
                       
                            <th scope="col" style="color:#0866ff">ဖာ</th>
                            <th scope="col" style="color:#0866ff">ကဒ်</th>
                            <th scope="col" style="color:#0866ff">ဗူး</th>

                            <th scope="col" style="color:#ff0d41">ဖာ</th>
                            <th scope="col" style="color:#ff0d41">ကဒ်</th>
                            <th scope="col" style="color:#ff0d41">ဗူး</th>
                        </tr>
                        
                        </thead>
                            <tbody>
                                <?php 
                                $sql = "SELECT * FROM  $catagories where active='1'";
                                $result = $connection->query($sql);
        
                                if ($result->num_rows > 0) {
                                    while ($row = $result->fetch_assoc()) {
                                        $type = $row['type'];


                                        $sql = "Select * from ".$cargo_1." where delete_d='0' and type='$type' order by id desc";
                                        $result = mysqli_query($connection, $sql);
                                        if ($result) {
                                            while ($row = mysqli_fetch_assoc($result)) {
                                                echo '<tr>
                                                <td contenteditable="true" class="fixed-column">' . htmlspecialchars($row['id']) . '</td>       
                                                <td><button type="button" class="btn btn-success" data-action="info" name="info" data-toggle="modal" data-target="#infoModal">update</button></td>     
                                                <td contenteditable="true" class="fixed-column-2">' . htmlspecialchars($row['barcode']) . '</td>
                                                <td contenteditable="true" class="fixed-column-2">' . htmlspecialchars($row['barcode_1']) . '</td>
                                                <th scope="row" contenteditable="true" class="fixed-column-3">' . htmlspecialchars($row['product_name']) . '</th>

                                                <td class="fixed-column-3" contenteditable="true">' . htmlspecialchars($row['type']) . '</td>  
                                                                                    
                                                <td contenteditable="true">' . htmlspecialchars($row['trans']) . '</td>      
                                                <td contenteditable="true">' . htmlspecialchars($row['unit']) . '</td>
                                                <td contenteditable="true">' . htmlspecialchars($row['pieces']) . '</td>      
                                                <td contenteditable="true">' . number_format($row['buy']) . '</td>';

                                                // echo '<td contenteditable="true">' . htmlspecialchars($row['rate']) . '</td>';

                                                echo '<td contenteditable="true">
                                                    <select id="cars" contenteditable="true">
                                                        <option value="' . $row['currency_buy'] . '">' . $row['currency_buy'] . '</option>
                                                        <option value="kyat">kyat</option>
                                                        <option value="baht">baht</option>
                                                        <option value="yuan">yuan</option>
                                                    </select></td>'; 
                                            

                                                echo '
                                                <td  style="color:#FFA62F">' . number_format($row['round_package_price']) . '</td>
                                                <td  style="color:#FFA62F">' . number_format($row['round_unit_price']) . '</td>
                                                <td  style="color:#FFA62F">' . number_format($row['round_pieces_price']) . '</td>';  
                                                
                                                echo '
                                                <td style="color:#42f560">' . number_format($row['package_exist']) . '</td>
                                                <td style="color:#42f560">' . number_format($row['unit_exist']) . '</td>
                                                <td style="color:#42f560">' . number_format($row['pieces_exist']) . '</td>';   

                                                echo '
                                                <td style="color:#00ffbb">' . number_format($row['package_remain']) . '</td>
                                                <td style="color:#00ffbb">' . number_format($row['unit_remain']) . '</td>
                                                <td style="color:#00ffbb">' . number_format($row['pieces_remain']) . '</td>';  

                                                echo '
                                                <td style="color:#fff41c">' . number_format($row['package_trans']) . '</td>
                                                <td style="color:#fff41c">' . number_format($row['unit_trans']) . '</td>
                                                <td style="color:#fff41c">' . number_format($row['pieces_trans']) . '</td>';  

                                                echo '
                                                <td style="color:#0866ff">' . number_format($row['package_sell']) . '</td>
                                                <td style="color:#0866ff">' . number_format($row['unit_sell']) . '</td>
                                                <td style="color:#0866ff">' . number_format($row['pieces_sell']) . '</td>';  

                                                echo '
                                                <td style="color:#ff0d41">' . number_format($row['package_damage']) . '</td>
                                                <td style="color:#ff0d41">' . number_format($row['unit_damage']) . '</td>
                                                <td style="color:#ff0d41">' . number_format($row['pieces_damage']) . '</td>';  
                                                
                                                echo'<td><button type="submit" class="btn btn-danger" data-action="delete">Delete</button></td>                            
                                                </tr>';
                                            }
                                        }
                                           

                                    }
                                }
                                mysqli_free_result($result);
                             

                                    

                                



                                
                                
                                ?>
                            </tbody>
                        </table>

                        <form id="actionForm" method="POST" action="product_view.php" style="display:none;">
                                <input type="hidden" name="id" id="formId">
                                <input type="hidden" name="action" id="formAction">
                            </form>

                            <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_view.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 src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

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


                       

        <!-- ရောင်းဈေးကို check ပြန်လုပ်ရန် -->
        <!-- Edit Data by click -->
        <?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['ဖာလိုက်ဝယ်ဈေး']);
                // $rate = $connection->real_escape_string($data['ငွေဈေး']);
                $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);

                $sql = "SELECT * FROM ".$catagories." where type='$type'";
                $result = $connection->query($sql);
                if ($result && $result->num_rows > 0) {

                    $product_tables = [$product,$cargo_1];

                    foreach ($product_tables as $product_data) {
                
                    $sql = "UPDATE ".$product_data." SET type='$type',unit='$unit',pieces='$pieces',buy='$buy',trans='$trans',currency_buy='$currency_buy' WHERE product_name='$product_name'";
                    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]);
                    }
                }
        }
                
                // include "../cal_pro_remain.php";
    
                function roundUpToNearestHundred($number) {
                    return ceil($number / 100) * 100;
                    }
        
                    // Fetch product details
                // 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) {
    $product_row = $product_result->fetch_assoc();
    $unit = $product_row['unit'];
    $pieces = $product_row['pieces'];
    $buy = $product_row['buy'];
    $trans = $product_row['trans'];

    // 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();
        $profit = $rate_row['profit'];
        $baht = $rate_row['baht'];
        $yuan = $rate_row['yuan'];
        $dollar = $rate_row['dollar'];

        // Calculate package price based on currency
        switch ($currency_buy) {
            case 'kyat':
                $package_price = ($buy * ($profit / 100)) + $buy + $trans;
                break;
            case 'baht':
                $package_price = (($buy * $baht) * ($profit / 100)) + ($buy * $baht) + $trans;
                break;
            case 'yuan':
                $package_price = (($buy * $yuan) * ($profit / 100)) + ($buy * $yuan) + $trans;
                break;
            case 'dollar':
                $package_price = (($buy * $dollar) * ($profit / 100)) + ($buy * $dollar) + $trans;
                break;
            default:
                echo json_encode(['status' => 'error', 'message' => 'Invalid currency']);
                exit;
        }

        // Calculate unit and pieces price
        $unit_price = $package_price / $unit;
        $pieces_price = $unit_price / $pieces;

        // 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.']);
            }
            
            }
        ?>
        <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_view.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>



                    </div>
                </div>


            </div>
            </div>
        </main>

        <script>
    // Call filterTable immediately after the page loads
    window.onload = function() {
        filterTable(); // Automatically filters based on the first option selected
    };
</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>



<?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>
