<!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_buy_shop.php";
include "login_check.php";


if (isset($_POST['add'])) {

    $name = $_POST['name'];
    $ph_no = $_POST['ph_no'];
    $address = $_POST['address'];
    $currency = $_POST['currency'];
    $total_buy = '0';
    $pay = '0';
    $payable = '0';


    $sql = "SELECT * FROM ".$supplier." where name='$name'";
    $result = $connection->query($sql);
    if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo '<script>alert("Already Exist") ;</script>';
        echo '<script>window.location = "product_buy_shop.php";</script>';
    }

    }else{
      $sql = "INSERT INTO ".$supplier." (name, ph_no, address,currency,total_buy,debt,pay_now,payable,pay_after)
      VALUES ('$name','$ph_no','$address','$currency','0','0','0','0','0')";

      if (mysqli_query($connection, $sql)) {
          header('location:product_buy_shop.php');
          echo '<script>alert("Add New Supplier Success") ;</script>';
          // echo "Insert successful";
      } else {
          
      }
    }
  }
    

  if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["id"])) {
    $id = $connection->real_escape_string($_POST["id"]);
    echo "Received id: " . $id;



        $query = "DELETE FROM ".$supplier." WHERE id = '$id'";
        if ($connection->query($query)) {
            header('location:product_buy_shop.php');
        } else {
            header('location:product_buy_shop.php');
        }


    }

?>

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


<body>
<div class="wrapper">
    <?php 
    include "database/database.php";
    include "database/data.php";
    include "sidebar.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">

                    <?php
$payable = ""; // Default value if form is not submitted
$voucher_data = ""; // Initialize voucher_data

if (isset($_POST['all']) || isset($_POST['add']) || isset($_POST['search'])) {
    $voucher_data = $_POST['voucher'];

    if (isset($_POST['all'])) {
        // SQL query to fetch the latest record
        $sql = "SELECT * FROM imv_voucher WHERE voucher_no = ?";
        $stmt = $connection->prepare($sql);

        if ($stmt === false) {
            die('Prepare failed: ' . htmlspecialchars($connection->error));
        }

        $stmt->bind_param("s", $voucher_data);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $payable = $row['payable'];
        } else {
            $payable = ""; // Default value if no record is found
        }

        $stmt->close();
    }
}
?>

<form action="product_buy_shop.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">ငွေကြေး:</label></th>
            <th>
                <select name="currency" id="bankingInput" class="form-control">
                    <option value="kyat">kyat</option>
                    <option value="baht">baht</option>
                    <option value="yuan">yuan</option>
                    <option value="dollar">dollar</option>
                </select>
            </th>
        </tr>


        <tr style="height: 50px;">
            <th><label for="pwd" alt="hi">ဆိုင်အမည်:</label></th>
            <th><input type="text" class="form-control" name="name" placeholder="" value="<?php echo htmlspecialchars($voucher_data); ?>"></th>
        </tr>

        <tr style="height: 50px;">
            <th><label for="pwd" alt="hi">ဖုန်းနံပါတ် :</label></th>
            <th><input type="text" class="form-control" name="ph_no" placeholder="" value="<?php echo htmlspecialchars($voucher_data); ?>"></th>
        </tr>

        <tr style="height: 50px;">
            <th><label for="pwd" alt="hi">လိပ်စာ:</label></th>
            <th><input type="text" class="form-control" name="address" placeholder="" value="<?php echo htmlspecialchars($voucher_data); ?>"></th>
        </tr>

        

        
    </table>
    <table class="table table-borderless">
        <tr>
            <td><button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;width:90%">ပေါင်းထည့်ရန်</button></td>
        </tr>
        <!-- <tr>
            <th scope="col"><button type="submit" name="search" class="btn btn-outline-danger" style="margin: 10px;width:90%">ရှာရန်</button></th>
        </tr> -->
    </table>
</form>

   


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

                <div class="card-header gx-5">
                    <form class="d-flex flex-row-reverse ">
                    <div class="col-auto" style="margin-left:10px">
                        <input type="text" class="form-control" id="searchInput" 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>

                    <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 scope="col">အမှတ်စဉ်</th>
                        <th scope="col">ဆိုင်အမည်</th>
                            <th scope="col">ဖုန်းနံပါတ်</th>
                            <th scope="col">လိပ်စာ</th>
                            <th scope="col">ငွေကြေး</th>
                            <th scope="col">ဝယ်အား</th> 
                            <th scope="col">ပေးရန်အကြွေး</th>
                            <th scope="col">ဝယ်ပြီးငွေချေ</th>
                            <th scope="col">ပြင်ပငွေချေ</th>
                            <th scope="col">ပေးရန်ကျန်ငွေ</th>          
                            <th scope="col">Delete</th>          
                        </tr>
                        </thead>
                            <tbody>
                                <?php 
                                $sql = "Select * from ".$supplier."";
                                $result = mysqli_query($connection, $sql);
                                if ($result) {
                                    while ($row = mysqli_fetch_assoc($result)) {
                                        echo '<tr>
                                        <td>' . $row['id']. '</td>
                                        <th scope="row" contenteditable="true" class="fixed-column">' . htmlspecialchars($row['name']) . '</th>       
                                        <td contenteditable="true" class="fixed-column">' . htmlspecialchars($row['ph_no']) . '</td>       
                                        <td contenteditable="true" class="fixed-column-2">' . htmlspecialchars($row['address']) . '</td>
                                        <td contenteditable="true" class="fixed-column-2">' . htmlspecialchars($row['currency']) . '</td>
                                        <td contenteditable="true" class="fixed-column-3">' . number_format($row['total_buy']) . '</td>
                                        <td contenteditable="true" class="fixed-column-3">' . number_format($row['debt']) . '</td>
                                        <td contenteditable="true" class="fixed-column-3">' . number_format($row['pay_now']) . '</td>
                                        <td contenteditable="true" class="fixed-column-3">' . number_format($row['pay_after']) . '</td>
                                        <td contenteditable="true" class="fixed-column-3">' . number_format($row['payable']) . '</td>
                                        <td><button type="submit" class="btn btn-success" onclick="deleteRow(this)">Delete</button></td>                            
                                        </tr>';
                                    }
                                }
                                    mysqli_free_result($result);
                                
                                ?>
                            </tbody>
                        </table>

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

                            <script>
                            function deleteRow(button) {
                            const row = button.parentNode.parentNode;
                            const id = row.cells[0].textContent; // Assuming the Product ID is in the first column (index 0)
                            console.log(id)
                            // Send the tra_id to the backend PHP script using AJAX for deletion
                            const xhr = new XMLHttpRequest();
                            xhr.open('POST', 'product_buy_shop.php', true);
                            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                            xhr.onreadystatechange = function() {
                                if (xhr.readyState === XMLHttpRequest.DONE) {
                                if (xhr.status === 200) {
                                    row.parentNode.removeChild(row); // Remove the row from the table on successful deletion
                                    alert('Data deleted successfully!');
                                    location.reload();

                                } else {
                                    alert('Error deleting data. Please try again.');
                                }
                                }
                            };
                            xhr.send('id=' + encodeURIComponent(id));
                            }
                        </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 -->


                    </div>
                </div>


            </div>
            </div>

        </main>


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