
<?php
date_default_timezone_set('Asia/Ho_Chi_Minh');
include 'connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bang = $_POST['bang'] ?? '';
    $edit_id = isset($_POST['edit_id']) ? intval($_POST['edit_id']) : 0;
    $nhap_30L = isset($_POST['nhap_30L']) ? intval($_POST['nhap_30L']) : 0;
    $nhap_50L = isset($_POST['nhap_50L']) ? intval($_POST['nhap_50L']) : 0;
    $xuat_30L = isset($_POST['xuat_30L']) ? intval($_POST['xuat_30L']) : 0;
    $xuat_50L = isset($_POST['xuat_50L']) ? intval($_POST['xuat_50L']) : 0;
    $nguoi_giao = isset($_POST['nguoi_giao']) ? $conn->real_escape_string($_POST['nguoi_giao']) : '';

    if ($edit_id > 0 && $bang !== '') {
        $sql_get_date = "SELECT ngay FROM $bang WHERE id=$edit_id";
        $result_date = $conn->query($sql_get_date);
        if ($result_date && $result_date->num_rows > 0) {
            $row_date = $result_date->fetch_assoc();
            $edit_ngay = $row_date['ngay'];
            $sql_get_prev = "SELECT ton_30L, ton_50L FROM $bang WHERE ngay < '$edit_ngay' ORDER BY ngay DESC LIMIT 1";
            $result_prev = $conn->query($sql_get_prev);
            if ($result_prev && $result_prev->num_rows > 0) {
                $row_prev = $result_prev->fetch_assoc();
                $prev_ton_30L = intval($row_prev['ton_30L']);
                $prev_ton_50L = intval($row_prev['ton_50L']);
            } else {
                $prev_ton_30L = 0;
                $prev_ton_50L = 0;
            }

            $ton_30L_new = $prev_ton_30L + $nhap_30L - $xuat_30L;
            $ton_50L_new = $prev_ton_50L + $nhap_50L - $xuat_50L;

            $sql_update = "UPDATE $bang SET nhap_30L=$nhap_30L, nhap_50L=$nhap_50L, 
                xuat_30L=$xuat_30L, xuat_50L=$xuat_50L, ton_30L=$ton_30L_new, ton_50L=$ton_50L_new, nguoi_giao='$nguoi_giao'
                WHERE id=$edit_id";
            $conn->query($sql_update);
            $sql_following = "SELECT id, nhap_30L, nhap_50L, xuat_30L, xuat_50L FROM $bang WHERE ngay > '$edit_ngay' ORDER BY ngay ASC";
            $result_following = $conn->query($sql_following);

            $last_ton_30L = $ton_30L_new;
            $last_ton_50L = $ton_50L_new;

            while ($row = $result_following->fetch_assoc()) {
                $id_follow = $row['id'];
                $nhap_30L_f = intval($row['nhap_30L']);
                $nhap_50L_f = intval($row['nhap_50L']);
                $xuat_30L_f = intval($row['xuat_30L']);
                $xuat_50L_f = intval($row['xuat_50L']);

                $ton_30L_f = $last_ton_30L + $nhap_30L_f - $xuat_30L_f;
                $ton_50L_f = $last_ton_50L + $nhap_50L_f - $xuat_50L_f;

                $conn->query("UPDATE $bang SET ton_30L=$ton_30L_f, ton_50L=$ton_50L_f WHERE id=$id_follow");

                $last_ton_30L = $ton_30L_f;
                $last_ton_50L = $ton_50L_f;
            }
        }
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bang = $_POST['bang'] ?? '';
    $edit_id = isset($_POST['edit_id']) ? intval($_POST['edit_id']) : 0;
    $nhap_30L = isset($_POST['nhap_30L']) ? intval($_POST['nhap_30L']) : 0;
    $nhap_50L = isset($_POST['nhap_50L']) ? intval($_POST['nhap_50L']) : 0;
    $xuat_30L = isset($_POST['xuat_30L']) ? intval($_POST['xuat_30L']) : 0;
    $xuat_50L = isset($_POST['xuat_50L']) ? intval($_POST['xuat_50L']) : 0;
    $nguoi_giao = isset($_POST['nguoi_giao']) ? $conn->real_escape_string($_POST['nguoi_giao']) : '';

    if ($edit_id > 0 && $bang !== '') {
    } elseif ($edit_id == 0 && $bang !== '') {
        $sql_get_last = "SELECT ton_30L, ton_50L FROM $bang ORDER BY ngay DESC LIMIT 1";
        $result_last = $conn->query($sql_get_last);
        if ($result_last && $result_last->num_rows > 0) {
            $row_last = $result_last->fetch_assoc();
            $last_ton_30L = intval($row_last['ton_30L']);
            $last_ton_50L = intval($row_last['ton_50L']);
        } else {
            $last_ton_30L = 0;
            $last_ton_50L = 0;
        }

        $ton_30L_new = $last_ton_30L + $nhap_30L - $xuat_30L;
        $ton_50L_new = $last_ton_50L + $nhap_50L - $xuat_50L;
        $now = date('Y-m-d H:i:s');
        $sql_insert = "INSERT INTO $bang (ngay, nhap_30L, nhap_50L, xuat_30L, xuat_50L, ton_30L, ton_50L, nguoi_giao)
                       VALUES ('$now', $nhap_30L, $nhap_50L, $xuat_30L, $xuat_50L, $ton_30L_new, $ton_50L_new, '$nguoi_giao')";
        $conn->query($sql_insert);
    }
}

$filter_date = $_GET['filter_date'] ?? null;
$filter_bang = $_GET['filter_bang'] ?? null;

function get_rows($conn, $table, $filter_bang, $filter_date) {
    if ($filter_bang === $table && $filter_date) {
        return $conn->query("SELECT * FROM $table WHERE DATE(ngay) = '$filter_date' ORDER BY ngay ASC");
    } else {
        $sql = "
            SELECT * FROM (
                SELECT * FROM $table ORDER BY ngay DESC LIMIT 2
            ) AS sub
            ORDER BY ngay ASC
        ";
        return $conn->query($sql);
    }
}
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $bang = $_GET['bang'] ?? '';

    if ($delete_id > 0 && $bang !== '') {
        $sql_delete = "DELETE FROM $bang WHERE id = $delete_id";
        if ($conn->query($sql_delete)) {
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error']);
        }
    }
    exit;
}

$result_hongha = get_rows($conn, 'bang_nhap_xuat_hongha', $filter_bang, $filter_date);
$result_new = get_rows($conn, 'bang_nhap_xuat_new', $filter_bang, $filter_date);










if (isset($_POST['ton_30L_hn']) || isset($_POST['ton_30L_new'])) {
    date_default_timezone_set('Asia/Ho_Chi_Minh');
    $ngay = date('Y-m-d H:i:s'); // Ngày + giờ hiện tại

    // --- HÀ NỘI ---
    if ($_POST['ton_30L_hn'] !== '' || $_POST['ton_50L_hn'] !== '') {
        $ton_30L = intval($_POST['ton_30L_hn']);
        $ton_50L = intval($_POST['ton_50L_hn']);

        $sql_hn = "
            INSERT INTO bang_nhap_xuat_hongha
            (ngay, nhap_30L, nhap_50L, xuat_30L, xuat_50L, ton_30L, ton_50L, nguoi_giao)
            VALUES ('$ngay', 0, 0, 0, 0, $ton_30L, $ton_50L, 'Tồn nhanh')
            ON DUPLICATE KEY UPDATE ton_30L = VALUES(ton_30L), ton_50L = VALUES(ton_50L)
        ";

        if (!$conn->query($sql_hn)) {
            echo "<p style='color:red;'>Lỗi Hà Nội: " . $conn->error . "</p>";
        }
    }

    // --- NEW ---
    if ($_POST['ton_30L_new'] !== '' || $_POST['ton_50L_new'] !== '') {
        $ton_30L_new = intval($_POST['ton_30L_new']);
        $ton_50L_new = intval($_POST['ton_50L_new']);

        $sql_new = "
            INSERT INTO bang_nhap_xuat_new
            (ngay, nhap_30L, nhap_50L, xuat_30L, xuat_50L, ton_30L, ton_50L, nguoi_giao)
            VALUES ('$ngay', 0, 0, 0, 0, $ton_30L_new, $ton_50L_new, 'Tồn nhanh')
            ON DUPLICATE KEY UPDATE ton_30L = VALUES(ton_30L), ton_50L = VALUES(ton_50L)
        ";

        if (!$conn->query($sql_new)) {
            echo "<p style='color:red;'>Lỗi NEW: " . $conn->error . "</p>";
        }
    }

    // Sau khi thêm xong, reload lại trang để cập nhật bảng
    echo "<script>window.location.href = window.location.href;</script>";
    exit;
}









?>


<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Tính Tồn Kho</title>
<style>
body {
    font-family: Arial, sans-serif;
    font-size: 16px;
    padding: 10px;
    margin: 0;
    background-color: #f9f9f9;
}

h2 {
    text-align: center;
    font-size: 5vw;

}

.table-wrapper {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

table {
    border-collapse: collapse;
    width: 100%;
    min-width: 500px;
    background-color: white;
    margin-bottom: 30px;
    table-layout: fixed;
    z-index: 1;
}

th, td {
    border: 2px solid black;
    padding: 6px 8px;
    text-align: center;
    font-size: 2vw; /* tự co chữ */
    white-space: nowrap;
    
}

button {
    font-size: 5vw;
    padding: 2px 2px;
    width: auto;
}

td[data-label="Ngày"] {
    font-size: 35px;
}
td[data-label="Nhập 30L"] {
    font-size: 50px;
}
td[data-label="Nhập 50L"] {
    font-size: 50px;
}
td[data-label="Xuất 30L"] {
    font-size: 50px;
}
td[data-label="Xuất 50L"] {
    font-size: 50px;
}
td[data-label="Tồn 30L"] {
    font-size: 50px;
}
td[data-label="Tồn 50L"] {
    font-size: 50px;
}
td[data-label="Người giao"] {
    font-size: 40px;
}

button.btn-edit, button.btn-edit-new {
  display: none;
}

.nguoi-giao {
    font-size: 35px;
    color: red;
    font-weight: bold;
    text-align: center;
    display: none;
    margin-bottom: -25px;
}

.picker-container {
    width: 600px;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 20px;
    position: absolute;
    margin-top: 175px;
    left: 50%;
    transform: translateX(-50%);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
    display: none;
    z-index: 9999;
    border: 2px solid #e1e1e1;
    
}

.numbers {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

}

.number-button {
    background-color: #f4f4f4;
    border: 1px solid #ddd;
    border-radius: 25px;
    font-size: 50px;
    cursor: pointer;
    transition: background-color 0.3s ease, transform 0.3s ease;
    width: 110px;
    height: 100px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    margin: 5px;
}

.numbers .number-button:nth-child(5n) {
    margin-right: 0;
}

.number-button:hover {
    background-color: #69a2ff;
    color: white;
    transform: scale(1.1);
}

.pagination {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
    width: 100%;
}

.pagination button {
    padding: 12px;
    background-color: #4CAF50;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 56px;
    transition: background-color 0.3s ease;
    flex-grow: 1;
    margin: 0 5px;
}

.pagination button:hover {
    background-color: #45a049;
}

.pagination button:disabled {
    background-color: #ddd;
    cursor: not-allowed;
}

.close-button {
    width: 100%;
    padding: 12px;
    background-color: red !important;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    margin-top: 10px;
    font-size: 16px;
    transition: background-color 0.3s ease;
}

.close-button:hover {
    background-color: #ff4040 !important;
}

.navigate-button {
    padding: 12px;
    background-color: #4CAF50;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s ease;
}

.navigate-button:hover {
    background-color: #45a049;
}

.navigate-button:disabled {
    background-color: #ddd;
    cursor: not-allowed;
}

input[type="text"], input[type="number"] {
    font-size: 5vw;
    padding: 0px;
    width: 100%;
    max-width: 100px;
    box-sizing: border-box;
    color: red;
    text-align: center; 
}

input[type="text"]:focus, input[type="number"]:focus {
    border-color: #69a2ff;
    outline: none;
}

#numbers .label {
    font-weight: bold;
    margin-bottom: 10px;
    text-align: center;
    font-size: 4vw;
}

td.editable-select,
td.editable-select_new {
    display: none; 
}
#btn-submit, #btn-cancel {
    font-size: 50px;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
}

#btn-submit:hover, #btn-cancel:hover {
    background-color: #f0f0f0;
}

#btn-submit-new, #btn-cancel-new {
    font-size: 50px;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
}

#btn-submit-new:hover, #btn-cancel-new:hover {
    background-color: #f0f0f0;
}


#btn-submit-ton-nhanh {
    font-size: 50px;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
}

#btn-submit-ton-nhanh:hover {
    background-color: #f0f0f0;
}

/* Nút xóa */
.btn-delete {
    background-color: #f44336;
    color: white;
    border: none;
    padding: 5px 10px;
    cursor: pointer;
    font-size: 33px; 
    border-radius: 4px; 
    display: none;
    transition: background-color 0.3s ease;
    margin-top: -90px;
}

/* Khi hover vào nút xóa */
.btn-delete:hover {
    background-color: #d32f2f;
}

.btn-delete[style*="display: none;"] {
    display: none !important;
}

</style>

</head>
<body>
<div class="picker-container" id="picker-container" style="display: none;">
    <div id="numbers" class="numbers"></div> <!-- Chứa các nút số -->
    <div class="pagination">
        <button id="previous-page" class="navigate-button" disabled>◀️</button>
        <button class="close-button" id="close-picker">Đóng</button>
        <button id="next-page" class="navigate-button">▶️</button>
    </div>
</div>
<script>
let currentPage = 1; 
const numbersPerPage = 50;
let targetInput = null;
let nhanLabels = {
    'nhap_30L': 'Chọn Nhập 30L - Hồng Hà',
    'nhap_50L': 'Chọn Nhập 50L - Hồng Hà',
    'xuat_30L': 'Chọn Xuất 30L - Hồng Hà',
    'xuat_50L': 'Chọn Xuất 50L - Hồng Hà',
    'nhap_30L_new': 'Chọn Nhập 30L - NEW',
    'nhap_50L_new': 'Chọn Nhập 50L - NEW',
    'xuat_30L_new': 'Chọn Xuất 30L - NEW',
    'xuat_50L_new': 'Chọn Xuất 50L - NEW',
    'ton_30L_hn': 'Chọn Tồn 30L - Hà Nội',
    'ton_50L_hn': 'Chọn Tồn 50L - Hà Nội',
    'ton_30L_new': 'Chọn Tồn 30L - NEW',
    'ton_50L_new': 'Chọn Tồn 50L - NEW'
};

function updateNumberButtons() {
    const startNumber = (currentPage - 1) * numbersPerPage + 1;
    const endNumber = currentPage * numbersPerPage;
    const buttonsContainer = document.getElementById("numbers");
    buttonsContainer.innerHTML = ""; 
    const labelText = nhanLabels[targetInput.id] || 'Chọn số';
    const labelElement = document.createElement("div");
    labelElement.classList.add("label");
    labelElement.textContent = labelText;
    buttonsContainer.appendChild(labelElement);
    const numberContainer = document.createElement("div");
    numberContainer.classList.add("number-container");

    for (let i = startNumber; i <= endNumber; i++) {
        const button = document.createElement("button");
        button.classList.add("number-button");
        button.textContent = i;
        button.addEventListener("click", function() {
            targetInput.value = i;
            closeNumberPicker();
        });
        numberContainer.appendChild(button);
    }

    buttonsContainer.appendChild(numberContainer);
    document.getElementById("previous-page").disabled = (currentPage === 1);
    document.getElementById("next-page").disabled = (currentPage === 2);
}

function showNumberPicker(inputId) {
    targetInput = document.getElementById(inputId);
    currentPage = 1;
    document.getElementById("picker-container").style.display = "block"; 
    updateNumberButtons();
}

function goToPreviousPage() {
    if (currentPage > 1) {
        currentPage--;
        updateNumberButtons();
    }
}

function goToNextPage() {
    if (currentPage < 2) {
        currentPage++;
        updateNumberButtons();
    }
}

function closeNumberPicker() {
    document.getElementById("picker-container").style.display = "none";
}

document.querySelectorAll('input[type="text"][readonly]').forEach(input => {
    input.addEventListener("click", function() {
        showNumberPicker(input.id);
    });
});

document.getElementById("close-picker").addEventListener("click", closeNumberPicker);
document.getElementById("previous-page").addEventListener("click", goToPreviousPage);
document.getElementById("next-page").addEventListener("click", goToNextPage);

document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll('input[type="text"][readonly]').forEach(input => {
        input.addEventListener("click", function() {
            showNumberPicker(input.id);
        });
    });
});


</script>

<p id="dateTime" style="text-align: center; font-size: 40px; font-weight: bold; margin: 5px 0;"></p>

<script>
function updateDateTime() {
    const now = new Date();

    let hours = now.getHours();
    let minutes = now.getMinutes();
    const day = now.getDate();
    const month = now.getMonth() + 1; // Tháng bắt đầu từ 0
    const year = now.getFullYear();

    // Xác định sáng/chiều
    const ampm = hours >= 12 ? "Chiều" : "Sáng";

    // Chuyển về 12h format
    hours = hours % 12;
    hours = hours ? hours : 12; // 0 -> 12

    // Định dạng số có 2 chữ số
    const hh = hours.toString().padStart(2, "0");
    const mm = minutes.toString().padStart(2, "0");

    // Ghép chuỗi với màu sắc
    const formatted = `
        <span style="color:black;">Thời gian:</span> 
        <span style="color:red;">${hh}:${mm}</span> (${ampm}) - 
        <span style="color:black;">Ngày:</span> 
        <span style="color:red;">${day}/${month}/${year}</span>
    `;

    document.getElementById("dateTime").innerHTML = formatted;
}

// Gọi khi tải trang
updateDateTime();

// Cập nhật mỗi phút
setInterval(updateDateTime, 60000);
</script>
<h2 style="color: green;">Bia - Hà Nội</h2>
<form method="get" id="form-hongha" style="display:none; margin-bottom:10px;">
    <input type="hidden" name="filter_bang" value="bang_nhap_xuat_hongha">
    <input type="date" name="filter_date" required>
    <button type="submit">Lọc</button>
    <a href="<?= $_SERVER['PHP_SELF'] ?>"><button type="button">Xóa lọc</button></a>
</form>
<div class="table-wrapper">
<table>
    <tr>
        <th rowspan="2" onclick="toggleFilter('form-hongha')" style="background-color:#d9d9d9; font-size: 30px;">Ngày</th>
        <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Nhập</th>
        <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Xuất</th>
        <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Tồn</th>
    </tr>
    <tr>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
    </tr>
<?php while ($row = $result_hongha->fetch_assoc()):
    $ngay = strtotime($row['ngay']);
    $now = time();
    $time_difference = $now - $ngay;
    $is_editable = ($time_difference <= 1800) ? true : false;
?>
<tr data-id="<?= $row['id'] ?>" data-editable="<?= $is_editable ? 'true' : 'false' ?>" onclick="toggleDeleteButtonHongHa(this)">
    <td data-label="Ngày" onclick="toggleDateNguoiGiao(this)">
        <span class="date"><?= date('d/m', strtotime($row['ngay'])) . "<br>" . date('H:i', strtotime($row['ngay'])) ?></span>
        <span class="nguoi-giao" style="display: none;"><?= htmlspecialchars($row['nguoi_giao']) ?></span>
        <br>
        <?php if ($is_editable): ?>
            <button class="btn-delete" data-id="<?= $row['id'] ?>" style="display: none;">Xóa</button>
        <?php endif; ?>
    </td>
    <td data-label="Nhập 30L" class="editable"><?= $row['nhap_30L'] ?></td>
    <td data-label="Nhập 50L" class="editable"><?= $row['nhap_50L'] ?></td>
    <td data-label="Xuất 30L" class="editable"><?= $row['xuat_30L'] ?></td>
    <td data-label="Xuất 50L" class="editable"><?= $row['xuat_50L'] ?></td>
    <td data-label="Tồn 30L"><?= $row['ton_30L'] ?></td>
    <td data-label="Tồn 50L"><?= $row['ton_50L'] ?></td>
    <td data-label="Người giao" class="editable-select"><?= htmlspecialchars($row['nguoi_giao']) ?></td>
</tr>

<?php endwhile; ?>



<form method="post" id="form-nhap-xuat">
    <tr>
        <td>
            <select name="nguoi_giao" id="nguoi_giao" style="font-size: 20px;" required>
                <option value="Khác" selected>Khác</option>
                <option value="Hiệp">Hiệp</option>
                <option value="Hồ">Hồ</option>
                <option value="Hưng">Hưng</option>
            </select>
        </td>
        <td>
            <input type="text" name="nhap_30L" id="nhap_30L" readonly onclick="showNumberPicker('nhap_30L')">
        </td>
        <td>
            <input type="text" name="nhap_50L" id="nhap_50L" readonly onclick="showNumberPicker('nhap_50L')">
        </td>
        <td>
            <input type="text" name="xuat_30L" id="xuat_30L" readonly onclick="showNumberPicker('xuat_30L')">
        </td>
        <td>
            <input type="text" name="xuat_50L" id="xuat_50L" readonly onclick="showNumberPicker('xuat_50L')">
        </td>
        <td colspan="2">
            <input type="hidden" name="bang" value="bang_nhap_xuat_hongha">
            <input type="hidden" name="edit_id" id="edit_id" value="">
            <button type="submit" id="btn-submit">Thêm</button>
            <button type="button" id="btn-cancel" style="display:none;">Hủy</button>
        </td>
    </tr>
</form>
</table>
</div>


<h2 style="color: green;">Bia - NEW</h2>
<form method="get" id="form-new" style="display:none; margin-bottom:10px;">
    <input type="hidden" name="filter_bang" value="bang_nhap_xuat_new">
    <input type="date" name="filter_date" required>
    <button type="submit">Lọc</button>
    <a href="<?= $_SERVER['PHP_SELF'] ?>"><button type="button">Xóa lọc</button></a>
</form>
<div class="table-wrapper">
<table>
    <tr>
        <th rowspan="2" onclick="toggleFilter('form-new')" style="background-color:#d9d9d9; font-size: 30px;">Ngày</th>
        <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Nhập</th>
        <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Xuất</th>
        <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Tồn</th>
    </tr>
    <tr>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
    </tr>
<?php while ($row = $result_new->fetch_assoc()):
    $ngay = strtotime($row['ngay']);
    $now = time();
    $time_difference = $now - $ngay;
    $is_editable = ($time_difference <= 1800) ? true : false;
?>
<tr data-id="<?= $row['id'] ?>" data-editable="<?= $is_editable ? 'true' : 'false' ?>" onclick="toggleDeleteButtonNew(this)">
    <td data-label="Ngày" onclick="toggleDateNguoiGiao(this)">
        <span class="date"><?= date('d/m', strtotime($row['ngay'])) . "<br>" . date('H:i', strtotime($row['ngay'])) ?></span>
        <span class="nguoi-giao" style="display: none;"><?= htmlspecialchars($row['nguoi_giao']) ?></span>
        <br>
        <?php if ($is_editable): ?>
            <button class="btn-delete" data-id="<?= $row['id'] ?>" style="display: none;">Xóa</button>
        <?php endif; ?>
    </td>
    <td data-label="Nhập 30L" class="editable_new"><?= $row['nhap_30L'] ?></td>
    <td data-label="Nhập 50L" class="editable_new"><?= $row['nhap_50L'] ?></td>
    <td data-label="Xuất 30L" class="editable_new"><?= $row['xuat_30L'] ?></td>
    <td data-label="Xuất 50L" class="editable_new"><?= $row['xuat_50L'] ?></td>
    <td data-label="Tồn 30L"><?= $row['ton_30L'] ?></td>
    <td data-label="Tồn 50L"><?= $row['ton_50L'] ?></td>
    <td data-label="Người giao" class="editable-select_new"><?= htmlspecialchars($row['nguoi_giao']) ?></td>
</tr>


<?php endwhile; ?>

    <form method="post" id="form-nhap-xuat-new">
    <tr>
        <td>
            <select name="nguoi_giao" id="nguoi_giao_new" style="font-size: 20px;" required>
                <option value="Khác" selected>Khác</option>
                <option value="Hiệp">Hiệp</option>
                <option value="Hồ">Hồ</option>
                <option value="Hưng">Hưng</option>
            </select>
        </td>
        <td>
            <input type="text" name="nhap_30L" id="nhap_30L_new" readonly onclick="showNumberPicker('nhap_30L_new')">
        </td>
        <td>
            <input type="text" name="nhap_50L" id="nhap_50L_new" readonly onclick="showNumberPicker('nhap_50L_new')">
        </td>
        <td>
            <input type="text" name="xuat_30L" id="xuat_30L_new" readonly onclick="showNumberPicker('xuat_30L_new')">
        </td>
        <td>
            <input type="text" name="xuat_50L" id="xuat_50L_new" readonly onclick="showNumberPicker('xuat_50L_new')">
        </td>
        <td colspan="2">
            <input type="hidden" name="bang" value="bang_nhap_xuat_new">
            <input type="hidden" name="edit_id" id="edit_id_new" value="">
            <br>
            <button type="submit" id="btn-submit-new">Thêm</button>
            <button type="button" id="btn-cancel-new" style="display:none;">Hủy</button>
        </td>
    </tr>
    </form>
</table>
</div>



<h2 style="color: green;">Nhập Tồn</h2>
<form method="post" id="form-ton-nhanh">
    <table border="1" width="100%">
        <tr>
            <th rowspan="2" onclick="toggleFilter('form-new')" style="background-color:#d9d9d9; font-size: 50px;">Ngày</th>
            <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Tồn (Hà Nội)</th>
            <th colspan="2" style="background-color:#d9d9d9; font-size: 50px;">Tồn (NEW)</th>
        </tr>
    <tr>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
        <th style="background-color:#CCFFCC; font-size: 35px; color: red;">30L</th><th style="background-color:#CCFFCC; font-size: 35px; color: red;">50L</th>
    </tr>
        <tr>
            <!-- Cột Ngày -->
            <td style="text-align: center;">
                <input type="hidden" name="ngay" id="ngay_tudong">
                <button type="submit" id="btn-submit-ton-nhanh">Thêm</button>
            </td>

<td>
  <input type="text" name="ton_30L_hn" id="ton_30L_hn" readonly 
         onclick="showNumberPicker('ton_30L_hn')">
</td>
<td>
  <input type="text" name="ton_50L_hn" id="ton_50L_hn" readonly 
         onclick="showNumberPicker('ton_50L_hn')">
</td>
<td>
  <input type="text" name="ton_30L_new" id="ton_30L_new" readonly 
         onclick="showNumberPicker('ton_30L_new')">
</td>
<td>
  <input type="text" name="ton_50L_new" id="ton_50L_new" readonly 
         onclick="showNumberPicker('ton_50L_new')">
</td>
        </tr>
    </table>
</form>

<script>
function toggleDeleteButtonHongHa(row) {
    const isEditable = row.getAttribute('data-editable') === 'true';
    const btnDelete = row.querySelector('.btn-delete');

    if (!btnDelete) return;

    if (!isEditable) {
        // Nếu đã quá 30 phút => ẩn hẳn nút xóa và chặn click
        btnDelete.style.display = 'none';
        btnDelete.disabled = true;
        return;
    }

    // Nếu còn trong 30 phút => cho phép hiện/tắt nút xóa khi click
    btnDelete.disabled = false;
    btnDelete.style.display = btnDelete.style.display === 'none' ? 'inline-block' : 'none';

    btnDelete.onclick = (event) => {
        event.stopPropagation();
        const id = btnDelete.dataset.id;
        if (confirm('Bạn có chắc chắn muốn xóa bản ghi này?')) {
            fetch('?delete_id=' + id + '&bang=bang_nhap_xuat_hongha')
                .then(r => r.json())
                .then(d => {
                    if (d.status === 'success') {
                        row.remove();
                    } else {
                        alert('Lỗi khi xóa bản ghi!');
                    }
                })
                .catch(err => {
                    alert('Có lỗi xảy ra khi xóa!');
                    console.error(err);
                });
        }
    };
}

function toggleDeleteButtonNew(row) {
    const isEditable = row.getAttribute('data-editable') === 'true';
    const btnDelete = row.querySelector('.btn-delete');

    if (!btnDelete) return;

    if (!isEditable) {
        btnDelete.style.display = 'none';
        btnDelete.disabled = true;
        return;
    }

    btnDelete.disabled = false;
    btnDelete.style.display = btnDelete.style.display === 'none' ? 'inline-block' : 'none';

    btnDelete.onclick = (event) => {
        event.stopPropagation();
        const id = btnDelete.dataset.id;
        if (confirm('Bạn có chắc chắn muốn xóa bản ghi này?')) {
            fetch('?delete_id=' + id + '&bang=bang_nhap_xuat_new')
                .then(r => r.json())
                .then(d => {
                    if (d.status === 'success') {
                        row.remove();
                    } else {
                        alert('Lỗi khi xóa bản ghi!');
                    }
                })
                .catch(err => {
                    alert('Có lỗi xảy ra khi xóa!');
                    console.error(err);
                });
        }
    };
}



function toggleDateNguoiGiao(cell) {
    const dateSpan = cell.querySelector('.date');
    const nguoiGiaoSpan = cell.querySelector('.nguoi-giao');
    if (dateSpan.style.display !== 'none') {
        dateSpan.style.display = 'none';
        nguoiGiaoSpan.style.display = 'block';
    } else {
        dateSpan.style.display = 'block';
        nguoiGiaoSpan.style.display = 'none';
    }
}

function toggleFilter(formId) {
    const form = document.getElementById(formId);
    form.style.display = form.style.display === 'none' ? 'block' : 'none';
}

document.querySelectorAll('.btn-edit').forEach(button => {
    button.addEventListener('click', () => {
        const tr = button.closest('tr');
        const id = tr.dataset.id;
        const cells = tr.querySelectorAll('td.editable, td.editable-select');
        const nhap_30L = cells[0].textContent.trim();
        const nhap_50L = cells[1].textContent.trim();
        const xuat_30L = cells[2].textContent.trim();
        const xuat_50L = cells[3].textContent.trim();
        const nguoi_giao = cells[4].textContent.trim();
        document.getElementById('nhap_30L').value = nhap_30L;
        document.getElementById('nhap_50L').value = nhap_50L;
        document.getElementById('xuat_30L').value = xuat_30L;
        document.getElementById('xuat_50L').value = xuat_50L;
        document.getElementById('nguoi_giao').value = nguoi_giao;
        document.getElementById('edit_id').value = id;
        document.getElementById('btn-submit').textContent = 'Sửa';
        document.getElementById('btn-cancel').style.display = 'inline-block';
    });
});

document.getElementById('btn-cancel').addEventListener('click', () => {
    document.getElementById('form-nhap-xuat').reset();
    document.getElementById('edit_id').value = '';
    document.getElementById('btn-submit').textContent = 'Thêm';
    document.getElementById('btn-cancel').style.display = 'none';
});



document.querySelectorAll('.btn-edit-new').forEach(button => {
    button.addEventListener('click', () => {
        const tr = button.closest('tr');
        const id = tr.dataset.id;
        const cells = tr.querySelectorAll('td.editable_new, td.editable-select_new');
        const nhap_30L = cells[0].textContent.trim();
        const nhap_50L = cells[1].textContent.trim();
        const xuat_30L = cells[2].textContent.trim();
        const xuat_50L = cells[3].textContent.trim();
        const nguoi_giao = cells[4].textContent.trim();

        document.getElementById('nhap_30L_new').value = nhap_30L;
        document.getElementById('nhap_50L_new').value = nhap_50L;
        document.getElementById('xuat_30L_new').value = xuat_30L;
        document.getElementById('xuat_50L_new').value = xuat_50L;
        document.getElementById('nguoi_giao_new').value = nguoi_giao;
        document.getElementById('edit_id_new').value = id;
        document.getElementById('btn-submit-new').textContent = 'Sửa';
        document.getElementById('btn-cancel-new').style.display = 'inline-block';
    });
});

document.getElementById('btn-cancel-new').addEventListener('click', () => {
    document.getElementById('form-nhap-xuat-new').reset();
    document.getElementById('edit_id_new').value = '';
    document.getElementById('btn-submit-new').textContent = 'Thêm';
    document.getElementById('btn-cancel-new').style.display = 'none';
});


// Chỉ cho phép sửa khi bản ghi còn trong 30 phút
document.querySelectorAll('td.editable, td.editable-select').forEach(td => {
    td.addEventListener('click', () => {
        const tr = td.closest('tr');
        if (tr.getAttribute('data-editable') !== 'true') return; // chặn edit quá hạn

        const id = tr.dataset.id;
        const cells = tr.querySelectorAll('td.editable, td.editable-select');
        document.getElementById('nhap_30L').value = cells[0].textContent.trim();
        document.getElementById('nhap_50L').value = cells[1].textContent.trim();
        document.getElementById('xuat_30L').value = cells[2].textContent.trim();
        document.getElementById('xuat_50L').value = cells[3].textContent.trim();
        document.getElementById('nguoi_giao').value = cells[4].textContent.trim();
        document.getElementById('edit_id').value = id;
        document.getElementById('btn-submit').textContent = 'Sửa';
        document.getElementById('btn-cancel').style.display = 'inline-block';
    });
});

document.querySelectorAll('td.editable_new, td.editable-select_new').forEach(td => {
    td.addEventListener('click', () => {
        const tr = td.closest('tr');
        if (tr.getAttribute('data-editable') !== 'true') return;

        const id = tr.dataset.id;
        const cells = tr.querySelectorAll('td.editable_new, td.editable-select_new');
        document.getElementById('nhap_30L_new').value = cells[0].textContent.trim();
        document.getElementById('nhap_50L_new').value = cells[1].textContent.trim();
        document.getElementById('xuat_30L_new').value = cells[2].textContent.trim();
        document.getElementById('xuat_50L_new').value = cells[3].textContent.trim();
        document.getElementById('nguoi_giao_new').value = cells[4].textContent.trim();
        document.getElementById('edit_id_new').value = id;
        document.getElementById('btn-submit-new').textContent = 'Sửa';
        document.getElementById('btn-cancel-new').style.display = 'inline-block';
    });
});


document.getElementById('form-nhap-xuat').addEventListener('submit', function(event) {
    const nhap_30L = document.getElementById('nhap_30L').value;
    const nhap_50L = document.getElementById('nhap_50L').value;
    const xuat_30L = document.getElementById('xuat_30L').value;
    const xuat_50L = document.getElementById('xuat_50L').value;

    let isAnyFieldFilled = false;
    if (nhap_30L !== '') {
        isAnyFieldFilled = true;
    }
    if (nhap_50L !== '') {
        isAnyFieldFilled = true;
    }
    if (xuat_30L !== '') {
        isAnyFieldFilled = true;
    }
    if (xuat_50L !== '') {
        isAnyFieldFilled = true;
    }

    if (!isAnyFieldFilled) {
        event.preventDefault();
        return false;
    }
    if (nhap_30L === '') {
        document.getElementById('nhap_30L').value = 0;
    }
    if (nhap_50L === '') {
        document.getElementById('nhap_50L').value = 0;
    }
    if (xuat_30L === '') {
        document.getElementById('xuat_30L').value = 0;
    }
    if (xuat_50L === '') {
        document.getElementById('xuat_50L').value = 0;
    }
});

document.getElementById('form-nhap-xuat-new').addEventListener('submit', function(event) {
    const nhap_30L_new = document.getElementById('nhap_30L_new').value;
    const nhap_50L_new = document.getElementById('nhap_50L_new').value;
    const xuat_30L_new = document.getElementById('xuat_30L_new').value;
    const xuat_50L_new = document.getElementById('xuat_50L_new').value;
    let isAnyFieldFilledNew = false;
    if (nhap_30L_new !== '') {
        isAnyFieldFilledNew = true;
    }
    if (nhap_50L_new !== '') {
        isAnyFieldFilledNew = true;
    }
    if (xuat_30L_new !== '') {
        isAnyFieldFilledNew = true;
    }
    if (xuat_50L_new !== '') {
        isAnyFieldFilledNew = true;
    }

    if (!isAnyFieldFilledNew) {
        event.preventDefault();
        return false;
    }

    if (nhap_30L_new === '') {
        document.getElementById('nhap_30L_new').value = 0;
    }
    if (nhap_50L_new === '') {
        document.getElementById('nhap_50L_new').value = 0;
    }
    if (xuat_30L_new === '') {
        document.getElementById('xuat_30L_new').value = 0;
    }
    if (xuat_50L_new === '') {
        document.getElementById('xuat_50L_new').value = 0;
    }
});
</script>

</body>
</html>
