const http = require('http');
const mysql = require('mysql2');

// Database configuration
const dbConfig = {
    host: '184.168.120.17',
    user: 'pm_fibre_2026',
    password: 'sE,CavL8*x~y',
    database: 'pm_fibre_2026',
    port: 3306
};

// Create connection pool
const pool = mysql.createPool(dbConfig);
const promisePool = pool.promise();

// Function to parse multiple punches from raw data
function parseMultiplePunches(rawData) {
    const punches = [];
    
    // Split by "Employee ID" pattern (looking for numbers at start of line)
    // The data format: EmployeeID Date Time [extra fields...]
    // Multiple punches appear as: 1 2026-05-22 16:52:17 ... 0 0 1 2026-05-22 16:52:18 ...
    
    const parts = rawData.trim().split(/\s+/);
    
    let i = 0;
    while (i < parts.length) {
        // Look for employee ID (should be a number)
        if (i < parts.length && /^\d+$/.test(parts[i])) {
            const employeeId = parseInt(parts[i]);
            i++;
            
            // Look for date (YYYY-MM-DD format)
            if (i < parts.length && /^\d{4}-\d{2}-\d{2}$/.test(parts[i])) {
                const dateStr = parts[i];
                i++;
                
                // Look for time (HH:MM:SS format)
                if (i < parts.length && /^\d{2}:\d{2}:\d{2}$/.test(parts[i])) {
                    const timeStr = parts[i];
                    i++;
                    
                    // Collect extra fields until next employee ID or end of data
                    const extraFields = [];
                    while (i < parts.length && !(/^\d+$/.test(parts[i]) && 
                           i+1 < parts.length && /^\d{4}-\d{2}-\d{2}$/.test(parts[i+1]))) {
                        extraFields.push(parts[i]);
                        i++;
                    }
                    
                    punches.push({
                        employeeId,
                        dateStr,
                        timeStr,
                        extraFields: extraFields.join(' ')
                    });
                }
            }
        } else {
            // Skip unknown data
            i++;
        }
    }
    
    return punches;
}

// Function to insert ATTLOG data (handles multiple punches)
async function insertATTLOG(rawData, url) {
    //console.log('Raw Data:', rawData);
    
    try {
        // Check if URL matches required parameters
        const isTargetUrl = url.includes('SN=NYU7253800254') && 
                           url.includes('table=ATTLOG') && 
                           url.includes('Stamp=9999');
        
        if (!isTargetUrl) {
            return false;
        }
        
        // Parse multiple punches from raw data
        const punches = parseMultiplePunches(rawData);
        
        //console.log(`Found ${punches.length} punch(es) to insert`);
        
        if (punches.length === 0) {
            //console.log('⚠️ No valid punches found in data');
            return false;
        }
        
        // Extract SN from URL
        const snMatch = url.match(/SN=([^&]+)/);
        const machineSn = snMatch ? snMatch[1] : null;
        
        // Insert each punch as a separate record
        let insertedCount = 0;
        
        for (const punch of punches) {
            const fullTimestamp = `${punch.dateStr} ${punch.timeStr}`;
            
            console.log(`Inserting - Employee ID: ${punch.employeeId}, DateTime: ${fullTimestamp}, Extra: ${punch.extraFields}`);
            
            const query = `INSERT INTO payroll_machine_log 
                (data_type, am_time, employee_am_id, machine_sn, extra_data, datetime) 
                VALUES (?, ?, ?, ?, ?, NOW())`;
            
            const values = [
                'ATTLOG',
                fullTimestamp,
                punch.employeeId,
                machineSn,
                punch.extraFields || null
            ];
            
            const [result] = await promisePool.execute(query, values);
            insertedCount++;
            console.log(`✅ Inserted ATTLOG ID: ${result.insertId}`);
        }
        
        //console.log(`✅ Successfully inserted ${insertedCount} of ${punches.length} punches`);
        return true;
        
    } catch (error) {
        //console.error('❌ Insert error:', error.message);
        //console.error('Full error:', error);
        return false;
    }
}

// HTTP Server
const server = http.createServer((req, res) => {
    //console.log(`\n📨 ${req.method} request received`);
    //console.log(`URL: ${req.url}`);
    
    if (req.method === 'GET') {
        //console.log(`GET: ${req.url}`);
        res.writeHead(200);
        res.end('OK');
        
    } else if (req.method === 'POST') {
        let body = '';
        
        req.on('data', chunk => {
            body += chunk.toString();
        });
        
        req.on('end', async () => {
            //console.log(`\n=== POST REQUEST FULL DATA ===`);
            //console.log(`URL: ${req.url}`);
            //console.log(`Raw Body: "${body}"`);
            //console.log(`Body length: ${body.length}`);
            
            // Check conditions
            const hasATTLOG = req.url.includes('table=ATTLOG');
            const hasCorrectSN = req.url.includes('SN=NYU7253800254');
            const hasStamp = req.url.includes('Stamp=9999');
            
            //console.log(`URL contains table=ATTLOG: ${hasATTLOG}`);
            //console.log(`URL contains SN=NYU7253800254: ${hasCorrectSN}`);
            //console.log(`URL contains Stamp=9999: ${hasStamp}`);
            
            if (hasATTLOG && hasCorrectSN && hasStamp) {
                //console.log('✅ Conditions met, inserting ATTLOG...');
                await insertATTLOG(body, req.url);
            } else {
                //console.log('⚠️ Conditions not met, skipping insert');
            }
            
            //console.log('-'.repeat(50));
            res.writeHead(200);
            res.end('OK');
        });
    }
});

// Start server
const PORT = 27501;
server.listen(PORT, '0.0.0.0', async () => {
    console.log(`🚀 Server running on port ${PORT}`);
    
    // Test database connection
    try {
        const [result] = await promisePool.query('SELECT 1 as test');
        console.log('✅ Database connected successfully');
    } catch (err) {
        console.error('❌ Database connection failed:', err.message);
    }
});