<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Invoice;
use App\Models\FeePayment;

class InvoiceController {
    public function downloadPdf() {
        if (!Auth::check()) {
            redirect('/login');
            exit;
        }

        if (!isset($_GET['id'])) {
            $redirectPath = Auth::user()['role'] !== 'student' ? '/admin/fees' : '/student/fees';
            redirect($redirectPath);
            exit;
        }

        $invoiceModel = new Invoice();
        $invoice = $invoiceModel->find($_GET['id']);

        if (!$invoice) {
            $redirectPath = Auth::user()['role'] !== 'student' ? '/admin/fees' : '/student/fees';
            redirect($redirectPath);
            exit;
        }

        // Security check
        if (Auth::user()['role'] === 'student') {
            $db = \App\Core\Database::getInstance();
            $stmt = $db->prepare("SELECT id FROM students WHERE email = :email LIMIT 1");
            $stmt->execute(['email' => Auth::user()['email']]);
            $student = $stmt->fetch();
            
            if (!$student || $invoice['student_id'] != $student['id']) {
                redirect('/student/fees');
                exit;
            }
        } elseif (!Auth::hasPermission('fees_management')) {
            redirect('/login');
            exit;
        }

        // Get Settings
        $db = \App\Core\Database::getInstance();
        $settingsStmt = $db->query("SELECT * FROM settings");
        $settingsData = $settingsStmt->fetchAll();
        $settings = [];
        foreach ($settingsData as $s) {
            $settings[$s['key_name']] = $s['key_value'];
        }

        // Generate PDF
        $dompdf = new \Dompdf\Dompdf();
        $dompdf->set_option('isRemoteEnabled', true);
        
        // Use a fresh buffer to capture only the PDF HTML
        ob_start();
        include __DIR__ . '/../../views/admin/invoice_pdf.php';
        $html = ob_get_clean();

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        // Clear any previous output (warnings/notices) that might corrupt the PDF
        if (ob_get_length()) ob_end_clean();

        $filename = "Invoice-" . str_pad($invoice['id'], 5, '0', STR_PAD_LEFT) . ".pdf";
        $dompdf->stream($filename, ["Attachment" => false]);
        exit;
    }
}
