const express = require('express');
const router = express.Router();
const db = require('../config/db');
const auth = require('../middleware/auth');

router.use(auth());

// GET /api/payments/rental/:rental_id
router.get('/rental/:rental_id', async (req, res, next) => {
    try {
        const [rows] = await db.execute('SELECT * FROM payments WHERE rental_id = ?', [req.params.rental_id]);
        res.json({ success: true, data: rows });
    } catch (err) {
        next(err);
    }
});

// POST /api/payments
router.post('/', async (req, res, next) => {
    try {
        const { rental_id, amount, method, status, reference_no } = req.body;
        const [result] = await db.execute(
            'INSERT INTO payments (rental_id, amount, method, status, reference_no, paid_at) VALUES (?, ?, ?, ?, ?, NOW())',
            [rental_id, amount, method, status || 'PAID', reference_no || null]
        );

        // Update the rentals table paid_amount
        await db.execute(
            'UPDATE rentals SET paid_amount = paid_amount + ? WHERE id = ?',
            [amount, rental_id]
        );

        res.status(201).json({ success: true, data: { id: result.insertId, ...req.body } });
    } catch (err) {
        next(err);
    }
});

module.exports = router;
