<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            // Get receipts
            if (isset($_GET['receipts'])) {
                $stmt = $db->query("SELECT * FROM fee_receipts ORDER BY created_at DESC");
                sendJson($stmt->fetchAll());
            }
            // Get due fees (students who don't have a receipt this month)
            elseif (isset($_GET['due'])) {
                $currentMonth = date('Y-m');
                $stmt = $db->prepare("SELECT s.id, s.student_id, s.full_name, s.monthly_fee, s.fee_status,
                    s.batch_name, s.phone, s.guardian_name
                    FROM students s
                    WHERE s.is_active = 1 AND s.id NOT IN (
                        SELECT student_id FROM fee_receipts WHERE month_year = ?
                    )");
                $stmt->execute([$currentMonth]);
                sendJson($stmt->fetchAll());
            }
            else {
                $studentId = $_GET['studentId'] ?? '';
                $sql = "SELECT * FROM fee_receipts WHERE 1=1";
                $params = [];
                if ($studentId) {
                    $sql .= " AND student_id = ?";
                    $params[] = $studentId;
                }
                $sql .= " ORDER BY created_at DESC";
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                sendJson($stmt->fetchAll());
            }
            break;

        case 'POST':
            // Record payment
            $receiptNumber = 'RCP-' . date('Y') . '-' . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $monthYear = date('Y-m');
            $amount = $input['amount'] ?? 0;

            $stmt = $db->prepare("INSERT INTO fee_receipts
                (receipt_number, student_id, month_year, monthly_fee, late_fee,
                 gst_amount, total_amount, amount_paid, payment_method, payment_date, notes)
                VALUES (?, ?, ?, ?, 0, 0, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $receiptNumber,
                $input['studentId'] ?? 0,
                $monthYear,
                $amount,
                $amount, // total = amount (no GST)
                $amount,
                $input['paymentMethod'] ?? 'cash',
                $input['paymentDate'] ?? date('Y-m-d'),
                $input['notes'] ?? ''
            ]);

            // Update student fee status
            $updateStmt = $db->prepare("UPDATE students SET fee_status = 'paid' WHERE id = ?");
            $updateStmt->execute([$input['studentId'] ?? 0]);

            sendJson(['success' => true, 'receiptNumber' => $receiptNumber]);
            break;

        default:
            sendJson(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
