const express = require('express');
const fs = require('fs');
const path = require('path');
const { execFile } = require('child_process');
const cors = require('cors');

const router = express.Router();
const RECEIPT_DIR = path.join(__dirname, 'bonuri');
const CMD_PATH = path.join(__dirname, 'datecs', 'dude-cmd.exe');

router.use(express.json());
router.use(cors()); // Permite cereri de la orice IP

function runDudeCmdWithInputFile(inputFilePath, callback) {
    const command = [
        "--rs232", 
        "--rs232-port", "1",
        "--rs232-baud", "115200",
        "--input", inputFilePath,
        "--language", "ro"
    ];

    console.log(`Executing: ${CMD_PATH} ${command.join(" ")}`);

    execFile(CMD_PATH, command, (error, stdout, stderr) => {
        if (error) {
            console.error("ERROR executing dude-cmd.exe");
            console.error("Exit Code:", error.code);
            console.error("STDOUT:", stdout.trim());
            console.error("STDERR:", stderr.trim());

            let errorMessage = "Eroare la procesarea comenzii.";

            if (stdout.includes("Timeout expired. (-6)")) {
                errorMessage = "Casa de marcat nu răspunde. Verificați conexiunea.";
            } else if (stdout.includes("-100403")) {  // Verificăm eroarea -100403
                errorMessage = "Lipsa hartie";
            } else if (stdout.includes("-100404")) {  // Verificăm eroarea -100403
                errorMessage = "Capac Deschis";
            } else if (stdout.includes("-100405")) {  // Verificăm eroarea -100403
                errorMessage = "Atentie! Se termina hartia";
            } else if (stdout.includes("-110811")) {  // Verificăm eroarea -100403
                errorMessage = "S-au depasit 24 ore de la deschiderea turei Emiteti un Raport Z";
            }

            return callback(false, errorMessage);
        }

        console.log("Command executed successfully!");
        console.log("STDOUT:", stdout.trim());
        console.log("STDERR:", stderr.trim());

        callback(true, "Raport generat cu succes.");
    });
}

router.post('/print-receipt', (req, res) => {
    console.log("Received request on /print-receipt");
    const data = req.body;

    if (!data || !Array.isArray(data.products) || data.products.length === 0) {
        return res.status(400).json({ status: "error", message: "No products provided" });
    }

    const modIncasare = Array.isArray(data.mod_incasare) ? data.mod_incasare : [];
    const cuiBon = data.CuiBon || {};
    const cuiText = cuiBon.cuitext || '';
    const cuiClient = cuiBon.cuiclient || '';

    let commands = [`48,1[\\t]0001[\\t]1[\\t]${cuiText}[\\t]${cuiClient}[\\t]`];

    data.products.forEach(product => {
        commands.push(`49,${product.product_name?.slice(0, 30) || 'Product'}[\\t]${product.id_cota || 0}[\\t]${(product.unit_price || 0).toFixed(2)}[\\t]${(product.quantity || 0).toFixed(3)}[\\t][\\t]0.00[\\t]1[\\t]${product.unit_of_measure || 'buc'}[\\t]`);
    });

    modIncasare.forEach(payment => {
        if (payment.id_incasare != null && payment.valoare_total != null) {
            commands.push(`53,${payment.id_incasare}[\\t]${payment.valoare_total.toFixed(2)}[\\t]`);
        }
    });

    commands.push("56");

    const receiptPath = path.join(RECEIPT_DIR, `bon.inp`);

    fs.mkdirSync(RECEIPT_DIR, { recursive: true });

    try {
        fs.writeFileSync(receiptPath, commands.join("\n") + "\n", 'utf8');
    } catch (error) {
        console.error("Error writing file:", error);
        return res.status(500).json({ status: "error", message: "Failed to write receipt file" });
    }

    // Modificăm funcția pentru a prelua mesajele de eroare
    runDudeCmdWithInputFile(receiptPath, (success, errorMessage) => {
        if (success) {
            setTimeout(() => {
                if (fs.existsSync(receiptPath)) {
                    fs.unlinkSync(receiptPath);
                }
            }, 1000);
            return res.json({ status: "success", message: "Receipt saved and printed successfully", commands });
        } else {
            console.error("Error processing receipt:", errorMessage); // Log pentru eroare detaliată
            return res.status(500).json({ status: "error", message: errorMessage || "Error processing receipt" });
        }
    });
});

router.post('/introducere', async (req, res) => {
    try {
        const { suma, actiune } = req.body;

        // Verificăm dacă `suma` și `actiune` sunt valide
        if (typeof suma !== 'number') {
            return res.status(400).json({ status: "error", message: "Invalid or missing 'suma'" });
        }
        if (![0, 1].includes(actiune)) {
            return res.status(400).json({ status: "error", message: "'actiune' must be 0 (introducere) or 1 (scoatere)" });
        }

        // Creăm comanda
        const command = `70,${actiune}[\\t]${suma.toFixed(2)}[\\t]`;

        // Creăm directorul dacă nu există
        if (!fs.existsSync(RECEIPT_DIR)) {
            fs.mkdirSync(RECEIPT_DIR, { recursive: true });
        }

        // Calea fișierului
        const receiptPath = path.join(RECEIPT_DIR, `bon_${Date.now()}.inp`);

        // Scriem fișierul
        try {
            fs.writeFileSync(receiptPath, command + "\n", 'utf8');
        } catch (error) {
            console.error("Error writing file:", error);
            return res.status(500).json({ status: "error", message: "Failed to write receipt file" });
        }

        // Rulăm comanda și gestionăm răspunsul
        runDudeCmdWithInputFile(receiptPath, (success) => {
            if (success) {
                // Ștergem fișierul după 1 secundă
                setTimeout(() => {
                    if (fs.existsSync(receiptPath)) {
                        fs.unlinkSync(receiptPath);
                    }
                }, 1000);
                return res.json({ status: "success", message: "Receipt saved and printed successfully", command });
            }
            return res.status(500).json({ status: "error", message: "Error processing receipt" });
        });

    } catch (error) {
        console.error("Unexpected error:", error);
        return res.status(500).json({ status: "error", message: "Internal server error" });
    }
});


router.post('/raport', async (req, res) => {
    try {
        const { suma, actiune, actiune2 } = req.body;

        if (suma !== undefined && typeof suma !== 'number') {
            const errorMessage = "Invalid or missing 'suma'";
            console.log(" Error sent to frontend:", errorMessage);
            return res.status(400).json({ status: "error", message: errorMessage });
        }

        if (!actiune && !actiune2) {
            const errorMessage = "Either 'actiune' or 'actiune2' must be provided";
            console.log(" Error sent to frontend:", errorMessage);
            return res.status(400).json({ status: "error", message: errorMessage });
        }

        let command = [];
        let raportTip = "";

        if (actiune) {
            command.push("69,X[\\t]"); // Raport X
            raportTip = "X";
        } else if (actiune2) {
            command.push("69,D[\\t]\n");
            command.push("69,Z[\\t]\n");
            raportTip = "Z";
        }

        if (!fs.existsSync(RECEIPT_DIR)) {
            fs.mkdirSync(RECEIPT_DIR, { recursive: true });
        }

        const receiptPath = path.join(RECEIPT_DIR, `bon.inp`);

        try {
            fs.writeFileSync(receiptPath, command.join("") + "\n", 'utf8');
        } catch (error) {
            const errorMessage = "Failed to write receipt file";
            console.log("❌ Error sent to frontend:", errorMessage);
            console.error("Error writing file:", error);
            return res.status(500).json({ status: "error", message: errorMessage });
        }

        // Rulăm comanda și gestionăm răspunsul
        runDudeCmdWithInputFile(receiptPath, (success, message) => {
            if (success) {
                setTimeout(() => {
                    if (fs.existsSync(receiptPath)) {
                        fs.unlinkSync(receiptPath);
                    }
                }, 1000);
                console.log("✅ Success message sent to frontend:", message);
                return res.json({ status: "success", message });
            } else {
                console.log("❌ Error sent to frontend:", message);
                return res.status(500).json({ status: "error", message });
            }
        });

    } catch (error) {
        const errorMessage = "Internal server error";
        console.log("❌ Error sent to frontend:", errorMessage);
        console.error("Unexpected error:", error);
        return res.status(500).json({ status: "error", message: errorMessage });
    }
});


module.exports = router;
