import { Router } from 'express';
import pool from '../db.js';
import { v4 as uuidv4 } from 'uuid';
const router = Router();
// Get all receipts
router.get('/', async (req, res) => {
    try {
        const [rows] = await pool.query(`
      SELECT 
        r.*, 
        c.name as customer_name,
        c.address as customer_address,
        c.email as customer_email,
        c.phone as customer_phone,
        c.vat_number as customer_vat_no,
        c.company as customer_company,
        i.invoice_number 
      FROM receipts r 
      LEFT JOIN customers c ON r.customer_id = c.id 
      LEFT JOIN invoices i ON r.invoice_id = i.id 
      ORDER BY r.date DESC
    `);
        res.json(rows);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
// Create receipt
router.post('/', async (req, res) => {
    const { customer_id, invoice_id, receipt_number, date, amount, payment_method, reference, notes } = req.body;
    const id = uuidv4();
    try {
        await pool.query('INSERT INTO receipts (id, customer_id, invoice_id, receipt_number, date, amount, payment_method, reference, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [id, customer_id, invoice_id, receipt_number, date, amount, payment_method, reference, notes]);
        // Also update invoice paid amount if linked
        if (invoice_id) {
            await pool.query('UPDATE invoices SET paid_amount = paid_amount + ?, status = CASE WHEN paid_amount + ? >= grand_total THEN "Paid" ELSE "Partial" END WHERE id = ?', [amount, amount, invoice_id]);
        }
        res.status(201).json({ id, customer_id, invoice_id, receipt_number, date, amount, payment_method, reference, notes });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
// Delete receipt
router.delete('/:id', async (req, res) => {
    const { id } = req.params;
    try {
        await pool.query('DELETE FROM receipts WHERE id = ?', [id]);
        res.json({ message: 'Receipt deleted successfully' });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
export default router;
//# sourceMappingURL=receipts.js.map