/*

 * Tên dự án: Cân Điện Tử Wi-Fi v3.5 (Ổn định I/O + Bảo mật Cài đặt)

 * Mô tả:

 * - HOÀN TÁC LOGIC ID:

 * + Gỡ bỏ hệ thống "số thứ tự" (counter.txt) để tránh

 * gây sụt nguồn/treo mạch do I/O chậm.

 * + Quay lại sử dụng ID (timestamp) do trình duyệt tạo ra

 * để đảm bảo ESP32 chỉ thực hiện I/O khi cần thiết.

 * - Cập nhật hàm dọn dẹp bộ nhớ để hoạt động với ID timestamp.

 * - Giữ nguyên giao diện và chức năng lọc ngày.

 * - ĐÃ THÊM: Tính năng đổi SSID, Mật khẩu Wi-Fi, Mật khẩu Admin từ v3.8

 * - CẬP NHẬT BẢO MẬT:

 * + Thêm trang đăng nhập (setup_login_html) cho route /setupwifi.

 * + Người dùng phải nhập đúng mật khẩu admin mới xem được trang cài đặt.

 * + Route /setupwifi/save vẫn kiểm tra lại mật khẩu để tăng cường an toàn.

 */

 

#include <WiFi.h>

#include <ESPAsyncWebServer.h>

#include <DNSServer.h>

#include <LittleFS.h>

#include "ArduinoJson.h"

#include <AsyncJson.h>

#include <freertos/task.h>     // Thêm từ v3.8

#include <time.h>              // Thêm từ v3.8


// --- CẤU HÌNH MẠNG WI-FI (MẶC ĐỊNH) ---

const char* default_ap_ssid = "CAN DIEN TU C3"; // Đổi tên từ v3.5

const char* default_ap_password = "can12345"; // Đổi tên từ v3.5

String current_ap_ssid;     // Thêm từ v3.8

String current_ap_password; // Thêm từ v3.8


// --- CẤU HÌNH SERIAL ĐỌC CÂN (từ v3.5) ---

#define BAUD_RATE 9600 

#define RX_PIN 4 

#define TX_PIN 3 


AsyncWebServer server(80);

AsyncWebSocket ws("/ws");

DNSServer dnsServer;


// --- BIẾN TOÀN CỤC ---

String latestWeightString = "0.00"; 

const float STORAGE_CLEANUP_THRESHOLD = 0.95; 


// --- TÊN CÁC TỆP TIN CẤU HÌNH (Thêm từ v3.8) ---

const char* ADMIN_HASH_FILE = "/admin_hash.txt";

const char* WIFI_SSID_FILE = "/wifi_ssid.txt"; 

const char* WIFI_PASS_FILE = "/wifi_pass.txt"; 

const char* DEFAULT_ADMIN_HASH = "-1422291640"; // Hash của "admin"



// --- GIAO DIỆN WEB HOÀN CHỈNH (HTML) ---

// (index_html từ v3.5 của bạn giống hệt v3.8, giữ nguyên)

const char index_html[] PROGMEM = R"rawliteral(

<!DOCTYPE html>

<html lang="vi">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Chương Trình Cân Điện Tử</title>

    <style>

        body {

            -webkit-user-select: none;

            -ms-user-select: none;

            user-select: none;

        }

        .post-body {

            position: fixed !important;

            top: 0;

            left: 0;

            width: 100vw !important;

            height: 100vh !important;

            padding: 20px 0 !important;

            margin: 0 !important;

            z-index: 99999;

            display: flex;

            justify-content: center;

            align-items: flex-start;

            background-color: #f0f2f5 !important;

            font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;

            box-sizing: border-box !important;

        }

        html { box-sizing: border-box; }

        *, *:before, *:after { box-sizing: inherit; }

        #main-container{

            padding:20px;

            border:1px solid #e0e0e0;

            border-radius:12px;

            max-width:700px;

            width:90%;

            margin: 0;

            background-color:#fff;

            box-shadow:0 4px 12px rgba(0,0,0,.08);

            box-sizing: border-box;

            max-height: 100%;

            overflow-y: auto;

        }

        h2,h3{text-align:center;color:#333;margin-top:0}

        #app-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;}

        .brand-link-container { text-align: left; margin-bottom: 10px; font-size: 15px; font-weight: bold; color: #8B0000; }

        #realtime-clock{font-size:1em;color:#555;padding:6px 12px;border:1px solid #e0e0e0;border-radius:8px;background-color:#f8f9fa;}

        .customer-info {

            display: grid;

            grid-template-columns: 1fr 1fr;

            gap: 10px;

            margin-bottom: 15px;

        }

        .customer-info input,.extra-info input{width:100%;padding:10px;font-size:16px;border:1px solid #ccc;border-radius:8px;box-sizing:border-box}

        .extra-info{margin-bottom:15px}

        .connection-controls button{font-size:16px;padding:10px 20px;cursor:pointer;border:none;border-radius:8px;color:#fff;transition:background-color .3s,opacity .3s}

        #connectToggleButton{background-color:#28a745; min-width: 130px; }

        #connectToggleButton.disconnect{background-color:#dc3545}

        .connection-controls button:hover{opacity:.8}.connection-controls button:disabled{background-color:#b0b0b0;cursor:not-allowed}

        #display-block{background-color:#fff;padding:15px;border:1px solid #007bff;border-radius:8px;margin-bottom:15px;}

        #weight-display-wrapper { position: relative; display: flex; justify-content: flex-end; align-items: baseline; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 10px; }

        #autoWeighButton { position: absolute; left: 0; top: 50%; transform: translateY(-50%); background-color: #6c757d; color: white; border: none; border-radius: 8px; width: 44px; height: 44px; font-size: 24px; cursor: pointer; transition: background-color 0.3s; }

        #autoWeighButton.active { background-color: #007bff; }

        #weight-display-row { display: flex; align-items: baseline; justify-content: center; gap: 15px; }

        #output { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; font-size: 48px; font-weight: 700; color: #1E90FF; padding: 0; margin: 0; line-height: 1.1; }

        #weight-unit { font-size: 28px; font-weight: 500; color: #6c757d; }

        #price-section{display:grid;grid-template-columns:1fr 1fr;gap:15px;align-items:center}

        .price-field label{display:block;font-weight:700;margin-bottom:5px;color:#555;white-space: nowrap;}

        .price-field input{width:100%;padding:10px;font-size:18px;border:1px solid #ccc;border-radius:8px;box-sizing:border-box;font-weight:700;text-align:right}

        #totalPrice{background-color:#e9ecef;color:#333}

        .action-buttons-group { margin-bottom: 20px; }

        .main-action-button{margin-bottom: 10px;}

        .secondary-action-buttons { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }

        .secondary-action-buttons button, .main-action-button button {font-size:16px;padding:12px 10px;cursor:pointer;border-radius:8px;border:1px solid #ccc;background-color:#fff;transition:background-color .3s,color .3s; white-space: nowrap;}

        #weighButton{background-color:#28a745;color:#fff;border:none;width:100%; font-size: 18px !important;}

        #saveAndNewButton { background-color: #007bff; color: white; border: none; }

        #reviewHistoryButton { background-color: #6c757d; color: white; border: none; }

        #saveAndNewButton:hover:not(:disabled) { background-color: #0069d9; opacity: 1; }

        #reviewHistoryButton:hover:not(:disabled) { background-color: #5a6268; opacity: 1; }

        .secondary-action-buttons button:disabled, .main-action-button button:disabled{background-color:#e9ecef;cursor:not-allowed;color:#6c757d; border: 1px solid #ccc;}

        #results-section{margin-top:0;}

        #resultsTable { width: 100%; border-collapse: collapse; margin-top: 10px; table-layout: fixed; }

        #resultsTable th { background-color: #f2f2f2; font-weight: 700; text-align: center; border: 1px solid #ddd; padding: 10px 5px; }

        #resultsTable tfoot td { font-weight: bold; border: 1px solid #ddd; padding: 10px 5px; background-color: #e9ecef; font-size: 18px; }

        #resultsTable tfoot td:first-child { font-size: 16px; }

        #resultsTable th:nth-child(1), #resultsTable tfoot td:nth-child(1) { width: 15%; }

        #resultsTable th:nth-child(2), #resultsTable tfoot td:nth-child(2) { width: 35%; }

        #resultsTable th:nth-child(3), #resultsTable tfoot td:nth-child(3) { width: 35%; }

        #resultsTable th.delete-column-header, #resultsTable tfoot td.delete-column-header { width: 15%; }

        #resultsTable tfoot td:nth-child(1) { text-align: left; }

        #resultsTable tfoot td:nth-child(2) { text-align: right; padding-right: 8px; }

        #resultsTable tfoot td:nth-child(3) { text-align: right; padding-right: 8px; }

        .data-container-cell { padding: 0; border: 0; border-left: 1px solid #ddd; border-right: 1px solid #ddd; }

        #dynamic-data-container { height: 135px; overflow-y: auto; }

        #dynamicDataTable { width: 100%; table-layout: fixed; border-collapse: collapse; }

        #dynamicDataTable td { border-bottom: 1px solid #ddd; padding: 10px 5px; vertical-align: middle; }

        #dynamicDataTable tr:last-child td { border-bottom: none; }

        #dynamicDataTable td:nth-child(1) { width: 15%; text-align: center; }

        #dynamicDataTable td:nth-child(2) { width: 35%; text-align: right; padding-right: 8px;}

        #dynamicDataTable td:nth-child(3) { width: 35%; text-align: right; padding-right: 8px;}

        #dynamicDataTable td.delete-column-data { width: 15%; text-align: center; }

        .delete-btn { background-color: #dc3545; color: white; border: none; border-radius: 50%; width: 24px; height: 24px; cursor: pointer; font-weight: bold; line-height: 24px; padding: 0; }

        .delete-btn:hover { background-color: #c82333; }

        .toast-notification{position:fixed;top:20px;left:50%;transform:translateX(-50%);padding:15px 20px;border-radius:8px;box-shadow:0 4px 8px rgba(0,0,0,.2);z-index:2001;opacity:0;visibility:hidden;transition:opacity .5s,visibility .5s,transform .5s;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:16px;color:white}

        .toast-notification.show{opacity:1;visibility:visible;transform:translateX(-50%)}

        .toast-notification.success{background-color:#28a745}.toast-notification.error{background-color:#dc3545}.toast-notification.info{background-color:#17a2b8}

        .brand-link-container a { color: #8B0000; text-decoration: none; }

        .brand-link-container a:hover { text-decoration: underline; }

        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); z-index: 2000; display: none; justify-content: center; align-items: center; }

        .modal-content { background-color: #fff; padding: 20px; border-radius: 12px; width: 95%; max-width: 700px; max-height: 90vh; overflow-y: auto; position: relative; }

        .modal-close-btn { position: absolute; top: 10px; right: 15px; font-size: 30px; font-weight: bold; cursor: pointer; color: #aaa; }

        .modal-close-btn:hover { color: #333; }

        

        #history-filter-controls {

            display: grid;

            grid-template-columns: 1fr 1fr;

            gap: 10px;

            margin-bottom: 15px;

            align-items: center;

        }

        #history-filter-controls label { font-size: 14px; }

        #history-filter-controls input[type="date"] {

            width: 100%;

            padding: 8px;

            font-size: 14px;

            border: 1px solid #ccc;

            border-radius: 8px;

            box-sizing: border-box;

        }

        #history-filter-button {

            grid-column: span 2;

            background-color: #17a2b8;

            color: white;

            border: none;

            padding: 10px;

            font-size: 16px;

            border-radius: 8px;

            cursor: pointer;

        }

        #history-filter-button:hover { background-color: #138496; }


        .history-list button { display: block; width: 100%; text-align: left; padding: 12px 15px; margin-bottom: 8px; border: 1px solid #ddd; background-color: #f9f9f9; border-radius: 8px; cursor: pointer; }

        .history-list button:hover { background-color: #e9e9e9; }

        

        #history-summary {

            margin-top: 15px;

            padding: 15px;

            background-color: #e9ecef;

            border: 1px solid #ddd;

            border-radius: 8px;

            font-weight: bold;

            text-align: center;

            font-size: 16px;

        }

        #history-summary p {

            margin: 5px 0;

            text-align: left;

            padding-left: 20%;

        }

        @media screen and (max-width: 480px) {

            #history-summary p {

                padding-left: 10%;

            }

        }


        #history-detail-view-content { border: 1px solid #ccc; border-radius: 8px; padding: 15px; }

        #history-detail-view-content h3 { margin-top: 0; }

        #history-detail-view-content table { width: 100%; border-collapse: collapse; margin-top: 10px; table-layout: fixed; }

        #history-detail-view-content th, #history-detail-view-content td { border: 1px solid #ddd; padding: 8px; text-align: center; }

        #history-detail-view-content th:nth-child(1), #history-detail-view-content td:nth-child(1) { width: 18%; }

        #history-detail-view-content th:nth-child(2), #history-detail-view-content td:nth-child(2) { width: 41%; }

        #history-detail-view-content th:nth-child(3), #history-detail-view-content td:nth-child(3) { width: 41%; }

        #history-detail-view-content th { background-color: #f2f2f2; }

        #history-detail-view-content tfoot td { font-weight: bold; background-color: #e9ecef; }

        #history-detail-view-content tfoot td:first-child { text-align: left; white-space: nowrap; }

        .modal-button-container { display: flex; gap: 10px; margin-top: 15px; }

        #exportHistoryButton { flex-grow: 1; background-color: #007bff; color: white; border: none; padding: 12px; font-size: 16px; border-radius: 8px; cursor: pointer; transition: background-color .3s; }

        #deleteHistoryButton { flex-grow: 1; background-color: #dc3545; color: white; border: none; padding: 12px; font-size: 16px; border-radius: 8px; cursor: pointer; transition: background-color .3s; }

        #closeHistoryDetailButton { background-color: #6c757d; color: white; border: none; padding: 12px 20px; font-size: 16px; border-radius: 8px; cursor: pointer; transition: background-color .3s; }

        #exportHistoryButton:hover { background-color: #0056b3; }

        #deleteHistoryButton:hover { background-color: #c82333; }

        #closeHistoryDetailButton:hover { background-color: #5a6268; }

        .bottom-spacer { height: 70px; }

        #storage-info { text-align: center; font-size: 12px; color: #aaa; padding-top: 5px;}

        @media screen and (max-width: 992px){.extra-info, #address-print-row {display:none}}

        @media screen and (max-width: 480px) {

            #main-container { padding: 10px; padding-bottom: 20px; width: 100%; margin: 0; border: none; border-radius: 0; box-shadow: none; max-height: 100vh; }

            #output { font-size: 38px; }

            #weight-unit { font-size: 20px; }

            .price-field input { font-size: 16px; }

            #resultsTable td, #resultsTable th, #dynamicDataTable td { padding: 8px 4px; font-size: 14px; }

            #dynamic-data-container { height: 115px; }

            .secondary-action-buttons button, .main-action-button button { font-size: 15px; padding: 10px 15px; }

            #realtime-clock { font-size: 0.9em; }

        }

    </style>

</head>

<body>


    <div class="toast-notification" id="toast"></div>

    <div id="main-container">

        <div id="app-header">

            <div id="realtime-clock"></div>

            <div class="connection-controls"><button id="connectToggleButton">Kết nối</button></div>

        </div>


        <div class="brand-link-container">

            <a href="https://www.bancandientu.vn/" target="_blank">CÂN ĐIỆN TỬ HOÀNG THANH</a> - 

            <a href="tel:0987059224">0987 059 224</a>

        </div>


        <div id="display-block">

            <div id="weight-display-wrapper">

                <button id="autoWeighButton" title="Tự động chốt số khi cân ổn định">⏱️</button>

                <div id="weight-display-row">

                    <div id="output">--.--</div>

                    <span id="weight-unit">kg</span>

                </div>

            </div>

            <div id="price-section">

                <div class="price-field"><label for="unitPrice">Đơn giá (VNĐ/kg)</label><input type="number" id="unitPrice" placeholder="0"></div>

                <div class="price-field"><label for="totalPrice">Thành tiền (VNĐ)</label><input type="text" id="totalPrice" placeholder="0" readonly></div>

            </div>

        </div>

        

        <div class="action-buttons-group">

            <div class="customer-info"><input id="customerName" placeholder="Tên khách hàng..." type="text"/><input id="productName" placeholder="Tên loại hàng..." type="text"/></div>

            <div class="extra-info"><input id="addressInput" placeholder="Địa chỉ..." type="text"/></div>

            

            <div class="main-action-button"><button disabled id="weighButton"><span style="color: red;">⚖️</span> Chốt Số Cân</button></div>

            <div class="secondary-action-buttons">

                <button disabled id="saveAndNewButton">💾 Lưu & Phiếu Mới</button>

                <button id="reviewHistoryButton">🔄 Xem lại</button>

            </div>

        </div>

        

        <div id="results-section">

            <table id="resultsTable">

                <thead>

                    <tr>

                        <th>STT</th>

                        <th>Khối Lượng (kg)</th>

                        <th>Thành tiền (VNĐ)</th>

                        <th class="delete-column-header">Xóa</th>

                    </tr>

                </thead>

                <tbody>

                    <tr>

                        <td colspan="4" class="data-container-cell">

                            <div id="dynamic-data-container">

                                <table id="dynamicDataTable">

                                    <tbody id="resultsBody">

                                    </tbody>

                                </table>

                            </div>

                        </td>

                    </tr>

                </tbody>

                <tfoot id="resultsFooter">

                    <tr>

                        <td><strong>Tổng</strong></td>

                        <td id="totalWeightCell">0.00</td>

                        <td id="totalPriceCell">0</td>

                        <td class="delete-column-header"></td>

                    </tr>

                </tfoot>

            </table>

        </div>

        <div class="bottom-spacer"></div>

        <div id="copyright" style="text-align: center; font-size: 12px; color: #aaa; padding-top: 15px;">

            &copy; <span id="copyright-year"></span> Cân Điện Tử Hoàng Thanh. Mọi quyền được bảo lưu.

        </div>

        <div id="storage-info">Đang tải...</div>

    </div>


    <!-- Modal xem lại lịch sử -->

    <div class="modal-overlay" id="history-modal">

        <div class="modal-content">

            <span class="modal-close-btn">&times;</span>

            <div id="history-list-view">

                <h3>Lịch sử phiếu cân</h3>

                

                <div id="history-filter-controls">

                    <div>

                        <label for="history-date-from">Từ ngày:</label>

                        <input type="date" id="history-date-from">

                    </div>

                    <div>

                        <label for="history-date-to">Đến ngày:</label>

                        <input type="date" id="history-date-to">

                    </div>

                    <button id="history-filter-button">Lọc / Tải lại</button>

                </div>

                

                <div class="history-list" id="history-list-container">

                </div>


                <div id="history-summary">

                </div>


            </div>

            <div id="history-detail-view" style="display: none;">

                <div id="history-detail-view-content">

                </div>

                <div class="modal-button-container">

                    <button id="exportHistoryButton">Tải về</button>

                    <button id="deleteHistoryButton">Xóa Phiếu Này</button>

                    <button id="closeHistoryDetailButton">Đóng</button>

                </div>

            </div>

        </div>

    </div>


    <script>

    document.addEventListener('DOMContentLoaded', function() {

        document.addEventListener('contextmenu', function(e) { e.preventDefault(); });

        document.addEventListener('keydown', function(e) {

            if (e.key === 'F12' || (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'i' || e.key === 'J' || e.key === 'j')) || (e.ctrlKey && (e.key === 'U' || e.key === 'u'))) {

                e.preventDefault();

                showToast('Chức năng này đã bị vô hiệu hóa.', 'error');

            }

        });

        

        // --- TỪ V3.5 ---

        var ADMIN_PASSWORD_HASH = "-1422291640"; 

        var STABILITY_THRESHOLD = 0.05;

        var STABILITY_COUNT = 3;

        var LOW_THRESHOLD = 0.5;

        

        var clockElement = document.getElementById('realtime-clock');

        var connectToggleButton = document.getElementById('connectToggleButton');

        var autoWeighButton = document.getElementById('autoWeighButton');

        var toast = document.getElementById('toast');

        var historyModal = document.getElementById('history-modal');

        var historyListView = document.getElementById('history-list-view');

        var historyDetailView = document.getElementById('history-detail-view');

        var historyListContainer = document.getElementById('history-list-container');

        var historyDetailContent = document.getElementById('history-detail-view-content');

        

        var historyDateFrom = document.getElementById('history-date-from');

        var historyDateTo = document.getElementById('history-date-to');

        var historyFilterButton = document.getElementById('history-filter-button');

        var historySummary = document.getElementById('history-summary');

        var fullHistoryData = []; 


        var allButtons = {

            weigh: document.getElementById('weighButton'),

            saveAndNew: document.getElementById('saveAndNewButton'),

            reviewHistory: document.getElementById('reviewHistoryButton'),

            exportHistory: document.getElementById('exportHistoryButton'),

            deleteHistory: document.getElementById('deleteHistoryButton'),

            closeHistoryDetail: document.getElementById('closeHistoryDetailButton'),

        };

        var allInputs = {

            customerName: document.getElementById('customerName'),

            productName: document.getElementById('productName'),

            address: document.getElementById('addressInput'),

            unitPrice: document.getElementById('unitPrice'),

            totalPrice: document.getElementById('totalPrice'),

        };

        var allDisplays = {

            output: document.getElementById('output'),

            resultsBody: document.getElementById('resultsBody'),

            totalWeightCell: document.getElementById('totalWeightCell'),

            totalPriceCell: document.getElementById('totalPriceCell'),

            storageInfo: document.getElementById('storage-info')

        };

        

        var websocket = null;

        var latestWeight = 0;

        var weighmentData = [];

        var isAutoWeighActive = false;

        var stableReadings = [];

        var readyForNextWeighing = true;

        var toastTimeout;

        var hasValidReading = false;

        var currentViewingTicketId = null;

        

        var SESSION_STORAGE_KEY = 'phienCanDangDo';


        function saveCurrentSessionToBrowser() {

            var sessionData = {

                weighments: weighmentData,

                customer: allInputs.customerName.value,

                product: allInputs.productName.value,

                address: allInputs.address.value,

                unitPrice: allInputs.unitPrice.value

            };

            localStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(sessionData));

        }


        function loadCurrentSessionFromBrowser() {

            var savedSessionJSON = localStorage.getItem(SESSION_STORAGE_KEY);

            if (savedSessionJSON) {

                var savedSession = JSON.parse(savedSessionJSON);

                if (savedSession && savedSession.weighments) {

                    weighmentData = savedSession.weighments;

                    allInputs.customerName.value = savedSession.customer || '';

                    allInputs.productName.value = savedSession.product || '';

                    allInputs.address.value = savedSession.address || '';

                    allInputs.unitPrice.value = savedSession.unitPrice || '';

                    renderTable();

                    updateTotals();

                    showToast('Đã khôi phục phiên làm việc trước.', 'info');

                }

            }

        }


        // --- TỪ V3.5 ---

        function startConnection() {

            showToast('Đang kết nối...', 'info', 4000);

            var gateway = 'ws://' + window.location.hostname + '/ws';

            websocket = new WebSocket(gateway);

            websocket.onopen = function() { updateButtonStates(true, true); };

            websocket.onclose = onDisconnected;

            websocket.onerror = function(event) {

                console.error('Lỗi WebSocket:', event);

                showToast('Lỗi kết nối WebSocket.', 'error');

                onDisconnected();

            };

            websocket.onmessage = handleWeightUpdate;

        }


        // --- TỪ V3.5 ---

        function onDisconnected() {

            showToast('Đã ngắt kết nối.', 'error', 4000);

            websocket = null;

            hasValidReading = false;

            updateButtonStates(false);

        }

        

        function toggleConnection() {

            if (websocket && websocket.readyState === WebSocket.OPEN) {

                websocket.close();

            } else {

                startConnection();

            }

        }


        // --- TỪ V3.5 ---

        function handleWeightUpdate(event) {

            var rawString = event.data;

            var currentWeight = null;

            var weightString = null;

            var weightPartMatch = null;


            if (rawString.startsWith('ww') && rawString.includes('kg')) {

                 weightPartMatch = rawString.match(/ww(.*?)kg/);

            } else if (rawString.includes('ST') && rawString.includes('GS')) {

                 var parts = rawString.split(',');

                 if (parts.length >= 3) {

                     weightPartMatch = [null, parts[parts.length - 1]];

                 }

            } else {

                 weightPartMatch = [null, rawString];

            }

            

            if (weightPartMatch && weightPartMatch[1]) {

                var weightData = weightPartMatch[1].trim(); 

                var parsedWeight = parseFloat(weightData);


                if (!isNaN(parsedWeight)) {

                    currentWeight = parsedWeight;

                    if (weightData.includes('.')) {

                        var decimalPlaces = (weightData.split('.')[1] || '').length;

                        weightString = currentWeight.toFixed(decimalPlaces);

                    } else {

                        weightString = String(currentWeight);

                    }

                }

            }

            

            if (currentWeight !== null && weightString !== null) {

                hasValidReading = true;

                latestWeight = currentWeight;

                allDisplays.output.textContent = weightString;

                calculateTotal();


                if (!isAutoWeighActive) return;


                if (!readyForNextWeighing && Math.abs(currentWeight) < LOW_THRESHOLD) {

                    readyForNextWeighing = true;

                }

                if (readyForNextWeighing) {

                    var lastReading = stableReadings.length > 0 ? stableReadings[stableReadings.length - 1] : 0;

                    if (Math.abs(currentWeight - lastReading) > STABILITY_THRESHOLD) {

                        stableReadings = [currentWeight];

                    } else {

                        stableReadings.push(currentWeight);

                    }

                    if (stableReadings.length >= STABILITY_COUNT) {

                        if (Math.abs(currentWeight) > LOW_THRESHOLD && captureWeighment()) {

                            readyForNextWeighing = false;

                        }

                        stableReadings = [];

                    }

                }

            }

        }

        

        // --- TỪ V3.5 ---

        function captureWeighment() {

            if (!websocket || websocket.readyState !== WebSocket.OPEN || !hasValidReading) {

                showToast('Chưa có giá trị cân hợp lệ!', 'error');

                return false;

            }

            var weighment = { stt: weighmentData.length + 1, weight: allDisplays.output.textContent, total: allInputs.totalPrice.value };

            weighmentData.push(weighment);

            renderTable();

            updateTotals();

            updateButtonStates(true);

            var dataContainer = document.getElementById('dynamic-data-container');

            dataContainer.scrollTop = dataContainer.scrollHeight;

            showToast('Đã chốt số cân', 'success', 2000);

            saveCurrentSessionToBrowser();

            return true;

        }


        // --- TỪ V3.5 ---

        function deleteRow(index) {

            weighmentData.splice(index, 1);

            weighmentData.forEach(function(item, i) { item.stt = i + 1; });

            renderTable();

            updateTotals();

            showToast('Đã xóa dòng cân.', 'info');

            saveCurrentSessionToBrowser();

        }


        // --- TỪ V3.5 ---

        function calculateTotal() {

            var unitPrice = parseFloat(allInputs.unitPrice.value) || 0;

            var totalPrice = latestWeight * unitPrice;

            allInputs.totalPrice.value = Math.round(totalPrice / 100) * 100 .toLocaleString('vi-VN');

        }


        // --- TỪ V3.5 ---

        function startNewSession() {

            weighmentData = [];

            allInputs.customerName.value = '';

            allInputs.productName.value = '';

            allInputs.address.value = '';

            allInputs.unitPrice.value = '';

            allInputs.totalPrice.value = '';

            renderTable();

            updateTotals();

            updateButtonStates(websocket && websocket.readyState === WebSocket.OPEN, false);

            localStorage.removeItem(SESSION_STORAGE_KEY);

        }

        

        // --- TỪ V3.5 ---

        function saveAndStartNew() {

            if (weighmentData.length === 0) {

                showToast('Chưa có dữ liệu để lưu!', 'error');

                return;

            }

            

            var currentSession = {

                id: Date.now(), // ID LÀ TIMESTAMP

                weighments: weighmentData,

                customer: allInputs.customerName.value,

                product: allInputs.productName.value,

                address: allInputs.address.value,

                unitPrice: allInputs.unitPrice.value

            };


            fetch('/api/save', {

                method: 'POST',

                headers: { 'Content-Type': 'application/json' },

                body: JSON.stringify(currentSession)

            })

            .then(function(response) {

                if (response.ok) {

                    return response.text();

                } else {

                    return response.text().then(function(errorText) {

                        throw new Error(errorText || 'Lỗi không xác định từ server.');

                    });

                }

            })

            .then(function(successMessage) {

                showToast('Đã lưu phiếu và tạo phiếu mới.', 'success');

                startNewSession();

                updateStorageInfo();

            })

            .catch(function(error) {

                console.error('Lỗi khi lưu phiếu:', error);

                showToast('Lỗi khi lưu: ' + error.message, 'error');

            });

        }

        

        // --- TỪ V3.5 ---

        function renderTable() {

            allDisplays.resultsBody.innerHTML = '';

            weighmentData.forEach(function(item, index) {

                var row = allDisplays.resultsBody.insertRow();

                row.innerHTML = '<td>' + item.stt + '</td>' +

                                '<td>' + item.weight + '</td>' +

                                '<td>' + item.total + '</td>' +

                                '<td class="delete-column-data"><button class="delete-btn" data-index="' + index + '">X</button></td>';

            });

        }


        // --- TỪ V3.5 ---

        function updateTotals() {

            var totalWeight = 0;

            var totalPrice = 0;

            weighmentData.forEach(function(item) {

                totalWeight += parseFloat(item.weight) || 0;

                totalPrice += parseInt(String(item.total).replace(/\./g, '')) || 0;

            });

            allDisplays.totalWeightCell.textContent = totalWeight.toFixed(2);

            allDisplays.totalPriceCell.textContent = totalPrice.toLocaleString('vi-VN');

            updateButtonStates(websocket && websocket.readyState === WebSocket.OPEN);

        }


        // --- TỪ V3.5 ---

        function updateButtonStates(isConnected, showConnectToast) {

            if (showConnectToast === void 0) { showConnectToast = false; }

            if (isConnected) {

                if (showConnectToast) showToast('Đã kết nối!', 'success', 2000);

                connectToggleButton.textContent = 'Ngắt kết nối';

                connectToggleButton.classList.add('disconnect');

            } else {

                connectToggleButton.textContent = 'Kết nối';

                connectToggleButton.classList.remove('disconnect');

                allDisplays.output.textContent = '--.--';

            }

            allButtons.weigh.disabled = !isConnected;

            var hasData = weighmentData.length > 0;

            allButtons.saveAndNew.disabled = !hasData;

        }


        // --- TỪ V3.5 ---

        function updateClock() {

            var now = new Date();

            var time = now.toLocaleTimeString('vi-VN');

            var date = now.toLocaleDateString('vi-VN');

            clockElement.textContent = time + ' - ' + date;

        }


        // --- TỪ V3.5 ---

        function showToast(message, type, duration) {

            if (type === void 0) { type = 'info'; }

            if (duration === void 0) { duration = 3000; }

            clearTimeout(toastTimeout);

            toast.textContent = message;

            toast.className = 'toast-notification';

            toast.classList.add(type);

            toast.classList.add('show');

            toastTimeout = setTimeout(function() {

                toast.classList.remove('show');

            }, duration);

        }

        

        // --- TỪ V3.5 ---

        function simpleHash(str) {

            var hash = 0;

            for (var i = 0; i < str.length; i++) {

                var char = str.charCodeAt(i);

                hash = ((hash << 5) - hash) + char;

                hash |= 0;

            }

            return hash.toString();

        }


        // --- TỪ V3.5 ---

        function renderHistoryList(ticketsToShow) {

            historyListContainer.innerHTML = '';

            historySummary.innerHTML = '';

            var summaryWeight = 0;

            var summaryPrice = 0;


            if (ticketsToShow.length === 0) {

                historyListContainer.innerHTML = '<p style="text-align: center; color: #6c757d;">Không tìm thấy phiếu nào.</p>';

                historySummary.innerHTML = 

                    '<p>Tổng số phiếu: 0</p>' +

                    '<p>Tổng khối lượng: 0.00 kg</p>' +

                    '<p>Tổng thành tiền: 0 VNĐ</p>';

                return;

            }


            ticketsToShow.forEach(function(ticket) {

                var button = document.createElement('button');

                var dateString = new Date(ticket.date).toLocaleString('vi-VN');

                // ID GIỜ LÀ TIMESTAMP

                button.textContent = dateString + ' - ' + (ticket.customer || 'Khách lẻ');

                button.dataset.ticketId = ticket.id; // Sử dụng 'id' (timestamp)

                historyListContainer.appendChild(button);


                summaryWeight += ticket.totalWeight;

                summaryPrice += ticket.totalPrice;

            });


            historySummary.innerHTML = 

                '<p>Tổng số phiếu: ' + ticketsToShow.length + '</p>' +

                '<p>Tổng khối lượng: ' + summaryWeight.toFixed(2) + ' kg</p>' +

                '<p>Tổng thành tiền: ' + summaryPrice.toLocaleString('vi-VN') + ' VNĐ</p>';

        }

        

        // --- TỪ V3.5 ---

        function filterAndRenderHistory() {

            var fromDate = historyDateFrom.value ? new Date(historyDateFrom.value).getTime() : 0;

            if (isNaN(fromDate)) fromDate = 0; 

            

            var toDate;

            var maxSafeInt = 9007199254740991;

            if (historyDateTo.value) {

                var d = new Date(historyDateTo.value);

                if (!isNaN(d.getTime())) {

                    toDate = d.getTime() + 86400000 - 1;

                } else {

                    toDate = maxSafeInt;

                }

            } else {

                toDate = maxSafeInt;

            }


            var filtered = fullHistoryData.filter(function(ticket) {

                return ticket.date >= fromDate && ticket.date <= toDate;

            });


            filtered.sort(function(a, b) {

                return b.date - a.date;

            });


            renderHistoryList(filtered);

        }


        // --- TỪ V3.5 ---

        function openHistoryModal() {

            fetch('/api/history')

                .then(function(response) {

                    if (!response.ok) {

                        throw new Error('Không thể tải lịch sử');

                    }

                    return response.json();

                })

                .then(function(history) {

                    fullHistoryData = history;


                    fullHistoryData.sort(function(a, b) {

                        return b.date - a.date;

                    });


                    var defaultData = fullHistoryData.slice(0, 10);

                    

                    renderHistoryList(defaultData);

                    

                    historyListView.style.display = 'block';

                    historyDetailView.style.display = 'none';

                    historyModal.style.display = 'flex';

                })

                .catch(function(error) {

                    showToast(error.message, 'error');

                });

        }


        function closeHistoryModal() {

            historyModal.style.display = 'none';

        }

        

        // --- TỪ V3.5 ---

        function showHistoryDetail(ticketId) {

             currentViewingTicketId = ticketId; 

             

             fetch('/api/ticket?id=' + ticketId) // ID LÀ TIMESTAMP

                .then(function(response) {

                    if (!response.ok) {

                        throw new Error('Không thể tải chi tiết phiếu');

                    }

                    return response.json();

                })

                .then(function(ticket) {

                    var totalWeight = 0;

                    var totalPrice = 0;

                    var tableRows = '';

                    

                    ticket.weighments.forEach(function(item) {

                        tableRows += '<tr><td>' + item.stt + '</td><td>' + item.weight + '</td><td>' + item.total + '</td></tr>';

                        totalWeight += parseFloat(item.weight) || 0;

                        totalPrice += parseInt(String(item.total).replace(/\./g,'')) || 0;

                    });


                    var ticketDate = new Date(ticket.id).toLocaleString('vi-VN');


                    historyDetailContent.innerHTML = 

                        '<h3>Phiếu Cân Hàng</h3>' + // ĐÃ XÓA SỐ PHIẾU

                        '<p><strong>Khách hàng:</strong> ' + (ticket.customer||'N/A') + '</p>' +

                        '<p><strong>Loại hàng:</strong> ' + (ticket.product||'N/A') + '</p>' +

                        '<p><strong>Địa chỉ:</strong> ' + (ticket.address||'N/A') + '</p>' +

                        '<p><strong>Ngày giờ cân:</strong> ' + ticketDate + '</p>' +

                        '<table><thead><tr><th>STT</th><th>Khối Lượng (kg)</th><th>Thành tiền (VNĐ)</th></tr></thead>' +

                        '<tbody>' + tableRows + '</tbody>' +

                        '<tfoot><tr><td><strong>Tổng</strong></td>' +

                        '<td>' + totalWeight.toFixed(2) + '</td>' +

                        '<td>' + totalPrice.toLocaleString('vi-VN') + '</td>' +

                        '</tr></tfoot></table>';

                    

                    historyListView.style.display = 'none';

                    historyDetailView.style.display = 'block';

                })

                .catch(function(error) {

                    showToast(error.message, 'error');

                });

        }


        // --- TỪ V3.5 ---

        function exportHistoryTicketAsTxt(ticketId) {

            if (!ticketId) {

                showToast('Lỗi: Không có ID phiếu.', 'error');

                return;

            }

            window.location.href = '/api/download?id=' + ticketId;

        }


        // --- TỪ V3.5 ---

        function deleteHistoryTicket(ticketId) {

            if (!ticketId) return;

            

            var password = prompt("Để xóa vĩnh viễn, vui lòng nhập mật khẩu quản trị (phân biệt chữ hoa/thường):");

            if (password === null) return;


            // Cập nhật: Lấy hash từ server thay vì hardcode

            // Nhưng vì JS v3.5 đã hardcode, chúng ta giữ nguyên

            if (simpleHash(password) !== ADMIN_PASSWORD_HASH) {

                showToast('Mật khẩu không đúng!', 'error');

                return;

            }


            if (!confirm('Bạn có chắc chắn muốn XÓA VĨNH VIỄN phiếu cân này không? Hành động này không thể hoàn tác.')) return;


            fetch('/api/ticket?id=' + ticketId, { method: 'DELETE' })

                .then(function(response) {

                    if (response.ok) {

                        showToast('Đã xóa phiếu thành công.', 'success');

                        currentViewingTicketId = null;

                        openHistoryModal();

                        updateStorageInfo();

                    } else {

                        throw new Error('Xóa phiếu thất bại.');

                    }

                })

                .catch(function(error) {

                    showToast(error.message, 'error');

                });

        }


        // --- TỪ V3.5 ---

        function toggleAutoWeigh() {

            if (isAutoWeighActive) {

                if (confirm("Bạn có muốn TẮT tính năng tự động chốt cân không?")) {

                    isAutoWeighActive = false;

                    autoWeighButton.classList.remove('active');

                    showToast('Tự động chốt cân: TẮT', 'info');

                    stableReadings = [];

                }

            } else {

                if (confirm("Bạn có muốn BẬT tính năng tự động chốt cân không?")) {

                    isAutoWeighActive = true;

                    autoWeighButton.classList.add('active');

                    showToast('Tự động chốt cân: BẬT', 'info');

                    readyForNextWeighing = true;

                }

            }

        }


        // --- TỪ V3.5 ---

        function updateStorageInfo() {

            fetch('/api/storage')

                .then(function(response) {

                    if (!response.ok) {

                        throw new Error('Lỗi tải dung lượng');

                    }

                    return response.json();

                })

                .then(function(data) {

                    var usedMB = (data.used / (1024 * 1024)).toFixed(2);

                    var totalMB = (data.total / (1024 * 1024)).toFixed(2);

                    var percent = totalMB > 0 ? ((data.used / data.total) * 100).toFixed(1) : 0;

                    allDisplays.storageInfo.textContent = 'Bộ nhớ: ' + usedMB + 'MB / ' + totalMB + 'MB (' + percent + '%)';

                })

                .catch(function(error) {

                    allDisplays.storageInfo.textContent = 'Lỗi tải dung lượng bộ nhớ.';

                });

        }

        

        // --- TỪ V3.5 ---

        function initialize() {

            document.getElementById('copyright-year').textContent = new Date().getFullYear();

            updateClock();

            setInterval(updateClock, 1000);


            connectToggleButton.addEventListener('click', toggleConnection);

            autoWeighButton.addEventListener('click', toggleAutoWeigh);

            allButtons.weigh.addEventListener('click', captureWeighment);

            allButtons.saveAndNew.addEventListener('click', saveAndStartNew);

            allButtons.reviewHistory.addEventListener('click', openHistoryModal);

            

            allButtons.exportHistory.addEventListener('click', function() {

                exportHistoryTicketAsTxt(currentViewingTicketId);

            });

            allButtons.deleteHistory.addEventListener('click', function() {

                deleteHistoryTicket(currentViewingTicketId);

            });

            // SỬA LỖI: NÚT CLOSE CỦA V3.5 TRONG V3.8 HTML KHÔNG ĐÚNG

            // allButtons.closeHistoryDetail.addEventListener('click', closeHistoryModal);

            // THAY BẰNG:

            allButtons.closeHistoryDetail.addEventListener('click', function() {

                 // Quay lại view danh sách thay vì đóng modal hoàn toàn

                 historyDetailView.style.display = 'none';

                 historyListView.style.display = 'block';

                 currentViewingTicketId = null; 

            });


            

            historyFilterButton.addEventListener('click', filterAndRenderHistory);

            

            allInputs.unitPrice.addEventListener('input', function() {

                calculateTotal();

                saveCurrentSessionToBrowser();

            });

            ['customerName', 'productName', 'address'].forEach(function(key) {

                allInputs[key].addEventListener('input', saveCurrentSessionToBrowser);

            });

            

            allDisplays.resultsBody.addEventListener('click', function(e) {

                if (e.target && e.target.classList.contains('delete-btn')) {

                    var index = parseInt(e.target.getAttribute('data-index'), 10);

                    if (!isNaN(index)) {

                        var password = prompt("Vui lòng nhập mật khẩu quản trị (phân biệt chữ hoa/thường):");

                        if (password === null) return;

                        if (simpleHash(password) === ADMIN_PASSWORD_HASH) {

                            deleteRow(index);

                        } else {

                            showToast('Mật khẩu không đúng!', 'error');

                        }

                    }

                }

            });

            

            historyModal.querySelector('.modal-close-btn').addEventListener('click', closeHistoryModal);

            historyListContainer.addEventListener('click', function(e) {

                var button = e.target.closest('button');

                if (button) {

                    showHistoryDetail(button.dataset.ticketId);

                }

            });

            

            loadCurrentSessionFromBrowser();

            updateButtonStates(false);

            updateTotals();

            updateStorageInfo();

        }

        

        initialize();

    });

    </script>

</body>

</html>

)rawliteral";


// --- GIAO DIỆN WEB TRANG CÀI ĐẶT (Thêm từ v3.8) ---

// Đây là trang cài đặt thực tế, sẽ được hiển thị SAU KHI đăng nhập

const char setupwifi_html[] PROGMEM = R"rawliteral(

<!DOCTYPE html>

<html lang="vi">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Cài Đặt Wi-Fi & Admin</title>

    <style>

        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #f0f2f5; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px; box-sizing: border-box; }

        .container { background-color: #fff; padding: 25px 30px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,.08); max-width: 500px; width: 100%; }

        h2 { text-align: center; color: #333; margin-top: 0; margin-bottom: 25px; }

        .form-group { margin-bottom: 20px; }

        .form-group label { display: block; font-weight: 600; margin-bottom: 8px; color: #555; }

        .form-group input { width: 100%; padding: 12px; font-size: 16px; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; }

        .btn { display: block; width: 100%; padding: 14px; font-size: 16px; font-weight: 600; cursor: pointer; border: none; border-radius: 8px; color: #fff; background-color: #007bff; transition: background-color .3s; }

        .btn:hover { background-color: #0056b3; }

        .toast { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); padding: 12px 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,.2); z-index: 100; opacity: 0; visibility: hidden; transition: opacity .5s, visibility .5s, transform .5s; font-size: 16px; color: white; }

        .toast.show { opacity: 1; visibility: visible; transform: translateX(-50%) translateY(0); }

        .toast.success { background-color: #28a745; }

        .toast.error { background-color: #dc3545; }

    </style>

</head>

<body>

    <div class="container">

        <h2>Cài Đặt Cân Điện Tử</h2>

        <form id="setupForm" method="POST" action="/setupwifi/save">

            <div class="form-group">

                <label for="new_ssid">Tên Wi-Fi (SSID) Mới</label>

                <input type="text" id="new_ssid" name="new_ssid" placeholder="Để trống nếu không đổi">

            </div>

            <div class="form-group">

                <label for="new_wifi_pass">Mật Khẩu Wi-Fi Mới</label>

                <input type="password" id="new_wifi_pass" name="new_wifi_pass" placeholder="Ít nhất 8 ký tự, để trống nếu không đổi">

            </div>

            <hr style="border: 0; border-top: 1px solid #eee; margin: 25px 0;">

            <div class="form-group">

                <label for="new_admin_pass">Mật Khẩu Quản Trị Mới</label>

                <input type="password" id="new_admin_pass" name="new_admin_pass" placeholder="Để trống nếu không đổi">

            </div>

            <div class="form-group">

                <label for="current_admin_pass">Mật Khẩu Quản Trị Hiện Tại</label>

                <input type="password" id="current_admin_pass" name="current_admin_pass" required>

            </div>

            <button type="submit" class="btn">Lưu và Khởi Động Lại</button>

        </form>

    </div>

    <div class="toast" id="toast"></div>


    <script>

        document.getElementById('setupForm').addEventListener('submit', function(e) {

            e.preventDefault();

            var form = this;

            var formData = new FormData(form);

            var btn = form.querySelector('.btn');

            

            btn.disabled = true;

            btn.textContent = 'Đang lưu...';


            fetch(form.action, {

                method: form.method,

                body: formData

            })

            .then(function(response) {

                return response.text().then(function(text) {

                    return { ok: response.ok, status: response.status, text: text };

                });

            })

            .then(function(result) {

                if (result.ok) {

                    showToast('Lưu thành công! Cân đang khởi động lại...', 'success');

                    // Không cần bật lại nút vì thiết bị sẽ khởi động lại

                } else {

                    showToast('Lỗi: ' + result.text, 'error');

                    btn.disabled = false;

                    btn.textContent = 'Lưu và Khởi Động Lại';

                }

            })

            .catch(function(error) {

                showToast('Lỗi mạng. Vui lòng thử lại.', 'error');

                btn.disabled = false;

                btn.textContent = 'Lưu và Khởi Động Lại';

            });

        });


        var toastTimeout;

        function showToast(message, type) {

            var toast = document.getElementById('toast');

            clearTimeout(toastTimeout);

            toast.textContent = message;

            toast.className = 'toast'; // Reset

            toast.classList.add(type);

            toast.classList.add('show');

            toastTimeout = setTimeout(function() {

                toast.classList.remove('show');

            }, 3000);

        }

    </script>

</body>

</html>

)rawliteral";


// --- GIAO DIỆN WEB TRANG ĐĂNG NHẬP CÀI ĐẶT (THÊM) ---

// Đây là trang đăng nhập, sẽ được hiển thị ĐẦU TIÊN

const char setup_login_html[] PROGMEM = R"rawliteral(

<!DOCTYPE html>

<html lang="vi">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Đăng Nhập Cài Đặt</title>

    <style>

        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #f0f2f5; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px; box-sizing: border-box; }

        .container { background-color: #fff; padding: 25px 30px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,.08); max-width: 400px; width: 100%; }

        h2 { text-align: center; color: #333; margin-top: 0; margin-bottom: 25px; }

        .form-group { margin-bottom: 20px; }

        .form-group label { display: block; font-weight: 600; margin-bottom: 8px; color: #555; }

        .form-group input { width: 100%; padding: 12px; font-size: 16px; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; }

        .btn { display: block; width: 100%; padding: 14px; font-size: 16px; font-weight: 600; cursor: pointer; border: none; border-radius: 8px; color: #fff; background-color: #007bff; transition: background-color .3s; }

        .btn:hover { background-color: #0056b3; }

        .error-msg { color: #dc3545; text-align: center; margin-bottom: 15px; display: none; }

    </style>

</head>

<body>

    <div class="container">

        <h2>Truy Cập Cài Đặt</h2>

        <p id="error" class="error-msg">Sai mật khẩu. Vui lòng thử lại.</p>

        <form id="loginForm" method="POST" action="/setupwifi/auth">

            <div class="form-group">

                <label for="admin_pass">Mật Khẩu Quản Trị</label>

                <input type="password" id="admin_pass" name="admin_pass" required>

            </div>

            <button type="submit" class="btn">Đăng Nhập</button>

        </form>

    </div>

    <script>

        // Check if the URL has an 'error' query param to show the error message

        if (window.location.search.includes('error=1')) {

            document.getElementById('error').style.display = 'block';

        }

    </script>

</body>

</html>

)rawliteral";



// --- CÁC HÀM HỖ TRỢ HỆ THỐNG FILE (Thêm/Sửa từ v3.8) ---


// Ghi file

bool writeFile(const char* path, const char* content) {

    File file = LittleFS.open(path, "w");

    if (!file) {

        Serial.println("Lỗi khi mở file để ghi");

        return false;

    }

    if (file.print(content)) {

        Serial.println("Ghi file thành công: " + String(path));

        file.close();

        return true;

    } else {

        Serial.println("Lỗi khi ghi file");

        file.close();

        return false;

    }

}


// Đọc file

String readFile(const char* path) {

    File file = LittleFS.open(path, "r");

    if (!file) {

        Serial.println("Lỗi khi mở file để đọc: " + String(path));

        return String();

    }

    String content = file.readString();

    file.close();

    return content;

}


// Tải thông tin đăng nhập

void loadCredentials() {

    // Tải SSID

    current_ap_ssid = readFile(WIFI_SSID_FILE);

    if (current_ap_ssid.length() == 0) {

        current_ap_ssid = default_ap_ssid;

        writeFile(WIFI_SSID_FILE, default_ap_ssid);

        Serial.println("SSID mặc định đã được thiết lập.");

    }

    

    // Tải Mật khẩu Wi-Fi

    current_ap_password = readFile(WIFI_PASS_FILE);

    if (current_ap_password.length() == 0) {

        current_ap_password = default_ap_password;

        writeFile(WIFI_PASS_FILE, default_ap_password);

        Serial.println("Mật khẩu Wi-Fi mặc định đã được thiết lập.");

    }


    // Tải Mật khẩu Admin

    if (!LittleFS.exists(ADMIN_HASH_FILE)) {

        writeFile(ADMIN_HASH_FILE, DEFAULT_ADMIN_HASH);

        Serial.println("Mật khẩu Admin mặc định đã được thiết lập.");

    }

}


// Hàm băm (sử dụng trên server)

String simpleHash(String str) {

    if (str.length() == 0) return "0";

    long hash = 0;

    for (int i = 0; i < str.length(); i++) {

        char c = str.charAt(i);

        hash = ((hash << 5) - hash) + c;

        hash |= 0; // Convert to 32bit integer

    }

    return String(hash);

}


// Hàm khởi động lại

void delayedRebootTask(void * parameter) {

    Serial.println("Bắt đầu khởi động lại sau 3 giây...");

    vTaskDelay(3000 / portTICK_PERIOD_MS);

    Serial.println("Đang khởi động lại!");

    ESP.restart();

}



// --- CÁC HÀM XỬ LÝ SỰ KIỆN VÀ FILE (Từ v3.5) ---


String formatNumber(long num) {

  String s = String(num);

  String result = "";

  int count = 0;

  for (int i = s.length() - 1; i >= 0; i--) {

    result = s.charAt(i) + result;

    count++;

    if (count % 3 == 0 && i > 0) {

      result = "." + result;

    }

  }

  return result;

}


String removeAccents(String str) {

    str.replace("á", "a"); str.replace("à", "a"); str.replace("ả", "a"); str.replace("ã", "a"); str.replace("ạ", "a");

    str.replace("ă", "a"); str.replace("ắ", "a"); str.replace("ằ", "a"); str.replace("ẳ", "a"); str.replace("ẵ", "a"); str.replace("ặ", "a");

    str.replace("â", "a"); str.replace("ấ", "a"); str.replace("ầ", "a"); str.replace("ẩ", "a"); str.replace("ẫ", "a"); str.replace("ậ", "a");

    str.replace("Á", "A"); str.replace("À", "A"); str.replace("Ả", "A"); str.replace("Ã", "A"); str.replace("Ạ", "A");

    str.replace("Ă", "A"); str.replace("Ắ", "A"); str.replace("Ằ", "A"); str.replace("Ẳ", "A"); str.replace("Ẵ", "A"); str.replace("Ặ", "A");

    str.replace("Â", "A"); str.replace("Ấ", "A"); str.replace("Ầ", "A"); str.replace("Ẩ", "A"); str.replace("Ẫ", "A"); str.replace("Ậ", "A");

    str.replace("đ", "d"); str.replace("Đ", "D");

    str.replace("é", "e"); str.replace("è", "e"); str.replace("ẻ", "e"); str.replace("ẽ", "e"); str.replace("ẹ", "e");

    str.replace("ê", "e"); str.replace("ế", "e"); str.replace("ề", "e"); str.replace("ể", "e"); str.replace("ễ", "e"); str.replace("ệ", "e");

    str.replace("É", "E"); str.replace("È", "E"); str.replace("Ẻ", "E"); str.replace("Ẽ", "E"); str.replace("Ẹ", "E");

    str.replace("Ê", "E"); str.replace("Ế", "E"); str.replace("Ề", "E"); str.replace("Ể", "E"); str.replace("Ễ", "E"); str.replace("Ệ", "E");

    str.replace("í", "i"); str.replace("ì", "i"); str.replace("ỉ", "i"); str.replace("ĩ", "i"); str.replace("ị", "i");

    str.replace("Í", "I"); str.replace("Ì", "I"); str.replace("Ỉ", "I"); str.replace("Ĩ", "I"); str.replace("Ị", "I");

    str.replace("ó", "o"); str.replace("ò", "o"); str.replace("ỏ", "o"); str.replace("õ", "o"); str.replace("ọ", "o");

    str.replace("ô", "o"); str.replace("ố", "o"); str.replace("ồ", "o"); str.replace("ổ", "o"); str.replace("ỗ", "o"); str.replace("ộ", "o");

    str.replace("ơ", "o"); str.replace("ớ", "o"); str.replace("ờ", "o"); str.replace("ở", "o"); str.replace("ỡ", "o"); str.replace("ợ", "o");

    str.replace("Ó", "O"); str.replace("Ò", "O"); str.replace("Ỏ", "O"); str.replace("Õ", "O"); str.replace("Ọ", "O");

    str.replace("Ô", "O"); str.replace("Ố", "O"); str.replace("Ồ", "O"); str.replace("Ổ", "O"); str.replace("Ỗ", "O"); str.replace("Ộ", "O");

    str.replace("Ơ", "O"); str.replace("Ớ", "O"); str.replace("Ờ", "O"); str.replace("Ở", "O"); str.replace("Ỡ", "O"); str.replace("Ợ", "O");

    str.replace("ú", "u"); str.replace("ù", "u"); str.replace("ủ", "u"); str.replace("ũ", "u"); str.replace("ụ", "u");

    str.replace("ư", "u"); str.replace("ứ", "u"); str.replace("ừ", "u"); str.replace("ử", "u"); str.replace("ữ", "u"); str.replace("ự", "u");

    str.replace("Ú", "U"); str.replace("Ù", "U"); str.replace("Ủ", "U"); str.replace("Ũ", "U"); str.replace("Ụ", "U");

    str.replace("Ư", "U"); str.replace("Ứ", "U"); str.replace("Ừ", "U"); str.replace("Ử", "U"); str.replace("Ữ", "U"); str.replace("Ự", "U");

    str.replace("ý", "y"); str.replace("ỳ", "y"); str.replace("ỷ", "y"); str.replace("ỹ", "y"); str.replace("ỵ", "y");

    str.replace("Ý", "Y"); str.replace("Ỳ", "Y"); str.replace("Ỷ", "Y"); str.replace("Ỹ", "Y"); str.replace("Ỵ", "Y");

    return str;

}



void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {

    switch (type) {

        case WS_EVT_CONNECT:

            Serial.printf("Client #%u da ket noi.\n", client->id());

            // Gửi giá trị hiện tại ngay khi kết nối

            client->text("ww" + latestWeightString + "kg");

            break;

        case WS_EVT_DISCONNECT:

            Serial.printf("Client #%u da ngat ket noi.\n", client->id());

            break;

        default:

            break;

    }

}


String readAndProcessSerial() {

    if (Serial1.available()) {

        String rs232Data = Serial1.readStringUntil('\n');

        

        if (rs232Data.length() >= 14) {

            char signChar = rs232Data.charAt(6); 

            String weightValue = rs232Data.substring(7, 14);

            weightValue.trim();

            

            if (signChar == '-') {

                weightValue = "-" + weightValue;

            }

            

            return weightValue;

        } else if (rs232Data.length() > 0) {

            rs232Data.trim();

            return rs232Data; 

        }

    }

    return latestWeightString; 

}


// Cập nhật hàm dọn dẹp để dùng ID timestamp

void checkStorageAndCleanUp() {

    float usedSpaceRatio = (float)LittleFS.usedBytes() / LittleFS.totalBytes();

    if (usedSpaceRatio > STORAGE_CLEANUP_THRESHOLD) {

        Serial.printf("Bo nho day (%.2f%%). Bat dau don dep...\n", usedSpaceRatio * 100);

        File historyDir = LittleFS.open("/history");

        File file = historyDir.openNextFile();

        

        long oldestFileTimestamp = -1;

        String oldestFileName = "";

        

        while(file){

            String fileName = file.name();

            if (fileName.endsWith(".json")) {

                // Tên file là /history/123456.json

                String timestampStr = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.lastIndexOf('.'));

                long currentTimestamp = timestampStr.toInt(); // Tên file là timestamp

                

                if (oldestFileTimestamp == -1 || currentTimestamp < oldestFileTimestamp) {

                    oldestFileTimestamp = currentTimestamp;

                    oldestFileName = file.name(); // Lưu tên file đầy đủ (có .json)

                }

            }

            file.close();

            file = historyDir.openNextFile();

        }


        if (oldestFileTimestamp != -1) {

            // Cần tạo đường dẫn đầy đủ

            String fullPath = oldestFileName;

            if (!fullPath.startsWith("/history/")) {

                fullPath = "/history/" + oldestFileName;

            }


            if (LittleFS.remove(fullPath)) {

                Serial.printf("Da xoa file cu nhat: %s\n", fullPath.c_str());

            } else {

                Serial.printf("Loi khi xoa file: %s\n", fullPath.c_str());

            }

        }

        historyDir.close();

    }

}


// --- SETUP ---

void setup() {

    Serial.begin(115200);

    

    if (!LittleFS.begin(true)) {

        Serial.println("Loi khoi tao LittleFS! Dang thu format...");

        if (LittleFS.format()) {

            Serial.println("Format thanh cong. Vui long reset lai mach.");

        } else {

            Serial.println("Format that bai.");

        }

        while(1);

    }

    

    if (!LittleFS.exists("/history")) {

        if (LittleFS.mkdir("/history")) {

            Serial.println("Da tao thu muc /history");

        } else {

            Serial.println("Loi tao thu muc /history");

        }

    }


    // Tải cấu hình (Thêm từ v3.8)

    loadCredentials();


    Serial1.begin(BAUD_RATE, SERIAL_8N1, RX_PIN, TX_PIN); 

    Serial.println("Da khoi tao Serial1 de doc du lieu can.");


    // CẬP NHẬT: Khởi động Wi-Fi với SSID/Pass đã lưu

    WiFi.softAP(current_ap_ssid.c_str(), current_ap_password.c_str());

    IPAddress IP = WiFi.softAPIP();

    Serial.print("Access Point IP: ");

    Serial.println(IP);


    dnsServer.start(53, "*", IP);

    Serial.println("DNS Server da khoi dong cho Captive Portal.");


    ws.onEvent(onWsEvent);

    server.addHandler(&ws);

    

    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){

        request->send_P(200, "text/html", index_html);

    });


    // --- CẬP NHẬT CÁC ROUTE CÀI ĐẶT (THÊM BẢO MẬT) ---


    // Bước 1: Yêu cầu đăng nhập khi truy cập /setupwifi

    server.on("/setupwifi", HTTP_GET, [](AsyncWebServerRequest *request) {

        // Luôn hiển thị trang đăng nhập trước

        request->send_P(200, "text/html", setup_login_html);

    });


    // Bước 2: Xác thực mật khẩu

    server.on("/setupwifi/auth", HTTP_POST, [](AsyncWebServerRequest *request) {

        if (request->hasArg("admin_pass")) {

            String submittedPass = request->arg("admin_pass");

            String storedHash = readFile(ADMIN_HASH_FILE);

            if (storedHash.length() == 0) {

                storedHash = DEFAULT_ADMIN_HASH; // Fallback

            }


            if (simpleHash(submittedPass) == storedHash) {

                // Mật khẩu đúng, hiển thị trang cài đặt

                request->send_P(200, "text/html", setupwifi_html);

            } else {

                // Mật khẩu sai, chuyển hướng về trang đăng nhập với thông báo lỗi

                AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "Redirecting");

                response->addHeader("Location", "/setupwifi?error=1");

                request->send(response);

            }

        } else {

            // Không có mật khẩu, chuyển hướng về trang đăng nhập

            AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "Redirecting");

            response->addHeader("Location", "/setupwifi");

            request->send(response);

        }

    });


    // Bước 3: Lưu cài đặt (handler này đã an toàn vì nó yêu cầu lại mật khẩu)

    server.on("/setupwifi/save", HTTP_POST, [](AsyncWebServerRequest *request) {

        String currentAdminPass = request->arg("current_admin_pass");

        String currentAdminHash = readFile(ADMIN_HASH_FILE);

        if (currentAdminHash.length() == 0) {

            currentAdminHash = DEFAULT_ADMIN_HASH;

        }

        

        // Kiểm tra lại mật khẩu quản trị hiện tại

        if (simpleHash(currentAdminPass) != currentAdminHash) {

            request->send(403, "text/plain", "Sai mat khau quan tri hien tai!");

            return;

        }


        bool changed = false;


        // Xử lý SSID mới

        if (request->hasArg("new_ssid") && request->arg("new_ssid").length() > 0) {

            String newSSID = request->arg("new_ssid");

            writeFile(WIFI_SSID_FILE, newSSID.c_str());

            Serial.println("Da cap nhat SSID moi.");

            changed = true;

        }


        // Xử lý Mật khẩu Wi-Fi mới

        if (request->hasArg("new_wifi_pass") && request->arg("new_wifi_pass").length() >= 8) {

            String newWifiPass = request->arg("new_wifi_pass");

            writeFile(WIFI_PASS_FILE, newWifiPass.c_str());

            Serial.println("Da cap nhat mat khau Wi-Fi moi.");

            changed = true;

        }


        // Xử lý Mật khẩu Admin mới

        if (request->hasArg("new_admin_pass") && request->arg("new_admin_pass").length() > 0) {

            String newAdminPass = request->arg("new_admin_pass");

            String newAdminHash = simpleHash(newAdminPass);

            writeFile(ADMIN_HASH_FILE, newAdminHash.c_str());

            Serial.println("Da cap nhat mat khau Admin moi.");

            changed = true;

        }


        if (changed) {

            request->send(200, "text/plain", "Luu thanh cong! Dang khoi dong lai...");

            // Khởi động lại trong một tác vụ riêng

            xTaskCreate(delayedRebootTask, "rebootTask", 2048, NULL, 5, NULL);

        } else {

            request->send(200, "text/plain", "Khong co gi thay doi.");

        }

    });


    // API: Lấy hash admin (JS v3.5 không dùng, nhưng thêm vào để phòng)

    server.on("/api/admin-hash", HTTP_GET, [](AsyncWebServerRequest *request) {

        request->send(200, "text/plain", readFile(ADMIN_HASH_FILE));

    });

    // --- KẾT THÚC CẬP NHẬT ROUTE CÀI ĐẶT ---

    

    server.on("/api/history", HTTP_GET, [](AsyncWebServerRequest *request){

        JsonDocument doc;

        JsonArray history = doc.to<JsonArray>();


        File historyDir = LittleFS.open("/history");

        File file = historyDir.openNextFile();

        while(file){

            String fileName = file.name();

            if (fileName.endsWith(".json")) {

                String filePath = "/history/" + fileName;

                File ticketFile = LittleFS.open(filePath, "r");

                if(ticketFile) {

                    JsonDocument ticketDoc;

                    if (deserializeJson(ticketDoc, ticketFile) == DeserializationError::Ok) {

                        

                        JsonObject obj = history.add<JsonObject>();

                        obj["date"] = ticketDoc["id"]; // Dùng 'id' làm 'date'

                        obj["customer"] = ticketDoc["customer"];

                        obj["id"] = ticketDoc["id"]; // Gửi 'id' (timestamp)


                        float totalW = 0;

                        long totalP = 0;

                        JsonArray weighments = ticketDoc["weighments"];

                        for (JsonVariant v : weighments) {

                            totalW += v["weight"].as<float>();

                            String totalStr = v["total"].as<String>();

                            totalStr.replace(".", "");

                            totalP += totalStr.toInt();

                        }

                        obj["totalWeight"] = totalW;

                        obj["totalPrice"] = totalP;


                    } else {

                        Serial.printf("Loi doc JSON tu file: %s\n", filePath.c_str());

                    }

                    ticketFile.close();

                }

            }

            file.close();

            file = historyDir.openNextFile();

        }

        historyDir.close();

        

        String response;

        serializeJson(doc, response);

        request->send(200, "application/json", response);

    });


    server.on("/api/ticket", HTTP_GET, [](AsyncWebServerRequest *request){

        if (request->hasParam("id")) {

            String id = request->getParam("id")->value(); // ID LÀ TIMESTAMP

            String path = "/history/" + id + ".json";

            if (LittleFS.exists(path)) {

                request->send(LittleFS, path, "application/json");

            } else {

                request->send(404, "text/plain", "Khong tim thay phieu");

            }

        } else {

            request->send(400, "text/plain", "Thieu ID phieu");

        }

    });


    server.on("/api/download", HTTP_GET, [](AsyncWebServerRequest *request){

        if (!request->hasParam("id")) {

            request->send(400, "text/plain", "Thieu ID phieu");

            return;

        }

        String id = request->getParam("id")->value(); // ID LÀ TIMESTAMP

        String path = "/history/" + id + ".json";

        if (!LittleFS.exists(path)) {

            request->send(404, "text/plain", "Khong tim thay phieu");

            return;

        }


        File ticketFile = LittleFS.open(path, "r");

        if (!ticketFile) {

            request->send(500, "text/plain", "Loi doc file phieu can");

            return;

        }


        JsonDocument doc;

        deserializeJson(doc, ticketFile);

        ticketFile.close();


        String fileContent = "";

        String ticketNum = doc["id"] | id; // Lấy ID (timestamp)

        

        fileContent += "              PHIEU CAN HANG\r\n"; // Đã xóa số phiếu

        fileContent += "------------------------------------------\r\n";

        

        String customer = doc["customer"] | "N/A";

        String address = doc["address"] | "N/A";

        String product = doc["product"] | "N/A";

        String unitPrice = doc["unitPrice"] | "0";


        fileContent += "Khach hang: " + removeAccents(customer) + "\r\n";

        fileContent += "Dia chi: " + removeAccents(address) + "\r\n";

        fileContent += "Loai hang: " + removeAccents(product) + "\r\n";

        fileContent += "Don gia: " + unitPrice + " VND/kg\r\n";

        

        fileContent += "------------------------------------------\r\n\r\n";

        fileContent += "STT | Khoi Luong | Thanh Tien\r\n";

        fileContent += "----|------------|---------------\r\n";


        float totalW = 0;

        long totalPrice = 0;

        JsonArray weighments = doc["weighments"];

        for (JsonVariant v : weighments) {

            String stt = v["stt"];

            String weight = v["weight"];

            String total = v["total"];

            

            String line = "";

            line += stt;

            while(line.length() < 4) line += " ";

            line += "| " + weight;

            while(line.length() < 17) line += " ";

            line += "| " + total + " VND\r\n";

            fileContent += line;


            totalW += weight.toFloat();

            total.replace(".", "");

            totalPrice += total.toInt();

        }


        fileContent += "==========================================\r\n";

        fileContent += "TONG CONG:\r\n";

        fileContent += " - Tong Khoi luong: " + String(totalW, 2) + " kg\r\n";

        fileContent += " - Tong Thanh tien: " + formatNumber(totalPrice) + " VND\r\n";

        fileContent += "==========================================\r\n";


        String safeCustomerName = removeAccents(customer);

        safeCustomerName.replace(" ", "_");

        String filename = "phieu-can-" + safeCustomerName + "-" + id + ".txt";


        AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", fileContent);

        response->addHeader("Content-Disposition", "attachment; filename=" + filename);

        request->send(response);

    });


    server.on("/api/ticket", HTTP_DELETE, [](AsyncWebServerRequest *request){

        if (request->hasParam("id")) {

            String id = request->getParam("id")->value(); // ID LÀ TIMESTAMP

            String path = "/history/" + id + ".json";

            if (LittleFS.exists(path)) {

                if (LittleFS.remove(path)) {

                    request->send(200, "text/plain", "Da xoa phieu thanh cong");

                } else {

                    request->send(500, "text/plain", "Loi khi xoa phieu");

                }

            } else {

                request->send(404, "text/plain", "Khong tim thay phieu de xoa");

            }

        } else {

            request->send(400, "text/plain", "Thieu ID phieu");

        }

    });


    AsyncCallbackJsonWebHandler* saveHandler = new AsyncCallbackJsonWebHandler("/api/save", [](AsyncWebServerRequest *request, JsonVariant &json) {

        checkStorageAndCleanUp(); 


        JsonObject jsonObj = json.as<JsonObject>();

        String idStr = jsonObj["id"].as<String>(); // Lấy ID (timestamp)

        String path = "/history/" + idStr + ".json";


        File file = LittleFS.open(path, "w");

        if (!file) {

            request->send(500, "text/plain", "Khong the tao file de luu");

            return;

        }

        if (serializeJson(jsonObj, file) == 0) {

            request->send(500, "text/plain", "Loi khi ghi file");

        } else {

            request->send(200, "text/plain", "Da luu phieu thanh cong");

        }

        file.close();

    });

    server.addHandler(saveHandler);


    server.on("/api/storage", HTTP_GET, [](AsyncWebServerRequest *request){

        JsonDocument doc;

        doc["total"] = LittleFS.totalBytes();

        doc["used"] = LittleFS.usedBytes();

        String response;

        serializeJson(doc, response);

        request->send(200, "application/json", response);

    });

    

    server.onNotFound([](AsyncWebServerRequest *request){

        request->redirect("/");

    });


    server.begin();

    Serial.println("Web Server va WebSocket da khoi dong.");

}


// --- LOOP (Từ v3.5) ---

void loop() {

    dnsServer.processNextRequest(); 

    ws.cleanupClients(); 

    

    String newWeight = readAndProcessSerial();

    

    if (newWeight != latestWeightString && newWeight.length() > 0) {

        latestWeightString = newWeight;

    }

    

    // Giữ nguyên logic gửi "ww...kg" của v3.5

    if (ws.count() > 0) {

        String formattedWeight = "ww" + latestWeightString + "kg";

        ws.textAll(formattedWeight.c_str()); 

    }


    delay(100); 

}