//var base_url='http://127.0.0.1:5000/';
// On prk_home.js or inside a <script> tag on prk_home.html

function auth_login(){
    const formData = {
        username: document.getElementById('login_name').value,
        password: document.getElementById('password').value,

    };

    // Send the data to the backend
    axios.post(`/login`, formData,)
        .then(response => {
            console.log(response.data);
            token=response.data.access_token;
            //alert(token);

            localStorage.setItem('token', token);
            window.location.href=(`/prk_home`);
        })
        .catch(error => {

            alert('Invalid User or Password');
        });
}

function logout(){
localStorage.removeItem('token'); // if stored in localStorage
sessionStorage.removeItem('token'); // if stored in sessionStorage

}
async function map_parking_data_x() {
    let park_data = document.getElementById('park_data');
    let x = 0; // You can adjust this based on your requirements
    try {
        const res = await axios.post('/prk_operation_api', { "req": x });
        const data = res.data.Park_Info;  // Accessing the "Park_Info" directly
        console.log(data);

        // Define the table headers as per your requirement
        const head_key = ['Sn', 'Motorist Name', 'Type', 'Vehicle No', 'In Time', 'Out Time', 'Park Time', 'Amount', 'Paid Type', 'Action'];
        console.log(head_key);

        // Prepare table header
        let head_Col = head_key.map(key => `<th>${key}</th>`).join('');
        const thead = `<thead><tr>${head_Col}</tr></thead>`;
        let tbody = '';

        // Initialize an array to store totals for numeric columns
        const totals = new Array(head_key.length).fill(0);

        // Helper function to check if a value is numeric
        const isNumeric = (value) => {
            return !isNaN(value) && value !== ' ' && value !== null;
        };

        // Helper function to check if a value is an amount (contains a decimal point)
        const isAmount = (value) => {
            return isNumeric(value) && value.toString().includes('.');
        };

        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                let rowData = [
                    i + 1, // Serial number
                    data[i].motorist_name,
                    data[i].type,
                    data[i].vehicle_plate_no,
                    data[i].park_in_time,
                    data[i].park_out_time,
                    data[i].total_park_time,
                    data[i].amount,
                    data[i].paid_type,
                    '<button>Action</button>' // Placeholder for actions
                ];

                let dt = '';

                // Generate table cells dynamically based on rowData
                for (let j = 0; j < rowData.length; j++) {
                    const value = rowData[j];
                    dt += `<td style="text-align: ${isNumeric(value) ? 'right' : 'left'};">${isNumeric(value) ? parseFloat(value) : value}</td>`;
                    
                    // If the value is an amount, add it to the totals array
                    if (isAmount(value)) {
                        totals[j] += parseFloat(value); // Accumulate totals for amounts
                    }
                }

                tbody += `<tr>${dt}</tr>`;
            }
        } else {
            tbody = `<tr><td colspan="${head_key.length}" style="text-align:center;">Data Not Found</td></tr>`;
        }

        // Add a totals row
        let totalsRow = '<tr><td style="text-align: right;">Total</td>';
        for (let j = 0; j < totals.length; j++) {
            totalsRow += `<td style="text-align: ${totals[j] ? 'right' : 'left'};">${totals[j] !== 0 ? totals[j].toFixed(2) : ''}</td>`;
        }
        totalsRow += '</tr>';

        park_data.innerHTML = '';
        park_data.innerHTML = thead + `<tbody>${tbody}${totalsRow}</tbody>`;
    } catch (error) {
        console.error('An error occurred:', error);
    }
}

//map_parking_data_xx();

//QR Code
async function map_parking_data() {
    let park_data = document.getElementById('park_data');
    let x = 0; // You can adjust this based on your requirements
    try {
        const res = await axios.post('/prk_operation_api', { "req": x });
        const data = res.data.Park_Info;  // Accessing the "Park_Info" directly
        console.log(data);

        // Define the table headers as per your requirement
        const head_key = ['Sn', 'Motorist Name', 'Type', 'Vehicle No', 'In Time', 'Out Time', 'Park Time', 'Amount', 'Paid Type', 'Action'];
        console.log(head_key);

        // Prepare table header
        let head_Col = head_key.map(key => `<th>${key}</th>`).join('');
        const thead = `<thead><tr>${head_Col}</tr></thead>`;
        let tbody = '';

        // Initialize an array to store totals for numeric columns
        const totals = new Array(head_key.length).fill(0);

        // Helper function to check if a value is numeric
        const isNumeric = (value) => {
            return !isNaN(value) && value !== ' ' && value !== null;
        };

        // Helper function to check if a value is an amount (contains a decimal point)
        const isAmount = (value) => {
            return isNumeric(value) && value.toString().includes('.');
        };

        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                let rowData = [
                    i + 1, // Serial number
                    data[i].motorist_name,
                    data[i].type,
                    data[i].vehicle_plate_no,
                    data[i].park_in_time,
                    data[i].park_out_time,
                    data[i].total_park_time,
                    data[i].amount,
                    data[i].paid_type,
                    `<button onclick="printRow(${i})">Print</button>` // Print button
                ];

                let dt = '';

                // Generate table cells dynamically based on rowData
                for (let j = 0; j < rowData.length; j++) {
                    const value = rowData[j];
                    dt += `<td style="text-align: ${isNumeric(value) ? 'right' : 'left'};">${isNumeric(value) ? parseFloat(value) : value}</td>`;
                    
                    // If the value is an amount, add it to the totals array
                    if (isAmount(value)) {
                        totals[j] += parseFloat(value); // Accumulate totals for amounts
                    }
                }

                tbody += `<tr>${dt}</tr>`;
            }
        } else {
            tbody = `<tr><td colspan="${head_key.length}" style="text-align:center;">Data Not Found</td></tr>`;
        }

        // Add a totals row
        let totalsRow = '<tr><td style="text-align: right;">Total</td>';
        for (let j = 0; j < totals.length-1; j++) {
            totalsRow += `<td style="text-align: ${totals[j] ? 'right' : 'left'};">${totals[j] !== 0 ? totals[j].toFixed(2) : ''}</td>`;
        }
        totalsRow += '</tr>';

        park_data.innerHTML = '';
        park_data.innerHTML = thead + `<tbody>${tbody}${totalsRow}</tbody>`;
    } catch (error) {
        console.error('An error occurred:', error);
    }
}

function printRowx(index) {
    const data = document.querySelectorAll('#park_data tbody tr')[index];
    const rowInfo = Array.from(data.children).map(td => td.innerText).join('\n');

    const qrCodeData = JSON.stringify({
        'Motorist Name': data.children[1].innerText,
        'Type': data.children[2].innerText,
        'Vehicle No': data.children[3].innerText,
        'In Time': data.children[4].innerText,
        'Out Time': data.children[5].innerText,
        'Park Time': data.children[6].innerText,
        'Amount': data.children[7].innerText,
        'Paid Type': data.children[8].innerText
    });

    const qrCode = new QRious({
        value: qrCodeData,
        size: 200
    });

    const printWindow = window.open('', '', 'height=400,width=600');
    printWindow.document.write('<html><head><title>Print</title></head><body>');
    printWindow.document.write('<h2>Parking Info</h2>');
    printWindow.document.write('<pre>' + rowInfo + '</pre>');
    printWindow.document.write('<h3>QR Code</h3>');
    printWindow.document.write(`<img src="${qrCode.toDataURL()}" alt="QR Code" height="40px" widht="40px" align="center"><br>`); // Display QR code as an image
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.print();
}

function printRow2(index) {
    const data = document.querySelectorAll('#park_data tbody tr')[index];
    const headers = ['Sn', 'Motorist Name', 'Type', 'Vehicle No', 'In Time', 'Out Time', 'Park Time', 'Amount', 'Paid Type'];
    let rowInfo = '';

    // Build the row info with headers in bold and smaller font size
    for (let i = 0; i < headers.length; i++) {
        rowInfo += `<strong style="font-size: 12px;">${headers[i]}:</strong> ${data.children[i].innerText}<br>`;
    }

    const qrCodeData = JSON.stringify({
        'Motorist Name': data.children[1].innerText,
        'Type': data.children[2].innerText,
        'Vehicle No': data.children[3].innerText,
        'In Time': data.children[4].innerText,
        'Out Time': data.children[5].innerText,
        'Park Time': data.children[6].innerText,
        'Amount': data.children[7].innerText,
        'Paid Type': data.children[8].innerText
    });

    const qrCode = new QRious({
        value: qrCodeData,
        size: 200
    });

    const printWindow = window.open('', '', 'height=400,width=600');
    printWindow.document.write(`
        <html>
            <head>
                <title>Print</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        text-align: left;
                        margin: 20px;
                        width: 302.4px; /* 80mm in pixels */
                        height: 100%;   /* Adjust as needed */

                    }
                    .border {
                        border: 2px solid black;
                        padding: 10px;
                        display: inline-block;
                    }
                    pre {
                        white-space: pre-wrap; /* Ensure long text wraps */
                        word-wrap: break-word; /* Break long words if necessary */
                    }
                </style>
            </head>
            <body>
                <div class="border">
                    <h2>Parking Info</h2>
                    <div>${rowInfo}</div> <!-- Use a div to allow HTML rendering -->
                    <h3>QR Code</h3>
                    <img src="${qrCode.toDataURL()}" alt="QR Code" height="200px" width="200px"><br>
                </div>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.print();
}
async function printRow(index) {
    const data = document.querySelectorAll('#park_data tbody tr')[index];
    const headers = ['Sn', 'Motorist Name', 'Type', 'Vehicle No', 'In Time', 'Out Time', 'Park Time', 'Amount'];
    let rowInfo = '';

    // Build the row info with headers in bold and smaller font size
    for (let i = 0; i < headers.length; i++) {
        rowInfo += `<strong style="font-size: 12px;">${headers[i]}:</strong> ${data.children[i].innerText}<br>`;
    }

    const qrCodeData = JSON.stringify({
        'Motorist Name': data.children[1].innerText,
        'Type': data.children[2].innerText,
        'Vehicle No': data.children[3].innerText,
        'In Time': data.children[4].innerText,
        'Out Time': data.children[5].innerText,
        'Park Time': data.children[6].innerText,
        'Amount': data.children[7].innerText
    });

    // Generate QR code
    const qrCodeDataUrl = await new Promise((resolve) => {
        const qrCode = new QRious({
            value: qrCodeData,
            size: 200
        });
        resolve(qrCode.toDataURL());
    });

    // Create a hidden iframe
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    
    const doc = iframe.contentWindow.document;
    doc.open();
    doc.write(`
        <html>
            <head>
                <title>Print</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        text-align: left;
                        margin: 10px;
                        width: 302.4px; /* 80mm in pixels */
                        height: auto;   /* Adjust as needed */
                    }
                    .border {
                        border: 1px solid black;
                        padding:10px;
                        display: inline-block;
                        width:275px;
                    }
                    pre {
                        white-space: pre-wrap; /* Ensure long text wraps */
                        word-wrap: break-word; /* Break long words if necessary */
                    }
                    img {
                        margin-left:80px;   
                    }
                </style>
            </head>
            <body>
                <div class="border">
                    <h4>The Malla Hotel</h4>
                    <h6>Parking Info</h6>
                    <div>${rowInfo}</div>
                    <img src="${qrCodeDataUrl}" alt="QR Code" height="100px" width="100px"><br>
                </div>
            </body>
        </html>
    `);
    doc.close();

    // Trigger the print
    iframe.contentWindow.focus(); // Focus on the iframe
    iframe.contentWindow.print(); // Open print dialog
}


async function map_parking_free_data() {
    let park_data = document.getElementById('park_free_data');
    let x = 0; // You can adjust this based on your requirements
    try {
        const res = await axios.post('/prk_operation_api', { "req": x });
        const data = res.data.Park_Info;  // Accessing the "Park_Info" directly
        console.log(data);

        // Define the table headers as per your requirement
        const head_key = ['Sn', 'Motorist Name', 'Type', 'Vehicle No', 'In Time', 'Out Time', 'Park Time', 'Amount', 'Paid Type', 'Action'];
        console.log(head_key);

        // Prepare table header
        let head_Col = head_key.map(key => `<th>${key}</th>`).join('');
        const thead = `<thead><tr>${head_Col}</tr></thead>`;
        let tbody = '';

        // Initialize an array to store totals for numeric columns
        const totals = new Array(head_key.length).fill(0);

        // Helper function to check if a value is numeric
        const isNumeric = (value) => {
            return !isNaN(value) && value !== ' ' && value !== null;
        };

        // Helper function to check if a value is an amount (contains a decimal point)
        const isAmount = (value) => {
            return isNumeric(value) && value.toString().includes('.');
        };

        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                let rowData = [
                    i + 1, // Serial number
                    data[i].motorist_name,
                    data[i].type,
                    data[i].vehicle_plate_no,
                    data[i].park_in_time,
                    data[i].park_out_time,
                    data[i].total_park_time,
                    data[i].amount,
                    data[i].paid_type,
                    `<button onclick="printRow(${data[i].id})">Free Allow</button>` // Print button
                ];

                let dt = '';

                // Generate table cells dynamically based on rowData
                for (let j = 0; j < rowData.length; j++) {
                    const value = rowData[j];
                    dt += `<td style="text-align: ${isNumeric(value) ? 'right' : 'left'};">${isNumeric(value) ? parseFloat(value) : value}</td>`;
                    
                    // If the value is an amount, add it to the totals array
                    if (isAmount(value)) {
                        totals[j] += parseFloat(value); // Accumulate totals for amounts
                    }
                }

                tbody += `<tr>${dt}</tr>`;
            }
        } else {
            tbody = `<tr><td colspan="${head_key.length}" style="text-align:center;">Data Not Found</td></tr>`;
        }

        // Add a totals row
        let totalsRow = '<tr><td style="text-align: right;">Total</td>';
        for (let j = 0; j < totals.length-1; j++) {
            totalsRow += `<td style="text-align: ${totals[j] ? 'right' : 'left'};">${totals[j] !== 0 ? totals[j].toFixed(2) : ''}</td>`;
        }
        totalsRow += '</tr>';

        park_data.innerHTML = '';
        park_data.innerHTML = thead + `<tbody>${tbody}${totalsRow}</tbody>`;
    } catch (error) {
        console.error('An error occurred:', error);
    }
}

map_parking_data();
map_parking_free_data();

