"use strict";
const { Router } = require("express");
const { query, insert, update } = require("../db");
const { getSession } = require("../auth");
const router = Router();

function calcStatus(total, paid) {
  if (paid <= 0) return "pending";
  if (paid >= total) return "paid";
  return "partial";
}

router.get("/fee-payments", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const { studentId, invoiceId } = req.query;
  let sql = "SELECT fp.*, i.invoice_number, i.total as invoice_total, i.term FROM fee_payments fp LEFT JOIN invoices i ON fp.invoice_id=i.id WHERE 1=1";
  const params = [];
  if (studentId) { sql += " AND fp.student_id=?"; params.push(studentId); }
  if (invoiceId) { sql += " AND fp.invoice_id=?"; params.push(invoiceId); }
  sql += " ORDER BY fp.created_at DESC";
  res.json(await query(sql, params));
});

router.get("/fee-payments/summary/:studentId", async (req, res) => {
  const session = getSession(req);
  if (!session) return res.status(401).json({ error: "Login required" });
  const [student] = await query("SELECT * FROM students WHERE id=?", [req.params.studentId]);
  if (!student) return res.status(404).json({ error: "Student not found" });
  const invoices = await query("SELECT * FROM invoices WHERE student_id=?", [req.params.studentId]);
  const payments = await query("SELECT * FROM fee_payments WHERE student_id=? ORDER BY created_at DESC", [req.params.studentId]);
  const totalBilled = invoices.reduce((s, i) => s + i.total, 0);
  const totalPaid = invoices.reduce((s, i) => s + i.amount_paid, 0);
  const enrichedInvoices = invoices.map(inv => ({
    ...inv,
    items: JSON.parse(inv.items || "[]"),
    payments: payments.filter(p => p.invoice_id === inv.id),
  }));
  res.json({
    studentId: student.id, studentName: `${student.first_name} ${student.last_name}`, studentCode: student.student_id,
    totalBilled: Math.round(totalBilled * 100) / 100, totalPaid: Math.round(totalPaid * 100) / 100,
    balance: Math.round((totalBilled - totalPaid) * 100) / 100,
    invoiceCount: invoices.length, paidCount: invoices.filter(i => i.status === "paid").length,
    pendingCount: invoices.filter(i => i.status !== "paid").length, invoices: enrichedInvoices,
  });
});

router.post("/fee-payments", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const { invoiceId, amount, method, reference, notes } = req.body;
  if (!invoiceId || !amount || amount <= 0) return res.status(400).json({ error: "invoiceId and positive amount required" });
  const [invoice] = await query("SELECT * FROM invoices WHERE id=?", [invoiceId]);
  if (!invoice) return res.status(404).json({ error: "Invoice not found" });
  const id = await insert("INSERT INTO fee_payments (invoice_id, student_id, amount, method, reference, notes, recorded_by) VALUES (?,?,?,?,?,?,?)",
    [invoiceId, invoice.student_id, amount, method || "cash", reference || "", notes || "", session.displayName]);
  const newPaid = Math.min(invoice.total, invoice.amount_paid + amount);
  await update("UPDATE invoices SET amount_paid=?, status=? WHERE id=?",
    [newPaid, calcStatus(invoice.total, newPaid), invoiceId]);
  res.json({ id, newAmountPaid: newPaid, newStatus: calcStatus(invoice.total, newPaid) });
});

router.delete("/fee-payments/:id", async (req, res) => {
  const session = getSession(req);
  if (!session || session.role !== "admin") return res.status(403).json({ error: "Admin only" });
  const [payment] = await query("SELECT * FROM fee_payments WHERE id=?", [req.params.id]);
  if (!payment) return res.status(404).json({ error: "Not found" });
  await query("DELETE FROM fee_payments WHERE id=?", [req.params.id]);
  const [invoice] = await query("SELECT * FROM invoices WHERE id=?", [payment.invoice_id]);
  if (invoice) {
    const newPaid = Math.max(0, invoice.amount_paid - payment.amount);
    await update("UPDATE invoices SET amount_paid=?, status=? WHERE id=?",
      [newPaid, calcStatus(invoice.total, newPaid), invoice.id]);
  }
  res.json({ deleted: true });
});

module.exports = router;
