const express = require('express');
const path = require('path');
const fs = require('fs');
const base64url = require('base64url');
 const multer = require('multer');
const mqtt = require('mqtt');
const { log } = require('console');
 

const app = express();
const upload = multer({ dest: 'public/images/drawable' });

// Configure EJS
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

// Static images mapping (matches Android resources)
const staticImages = {
  home: 'am_card_pay_black.png',
  scan: 'am_barcode_black.png',
  printer: 'am_receipt_cart_black.png',
  settings: 'am_settings_black.png',
  mulberry: 'am_mulberry_logo_wide_color.png',
  // ... add other images
};

// MQTT Client setup
const client = mqtt.connect('mqtt://192.168.1.199', {
    username: 'ahkad',
    password: 'Ksenia11241124m'
});

// Topics list
const topics = ['pos/update', 'pos/update2', 'pos/update3'];

// Sample configuration data structure
const defaultConfig = {
  type: "configuration",
  navItems: [
    {
      navPage: "NAV_HOME",
      navName: "Payment",
      icon: { type: "resource", value: "home" },
      position: 0,
      enabled: true
    },
    {
      navPage: "NAV_SCAN",
      navName: "Scanner",
      icon: { type: "resource", value: "scan" },
      position: 1,
      enabled: true
    },
    {
      navPage: "NAV_PRINTER",
      navName: "Printer",
      icon: { type: "resource", value: "printer" },
      position: 2,
      enabled: true
    },
    {
      navPage: "NAV_SETTINGS",
      navName: "Settings",
      icon: { type: "resource", value: "settings" },
      position: 3,
      enabled: true
    }
  ],
  
    mainLogo: {
        type: "base64",
        value: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABlUAAAE "
    },
     
    footerLogo: {
        type: "base64",
        value: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABaQAAAWY"
     },
    footerLogoVisibility: "ture",
    footerGreetingText: "Привет Игорь! ))",
    footerText: "Mulberry, OOO Demo ©2025",
    primaryColor: "#002233"
};


client.on('connect', () => {
    console.log('Connected to MQTT broker');
});

client.on('error', (err) => {
    console.error('MQTT error:', err);
});
 
// Payment endpoint
app.get('/pay', (req, res) => {
    try {
        const paymentData = JSON.parse(base64url.decode(req.query.data));
        
        if (!paymentData.deviceId || !paymentData.paymentMethod || !paymentData.amount) {
            return res.redirect(`/error?message=${encodeURIComponent('Invalid payment data')}`);
        }
        console.log(paymentData);
        
        // Format data for the receipt
        const receiptData = {
            deviceId: paymentData.deviceId,
            appLogo: paymentData.appLogo,
            appColor: paymentData.appColor,
            paymentMethod: paymentData.paymentMethod,
            amount: paymentData.amount.toFixed(2),
            timestamp: new Date(paymentData.timestamp).toLocaleString(),
            transactionId: `TXN-${Math.random().toString(36).substr(2, 9).toUpperCase()}`
        };
        
        // Render EJS template with data
        res.render('receipt', { 
            title: 'DatexPay Virtual Bank - Receipt',
            ...receiptData
        });
        
    } catch (error) {
        res.redirect(`/error?message=${encodeURIComponent(error.message)}`);
    }
});

// ANSI escape code for grey text
const grey = '\x1b[90m';
const reset = '\x1b[0m'; // Reset to default color

// Handle Pay command
app.post('/pay-command', (req, res) => {
    const id = req.query.id; // Get the id from the query parameter
    const timestamp = new Date().toLocaleString(); // Get the current date and time
    console.log(`${grey}[${timestamp}] pay command on id: ${id}${reset}`);

    client.publish(id, 'PRINT_RECEIPT');
    res.send({ message: 'Receipt printed successfully!' });
});

// Handle Cancel command
app.post('/cancel-command', (req, res) => {
    const id = req.query.id; // Get the id from the query parameter
    const timestamp = new Date().toLocaleString(); // Get the current date and time
    console.log(`${grey}[${timestamp}] cancel command on id: ${id}${reset}`);

    client.publish(id, 'REJECT_RECEIPT');
    res.send({ message: 'Receipt rejected!' });
});

// Error page
app.get('/error', (req, res) => {
    res.render('error', { 
        title: 'Payment Error',
        message: req.query.message || 'An unknown error occurred'
    });
});


app.post('/upload', upload.single('image'), (req, res) => {
  const base64 = fs.readFileSync(req.file.path, 'base64');
  fs.unlinkSync(req.file.path); // Clean up
  res.json({ base64: `data:image/png;base64,${base64}` });
});

// Routes
app.get('/', (req, res) => {
  res.render('index', { 
    staticImages: Object.keys(staticImages),
    topics, 
    defaultConfig  
  });

});
app.post('/publish', (req, res) => {
  const { config, topic } = req.body;
  client.publish(topic, JSON.stringify(config));
  res.sendStatus(200);
});
 

app.listen(80, () => {
    console.log('Server running on port 80');
});