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

    <link rel="stylesheet" href="extensions/fixed-columns/bootstrap-table-fixed-columns.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="extensions/fixed-columns/bootstrap-table-fixed-columns.js"></script>
</head>
<style>
        .image-container {
            width: 200px; /* Adjust this width as needed */
            height: 200px; /* Adjust this height as needed */
            overflow: hidden;
            position: relative;
            border: 1px solid #ccc; /* Add a border for the frame effect */
        }
        .image-container img {
            width: 100%;
            height: 100%;
            object-fit: contain; /* Ensure the entire image is visible */
        }
    </style>



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


    <style>
    .select-container {
        position: relative;
        display: inline-block;
    }
    .select-container select {
        appearance: none;
        -webkit-appearance: none;
        -moz-appearance: none;
        padding-right: 30px; /* Adjust this based on your icon size */
    }
    .select-container .fa-chevron-down {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        pointer-events: none; /* Allows clicking through the icon to the select element */
    }
</style>


<body>
    <div class="wrapper">
        <?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="mb-3" style="position: relative;">
                
                    
                </div>


                <div class="row">
    <!-- Table Element -->
    <div class="container-fluid">
        <div class="container-fluid" style="margin-bottom: 20px;">
            <form>
                <div class="row">

                    <div class="col-sm-2 mb-2">
                        <div class="select-container">
                            <select name="product_type" id="accountInput" onchange="filterTable()" 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>
                            <i class="fas fa-chevron-down"></i>
                        </div>
                    </div>

                    <div class="col-sm-2">
                        <div class="select-container">
                            <button type="submit" class="btn btn-outline-success" onclick="refreshPage()">Show All</button>
                        </div>
                    </div>

                </div>
            </form>
        </div>

        <!-- Table Section -->
        <div class="scrollable-table" style="height:70vh;">
            <table class="table table-bordered table-hover" style="color:white;font-size:18px;" id="dataTable">
                <thead style="background-color:#19242e">
                    <tr>
                        <th class="data-fixed-columns" scope="col">id</th>
                        <th scope="col">barcode</th>
                        <th scope="col">barcode_1</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" style="color:#42f560">ရောင်းဈေး(ဖာ)</th>
                        <th scope="col" style="color:#42f560">ရောင်းဈေး(ကဒ်)</th>
                        <th scope="col" style="color:#42f560">ရောင်းဈေး(ဗူး)</th>

                        <th scope="col" style="color:#ffaa0d">လက်ကျန်(ဖာ)</th>
                        <th scope="col" style="color:#ffaa0d">လက်ကျန်(ကဒ်)</th>
                        <th scope="col" style="color:#ffaa0d">လက်ကျန်(ဗူး)</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 ".$product." where delete_d='0'";
                    $result = mysqli_query($connection, $sql);
                    if ($result) {
                        while ($row = mysqli_fetch_assoc($result)) {
                            echo '<tr>
                            <td>' . $row['id']. '</td>
                            <td>' . $row['barcode']. '</td>
                            <td>' . $row['barcode_1']. '</td>
                            <th scope="row" display="none">' . $row['product_name'] . '</th>
                            <td scope="row">' . $row['product_name'] . '</td>
                            <td contenteditable="true">' . $row['type'] . '</td>
                            <td contenteditable="true" style="width:20px">' . $row['unit'] . '</td>
                            <td contenteditable="true">' . $row['pieces'] . '</td>
                            <td contenteditable="true">' . number_format($row['buy']).'</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>
                                <option value="dollar">dollar</option>
                            </select></td>'; 

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

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

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

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

                            <td style="color:#ff0d41">' .  $row['package_damage'] . '</td>                                                
                            <td style="color:#ff0d41">' .  $row['unit_damage'] . '</td>                                                
                            <td style="color:#ff0d41">' .  $row['pieces_damage'] . '</td>                                                                                    
                            </tr>';
                        }
                        mysqli_free_result($result);
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Script to Filter and Refresh -->
    <script>
        function refreshPage() {
            location.reload();
        }

        function filterTable() {
            var accountInput, filterAccount, table, tr, tdAccount, i;
            accountInput = document.getElementById("accountInput");
            filterAccount = accountInput.value.toUpperCase(); // Get selected value and convert to uppercase
            table = document.getElementById("dataTable");
            tr = table.getElementsByTagName("tr");

            console.log("Filter Account: ", filterAccount); // Debugging log

            // Loop through all table rows (except the header)
            for (i = 1; i < tr.length; i++) { // Start from 1 to skip the header row
                tdAccount = tr[i].getElementsByTagName("td")[4]; // Account column (5th column, index 4)

                if (tdAccount) {
                    // Check if the account matches the filter
                    console.log("Row " + i + " Account: " + tdAccount.textContent); // Debugging log
                    if (tdAccount.textContent.toUpperCase().indexOf(filterAccount) > -1 || filterAccount === "") {
                        tr[i].style.display = ""; // Show the row
                    } else {
                        tr[i].style.display = "none"; // Hide the row
                    }
                }
            }
        }

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

    
</div>


                </div>
            </main>

            <!-- Add this script after your form -->
<script>
    // Call filterTable immediately after the page loads
    window.onload = function() {
        filterTable(); // Automatically filters based on the first option selected
    };
</script>

<?php 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    if ($data) {
        // Process data and update your database
        // Example: $data['HeaderText'] will access the relevant field
    } else {
        http_response_code(400); // Bad Request
        echo json_encode(["message" => "Invalid data received"]);
    }
}

?>

        <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[  ]');
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>
    

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