const express = require('express');
const router = express.Router();

// Importă conexiunea la baza de date
const pool = require('../db'); 

// Importă middleware-ul de autentificare
const authenticateToken = require('../middleware/auth');
function generateEAN13() {
    let barcode = '';
    for (let i = 0; i < 12; i++) {
        barcode += Math.floor(Math.random() * 10);
    }

    // Calculează cifra de control (checksum) pentru EAN-13
    let sum = 0;
    for (let i = 0; i < 12; i++) {
        const digit = parseInt(barcode[i]);
        sum += (i % 2 === 0) ? digit : digit * 3;
    }
    const checksum = (10 - (sum % 10)) % 10;
    return barcode + checksum;
}
// routes/products.js
router.post('/:id/promotions', async (req, res) => {
  try {
    const productId = req.params.id;
    const {
      discount_product_id,
      promotion_type,
      required_quantity,
      bonus_quantity,
      start_date,
      end_date,
      is_active
    } = req.body;

    if (!productId || isNaN(productId)) {
      return res.status(400).json({ error: "ID produs invalid" });
    }

    // Validări minime (poți extinde)
    if (!promotion_type || !start_date || !end_date) {
      return res.status(400).json({ error: "Date lipsă pentru promoție" });
    }

    await pool.promise().query(`
      INSERT INTO promotions (
        product_id,
        discount_product_id,
        promotion_type,
        required_quantity,
        bonus_quantity,
        start_date,
        end_date,
        is_active
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `, [
      productId,
      discount_product_id || null,
      promotion_type,
      required_quantity || 0,
      bonus_quantity || 0,
      start_date,
      end_date,
      is_active !== undefined ? is_active : true
    ]);

    res.status(201).json({ message: "Promoție adăugată cu succes" });

  } catch (err) {
    console.error('Eroare la inserare promoție:', err);
    res.status(500).json({
      error: "Eroare server",
      details: err.message,
      stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
    });
  }
});
// routes/promotions.js (sau unde ai endpointurile)
router.get('/promotions', async (req, res) => {
  try {
    const [results] = await pool.promise().query(`
      SELECT 
        p.*,
        prod1.name AS product_name,
        prod2.name AS discount_product_name
      FROM promotions p
      LEFT JOIN products prod1 ON p.product_id = prod1.id
      LEFT JOIN products prod2 ON p.discount_product_id = prod2.id
    `);

    res.json(results);
  } catch (err) {
    console.error('Eroare la get promotions:', err);
    res.status(500).json({ 
      error: "Eroare server",
      details: err.message,
      stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
    });
  }
});
router.put('/update-promotii/:id', async (req, res) => {
  try {
    const promotionId = req.params.id;
    const {
      product_id,
      discount_product_id,
      promotion_type,
      required_quantity,
      bonus_quantity,
      start_date,
      end_date,
      is_active
    } = req.body;

    // Funcție pentru conversia datelor în format compatibil MySQL
    const formatDate = (isoString) => {
      if (!isoString) return null;
      const date = new Date(isoString);
      return date.toISOString().slice(0, 19).replace('T', ' ');
    };

    const formattedStartDate = formatDate(start_date);
    const formattedEndDate = formatDate(end_date);

    const [result] = await pool.promise().query(`
      UPDATE promotions SET
        product_id = ?,
        discount_product_id = ?,
        promotion_type = ?,
        required_quantity = ?,
        bonus_quantity = ?,
        start_date = ?,
        end_date = ?,
        is_active = ?
      WHERE id = ?
    `, [
      product_id,
      discount_product_id || null,
      promotion_type,
      required_quantity,
      bonus_quantity,
      formattedStartDate,
      formattedEndDate,
      is_active,
      promotionId
    ]);

    res.json({ message: 'Promoție actualizată cu succes' });

  } catch (err) {
    console.error('Eroare la actualizare promoție:', err);
    res.status(500).json({
      error: "Eroare server",
      details: err.message,
      stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
    });
  }
});

// routes/promotii.js
router.delete('/delete/:id', async (req, res) => {
  try {
    const promotionId = req.params.id;

    if (!promotionId || isNaN(promotionId)) {
      return res.status(400).json({ error: "ID invalid" });
    }

    const [result] = await pool.promise().query(
      `DELETE FROM promotions WHERE id = ?`,
      [promotionId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ error: "Promoție inexistentă" });
    }

    res.json({ message: "Promoție ștearsă cu succes" });
  } catch (err) {
    console.error('Eroare la ștergerea promoției:', err);
    res.status(500).json({
      error: "Eroare server",
      details: err.message
    });
  }
});
router.get('/list_products', async (req, res) => {
  const { tip_produs } = req.query;

  let sql = `
    SELECT 
      p.id, 
      p.name, 
      p.barcode, 
      p.price, 
      p.vat_rate, 
      p.category, 
      p.unit_of_measure, 
      p.garantie_sgr,
      p.tip_produs,
      COALESCE(s.stoc_actual, 0) AS stoc_actual
    FROM products p
    LEFT JOIN stoc_produse s ON p.id = s.id_produs
  `;

  const params = [];

  // Adaugă filtrul doar dacă este specificat tip_produs
  if (tip_produs) {
    sql += ' WHERE p.tip_produs = ?';
    params.push(tip_produs);
  }

  try {
    const [results] = await pool.promise().query(sql, params);
    res.json(results);
  } catch (err) {
    console.error('Error fetching products:', err);
    res.status(500).json({ message: 'Error fetching products' });
  }
});
router.post('/create-promotii', async (req, res) => {
  try {
    const {
      product_id,
      discount_product_id,
      promotion_type,
      required_quantity,
      bonus_quantity,
      start_date,
      end_date,
      is_active
    } = req.body;

    // Funcție pentru conversia datelor în format compatibil MySQL
    const formatDate = (isoString) => {
      if (!isoString) return null;
      const date = new Date(isoString);
      return date.toISOString().slice(0, 19).replace('T', ' ');
    };

    const formattedStartDate = formatDate(start_date);
    const formattedEndDate = formatDate(end_date);

    const [result] = await pool.promise().query(`
      INSERT INTO promotions (
        product_id,
        discount_product_id,
        promotion_type,
        required_quantity,
        bonus_quantity,
        start_date,
        end_date,
        is_active
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `, [
      product_id,
      discount_product_id || null,
      promotion_type,
      required_quantity,
      bonus_quantity,
      formattedStartDate,
      formattedEndDate,
      is_active
    ]);

    res.status(201).json({ message: 'Promoție adăugată cu succes', insertId: result.insertId });

  } catch (err) {
    console.error('Eroare la crearea promoției:', err);
    res.status(500).json({
      error: "Eroare server",
      details: err.message,
      stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
    });
  }
});


module.exports = router;