<?php

namespace App\Core;

use App\Models\Admission;
use App\Models\CourseFee;
use App\Models\Invoice;

class InvoiceGenerator {
    public static function generateMonthly() {
        $db = Database::getInstance();
        $admissionModel = new Admission();
        $courseFeeModel = new CourseFee();
        $invoiceModel = new Invoice();

        // Get all active admissions
        $stmt = $db->query("SELECT * FROM admissions WHERE status = 'Active'");
        $activeAdmissions = $stmt->fetchAll();
        
        $count = 0;
        $monthYear = date('F Y');
        $dueDate = date('Y-m-t'); // Last day of current month

        foreach ($activeAdmissions as $admission) {
            $monthlyFees = $courseFeeModel->getMonthlyByCourse($admission['course_id']);

            foreach ($monthlyFees as $fee) {
                $invoiceTitle = "{$fee['fee_type']} - {$monthYear}";

                // Check if invoice already exists
                $stmt = $db->prepare("SELECT id FROM invoices 
                                      WHERE student_id = :student_id 
                                      AND admission_id = :admission_id 
                                      AND title = :title");
                $stmt->execute([
                    'student_id' => $admission['student_id'],
                    'admission_id' => $admission['id'],
                    'title' => $invoiceTitle
                ]);

                if (!$stmt->fetch()) {
                    $invoiceModel->save([
                        'student_id' => $admission['student_id'],
                        'admission_id' => $admission['id'],
                        'title' => $invoiceTitle,
                        'total_amount' => $fee['amount'],
                        'paid_amount' => 0,
                        'discount_amount' => 0,
                        'due_date' => $dueDate,
                        'status' => 'Pending'
                    ]);
                    $count++;
                }
            }
        }

        return $count;
    }
}
