<!DOCTYPE html>
<html lang="vi" class="h-full bg-gray-100">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ứng dụng Chấm công</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .fixed-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 100;
            width: 100%;
            max-width: 28rem;
        }

        #lastCheckContainer,
        #historyContainer {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 100;
            width: 100%;
            max-width: 28rem;
        }
    </style>
</head>

<body class="h-full bg-gray-100">
    <div class="min-h-full">
        <header class="bg-white shadow">
            <div class="max-w-7xl mx-auto px-4 py-4 sm:px-6 lg:px-8">
                <h1 class="text-2xl sm:text-3xl font-bold tracking-tight text-gray-900">Chấm công</h1>
            </div>
        </header>

        <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
            <div id="loginForm" class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
                <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
                    <form class="space-y-6">
                        <div>
                            <label for="username" class="block text-sm font-medium text-gray-700">Tên đăng nhập</label>
                            <input id="username" type="text" required
                                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                        </div>
                        <div>
                            <label for="password" class="block text-sm font-medium text-gray-700">Mật khẩu</label>
                            <input id="password" type="password" required
                                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                        </div>
                        <div class="flex items-center">
                            <input id="rememberLogin" type="checkbox"
                                class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                            <label for="rememberLogin" class="ml-2 block text-sm text-gray-900">Ghi nhớ đăng
                                nhập</label>
                        </div>
                        <button id="loginBtn" type="button"
                            class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Đăng
                            nhập</button>
                    </form>
                </div>
            </div>

            <!-- Sửa lại phần checkInOutChoice -->
            <div id="checkInOutChoice" class="hidden mt-8 sm:mx-auto sm:w-full sm:max-w-md">
                <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
                    <div class="space-y-4">
                        <button id="checkInBtn"
                            class="w-full py-3 px-4 rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700">Check
                            In</button>
                        <button id="checkOutBtn"
                            class="w-full py-3 px-4 rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700">Check
                            Out</button>
                        <!-- Thêm 2 nút này vào đây -->
                        <button id="viewLastCheckBtn"
                            class="w-full py-3 px-4 rounded-md shadow-sm text-white bg-yellow-600 hover:bg-yellow-700">Xem
                            ảnh chấm công gần nhất</button>
                        <button id="viewHistoryBtn"
                            class="w-full py-3 px-4 rounded-md shadow-sm text-white bg-purple-600 hover:bg-purple-700">Xem
                            lịch sử chấm công</button>
                        <button id="logoutBtn"
                            class="w-full py-3 px-4 rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700">Đăng
                            xuất</button>
                    </div>
                </div>
            </div>

            <div id="cameraContainer" class="hidden mt-8 sm:mx-auto sm:w-full sm:max-w-md">
                <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
                    <div class="space-y-6">
                        <div class="relative">
                            <video id="camera" class="w-full rounded-lg shadow-lg" autoplay playsinline></video>
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <button id="switchCameraBtn"
                                class="flex items-center justify-center py-3 px-4 rounded-md text-white bg-gray-600 hover:bg-gray-700">
                                <i class="fas fa-sync-alt mr-2"></i>Đổi Camera
                            </button>
                            <button id="captureBtn"
                                class="flex items-center justify-center py-3 px-4 rounded-md text-white bg-blue-600 hover:bg-blue-700">
                                <i class="fas fa-camera mr-2"></i>Chụp ảnh vào
                            </button>
                        </div>
                        <button id="captureOutBtn"
                            class="hidden w-full flex items-center justify-center py-3 px-4 rounded-md text-white bg-green-600 hover:bg-green-700">
                            <i class="fas fa-camera mr-2"></i>Chụp ảnh ra
                        </button>
                        <button id="backBtn"
                            class="w-full flex items-center justify-center py-3 px-4 rounded-md text-white bg-gray-600 hover:bg-gray-700">
                            <i class="fas fa-arrow-left mr-2"></i>Quay lại
                        </button>

                    </div>
                </div>
            </div>
        </main>
    </div>
    <!-- Thêm vào main -->
    <div id="lastCheckContainer" class="hidden mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
            <div class="space-y-6">
                <img id="lastCheckImage" class="w-full rounded-lg shadow-lg" alt="Ảnh chấm công gần nhất">
                <div id="lastCheckInfo" class="text-sm text-gray-600"></div>
                <button id="backFromLastCheck"
                    class="w-full py-3 px-4 rounded-md shadow-sm text-white bg-gray-600 hover:bg-gray-700">Quay
                    lại</button>
            </div>
        </div>
    </div>

    <div id="historyContainer" class="hidden mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
            <div class="space-y-4">
                <h2 class="text-lg font-medium">Lịch sử chấm công</h2>
                <div id="historyList" class="space-y-3"></div>
                <button id="backFromHistory"
                    class="w-full py-3 px-4 rounded-md shadow-sm text-white bg-gray-600 hover:bg-gray-700">Quay
                    lại</button>
            </div>
        </div>
    </div>
    <div id="loadingBox" class="fixed inset-0 flex items-center justify-center bg-gray-900 bg-opacity-50 z-50 hidden">
        <div class="bg-white p-5 rounded-lg shadow-lg">
            <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-gray-900"></div>
            <p class="mt-3 text-gray-700">Đang xử lý...</p>
        </div>
    </div>

    <script>
        // Constants
        const APP_ID = '1216c729-76e6-4515-80c1-3b9c4ef3ed9e';
        const ACCESS_KEY = 'V2-X3g13-TINHw-bkl3F-Arpld-zMzvm-DoWDE-lsUXP-GCjuW';
        const API_URL = `https://www.appsheet.com/api/v2/apps/${APP_ID}/tables`;
        const IMGBB_API_KEY = '7267d539a8c541130ce4524afdc69ad3';
        const IMGBB_UPLOAD_URL = 'https://api.imgbb.com/1/upload';

        // State
        let stream;
        let facingMode = "environment";
        let currentUser = null;

        // Elements
        const elements = {
            camera: document.getElementById('camera'),
            captureBtn: document.getElementById('captureBtn'),
            captureOutBtn: document.getElementById('captureOutBtn'),
            switchCameraBtn: document.getElementById('switchCameraBtn'),
            backBtn: document.getElementById('backBtn'),
            cameraContainer: document.getElementById('cameraContainer'),
            checkInOutChoice: document.getElementById('checkInOutChoice'),
            loadingBox: document.getElementById('loadingBox'),
            checkInBtn: document.getElementById('checkInBtn'),
            checkOutBtn: document.getElementById('checkOutBtn'),
            logoutBtn: document.getElementById('logoutBtn'),
            loginBtn: document.getElementById('loginBtn'),
            loginForm: document.getElementById('loginForm'),
            username: document.getElementById('username'),
            password: document.getElementById('password'),
            rememberLogin: document.getElementById('rememberLogin')
        };

        // API Functions
        const apiRequest = async (tableName, action, data) => {
            try {
                const response = await axios.post(`${API_URL}/${tableName}/Action`, {
                    Action: action,
                    ...data
                }, {
                    headers: {
                        'ApplicationAccessKey': ACCESS_KEY,
                        'Content-Type': 'application/json'
                    }
                });
                return response.data;
            } catch (error) {
                throw new Error('API request failed: ' + error.message);
            }
        };

        // Camera Functions
        const startCamera = async () => {
            if (stream) stream.getTracks().forEach(track => track.stop());
            try {
                stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        facingMode,
                        width: { ideal: 1280 },
                        height: { ideal: 720 }
                    }
                });
                elements.camera.srcObject = stream;
            } catch (err) {
                showToast("Không thể truy cập camera", 'error');
            }
        };
        // Thêm elements mới
        Object.assign(elements, {
            viewLastCheckBtn: document.getElementById('viewLastCheckBtn'),
            viewHistoryBtn: document.getElementById('viewHistoryBtn'),
            lastCheckContainer: document.getElementById('lastCheckContainer'),
            historyContainer: document.getElementById('historyContainer'),
            lastCheckImage: document.getElementById('lastCheckImage'),
            lastCheckInfo: document.getElementById('lastCheckInfo'),
            historyList: document.getElementById('historyList'),
            backFromLastCheck: document.getElementById('backFromLastCheck'),
            backFromHistory: document.getElementById('backFromHistory')
        });

        // Thêm functions
        const getLastCheck = async () => {
            try {
                elements.loadingBox.classList.remove('hidden');
                const result = await apiRequest('ChamCong', 'Find', {
                    Properties: {
                        Selector: `Filter(ChamCong, and([HỌ VÀ TÊN]="${currentUser['Họ và Tên']}" ,[NGÀY] =today()))`
                    }
                });

                if (result?.[0]) {
                    const lastCheck = result[0];
                    elements.lastCheckImage.src = lastCheck["HÌNH ẢNH OUT"] || lastCheck["HÌNH ẢNH IN"];
                    elements.lastCheckInfo.innerHTML = `
                Ngày: ${lastCheck["NGÀY"]}<br>
                Check In: ${lastCheck["IN"] || 'Chưa check in'}<br>
                Check Out: ${lastCheck["OUT"] || 'Chưa check out'}<br>
                Địa chỉ: ${lastCheck["ĐỊA CHỈ OUT"] || lastCheck["ĐỊA CHỈ IN"]}
            `;
                    elements.checkInOutChoice.classList.add('hidden');
                    elements.lastCheckContainer.style.display = 'block'; // Thay vì remove hidden
                } else {
                    showToast('Không có dữ liệu chấm công', 'error');
                }
            } catch (error) {
                showToast('Lỗi tải dữ liệu', 'error');
            } finally {
                elements.loadingBox.classList.add('hidden');
            }
        };

        const getHistory = async () => {
            try {
                elements.loadingBox.classList.remove('hidden');
                const result = await apiRequest('ChamCong', 'Find', {
                    Properties: {
                        Selector: `Filter(ChamCong,[HỌ VÀ TÊN]="${currentUser['Họ và Tên']}")`
                    }
                });

                elements.historyList.innerHTML = result.map(record => `
            <div class="p-4 bg-gray-50 rounded-lg">
                <div class="font-medium">Ngày: ${record["NGÀY"]}</div>
                <div>Check In: ${record["IN"] || 'Chưa check in'}</div>
                <div>Check Out: ${record["OUT"] || 'Chưa check out'}</div>
                <div class="text-sm text-gray-500">Địa chỉ: ${record["ĐỊA CHỈ OUT"] || record["ĐỊA CHỈ IN"]}</div>
            </div>
        `).join('');

                elements.checkInOutChoice.style.display = 'none';
                elements.historyContainer.style.display = 'block';
            } catch (error) {
                showToast('Lỗi tải lịch sử', 'error');
            } finally {
                elements.loadingBox.classList.add('hidden');
            }
        };

        // Thêm event listeners
        elements.viewLastCheckBtn.addEventListener('click', getLastCheck);
        elements.viewHistoryBtn.addEventListener('click', getHistory);
        elements.backFromLastCheck.addEventListener('click', () => {
            elements.lastCheckContainer.style.display = 'none';
            elements.checkInOutChoice.style.display = 'block';
        });
        elements.backFromHistory.addEventListener('click', () => {
            elements.historyContainer.style.display = 'none';
            elements.checkInOutChoice.style.display = 'block';
        });
        const captureImage = async () => {
            const canvas = document.createElement('canvas');
            canvas.width = elements.camera.videoWidth;
            canvas.height = elements.camera.videoHeight;
            canvas.getContext('2d').drawImage(elements.camera, 0, 0);

            return new Promise((resolve) => {
                canvas.toBlob(async (blob) => {
                    const formData = new FormData();
                    formData.append('image', blob);
                    try {
                        const response = await axios.post(IMGBB_UPLOAD_URL, formData, {
                            params: { key: IMGBB_API_KEY }
                        });
                        resolve(response.data.data.url);
                    } catch {
                        resolve(null);
                    }
                }, 'image/jpeg', 0.8);
            });
        };

        // Location Functions
        const getLocation = () => new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(
                pos => resolve(`${pos.coords.latitude},${pos.coords.longitude}`),
                () => reject('Không xác định được vị trí'),
                { timeout: 5000 }
            );
        });

        // Check In/Out Functions
        const getBasicInfo = () => {
            const currentTime = moment().tz("Asia/Ho_Chi_Minh");
            return {
                fullName: currentUser['Họ và Tên'],
                date: currentTime.format('DD/MM/YYYY'),
                timeStr: currentTime.format('HH:mm:ss'),
                datee: currentTime.format('YYYY-MM-DD'),
                idChamCong: `${currentUser['Họ và Tên']}${currentTime.format('DD/MM/YYYY')}`
            };
        };

        const handleCheckInOut = async (type) => {
            elements.loadingBox.classList.remove('hidden');
            try {
                const info = getBasicInfo();
                const [existingRecord] = await apiRequest('ChamCong', 'Find', {
                    Properties: { Selector: `Filter(ChamCong,[ID CV]="${info.idChamCong}")` }
                }) || [];

                if (type === 'out' && !existingRecord?.IN) {
                    throw new Error("Chưa check-in!");
                }

                const [location, imageUrl] = await Promise.all([
                    getLocation(),
                    captureImage()
                ]);

                if (!imageUrl) throw new Error('Không thể upload ảnh');

                const historyEntry = `${info.fullName} - ${info.date} ${info.timeStr} - ${location}`;
                const newData = {
                    "ID CV": info.idChamCong,
                    "NGÀY": info.datee,
                    "HỌ VÀ TÊN": info.fullName,
                    "GHI CHÚ": `Check ${type} qua API`
                };

                if (type === 'in') {
                    Object.assign(newData, {
                        "IN": info.timeStr,
                        "HÌNH ẢNH IN": imageUrl,
                        "ĐỊA CHỈ IN": location,
                        "LỊCH SỬ IN": existingRecord?.["LỊCH SỬ IN"] ?
                            `${existingRecord["LỊCH SỬ IN"]}\n${historyEntry}` : historyEntry
                    });
                } else {
                    Object.assign(newData, {
                        ...existingRecord,
                        "OUT": info.timeStr,
                        "HÌNH ẢNH OUT": imageUrl,
                        "ĐỊA CHỈ OUT": location,
                        "LỊCH SỬ OUT": existingRecord["LỊCH SỬ OUT"] ?
                            `${existingRecord["LỊCH SỬ OUT"]}\n${historyEntry}` : historyEntry
                    });
                }

                await apiRequest('ChamCong', existingRecord ? 'Edit' : 'Add', { Rows: [newData] });
                showToast(`Check ${type} thành công!`);
                elements.cameraContainer.classList.add('hidden');
                elements.checkInOutChoice.classList.remove('hidden');
            } catch (error) {
                showToast(error.message || 'Lỗi không xác định', 'error');
            } finally {
                elements.loadingBox.classList.add('hidden');
            }
        };

        // UI Functions
        const showToast = (message, type = 'success') => {
            Toastify({
                text: message,
                duration: 3000,
                close: true,
                gravity: "top",
                position: "center",
                backgroundColor: type === 'error' ? "#ff0000" : "#4CAF50",
            }).showToast();
        };

        // Auth Functions
        const login = async () => {
            elements.loadingBox.classList.remove('hidden');
            try {
                const result = await apiRequest('DSNV', 'Find', {
                    Properties: {
                        Selector: `Filter(DSNV, and([username]="${elements.username.value}",[password]="${elements.password.value}"))`
                    }
                });

                if (result?.[0]) {
                    currentUser = result[0];
                    if (elements.rememberLogin.checked) {
                        localStorage.setItem('username', elements.username.value);
                        localStorage.setItem('fullName', currentUser['Họ và Tên']);
                    }
                    elements.loginForm.classList.add('hidden');
                    elements.checkInOutChoice.classList.remove('hidden');
                    showToast(`Xin chào, ${currentUser['Họ và Tên']}!`);
                } else {
                    showToast('Thông tin đăng nhập không đúng!', 'error');
                }
            } catch (error) {
                showToast('Lỗi đăng nhập', 'error');
            } finally {
                elements.loadingBox.classList.add('hidden');
            }
        };

        const logout = () => {
            localStorage.removeItem('username');
            localStorage.removeItem('fullName');
            currentUser = null;
            elements.checkInOutChoice.classList.add('hidden');
            elements.cameraContainer.classList.add('hidden');
            elements.loginForm.classList.remove('hidden');
            elements.username.value = '';
            elements.password.value = '';
        };

        const checkLoginStatus = () => {
            const savedUsername = localStorage.getItem('username');
            const savedFullName = localStorage.getItem('fullName');
            if (savedUsername && savedFullName) {
                currentUser = { 'Họ và Tên': savedFullName };
                elements.loginForm.classList.add('hidden');
                elements.checkInOutChoice.classList.remove('hidden');
                showToast(`Xin chào, ${savedFullName}!`);
            }
        };

        // Event Listeners
        elements.loginBtn.addEventListener('click', login);
        elements.logoutBtn.addEventListener('click', logout);

        elements.checkInBtn.addEventListener('click', () => {
            elements.checkInOutChoice.classList.add('hidden');
            elements.cameraContainer.classList.remove('hidden');
            elements.captureBtn.classList.remove('hidden');
            elements.captureOutBtn.classList.add('hidden');
        });

        elements.checkOutBtn.addEventListener('click', () => {
            elements.checkInOutChoice.classList.add('hidden');
            elements.cameraContainer.classList.remove('hidden');
            elements.captureBtn.classList.add('hidden');
            elements.captureOutBtn.classList.remove('hidden');
        });

        elements.backBtn.addEventListener('click', () => {
            elements.cameraContainer.classList.add('hidden');
            elements.checkInOutChoice.classList.remove('hidden');
        });

        elements.switchCameraBtn.addEventListener('click', () => {
            facingMode = facingMode === "user" ? "environment" : "user";
            startCamera();
        });

        elements.captureBtn.addEventListener('click', () => handleCheckInOut('in'));
        elements.captureOutBtn.addEventListener('click', () => handleCheckInOut('out'));



        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            checkLoginStatus();
            startCamera();
        });

    </script>
</body>

</html>