<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Admission;
use App\Models\Student;
use App\Models\Course;
use App\Models\Batch;
// Note: We'll implement basic saving first, integrating invoice generation next if needed

class AdmissionController {
    public function index() {
        if (!Auth::hasPermission('admissions')) {
            redirect('/login');
            exit;
        }

        $admissionModel = new Admission();
        $params = [
            'search' => $_GET['search'] ?? '',
            'filter_course' => $_GET['filter_course'] ?? '',
            'page' => $_GET['page'] ?? 1,
        ];

        $paginatedAdmissions = $admissionModel->search($params);
        $admissions = $paginatedAdmissions['data'];
        
        $studentModel = new Student();
        // Just get active students for the dropdown
        $db = \App\Core\Database::getInstance();
        $students = $db->query("SELECT id, name, student_id FROM students ORDER BY name")->fetchAll();

        $courseModel = new Course();
        $courses = $db->query("SELECT id, name FROM courses")->fetchAll();

        // Get batches to be available in JS
        $batchesRaw = $db->query("SELECT id, name, course_id, capacity FROM batches")->fetchAll();
        $batchesJson = json_encode($batchesRaw);

        // Get course fees for the JS calculation
        $feesRaw = $db->query("SELECT course_id, fee_type, amount, frequency FROM course_fees")->fetchAll();
        $courseFeesJson = json_encode($feesRaw);

        // Enrolled counts per batch
        $enrolledRaw = $db->query("SELECT batch_id, COUNT(*) as enrolled FROM admissions WHERE status = 'Active' AND batch_id IS NOT NULL GROUP BY batch_id")->fetchAll();
        $enrolledJson = json_encode($enrolledRaw);

        $title = 'Admissions';
        
        $editingAdmission = null;
        if (isset($_GET['edit_id'])) {
            $editingAdmission = $admissionModel->find($_GET['edit_id']);
        }

        $preSelectedStudent = $_GET['student_id'] ?? null;

        require_once __DIR__ . '/../../views/admin/admissions.php';
    }

    public function save() {
        if (!Auth::hasPermission('admissions')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $admissionModel = new Admission();
            
            $data = [
                'id' => $_POST['id'] ?? null,
                'student_id' => $_POST['student_id'],
                'course_id' => $_POST['course_id'],
                'batch_id' => !empty($_POST['batch_id']) ? $_POST['batch_id'] : null,
                'admission_date' => $_POST['admission_date'],
                'status' => $_POST['status'] ?? 'Active',
            ];

            try {
                $db = \App\Core\Database::getInstance();
                $db->beginTransaction();

                $admissionId = $admissionModel->save($data);
                
                // If it's a new admission, create invoice for full course fees
                if (empty($data['id'])) {
                    $invoiceModel = new \App\Models\Invoice();
                    
                    // Calculate total one-time fees for this course
                    $courseFeeModel = new \App\Models\CourseFee();
                    $courseFees = $courseFeeModel->getByCourse($data['course_id']);
                    $totalFees = 0;
                    foreach ($courseFees as $cf) {
                        if ($cf['frequency'] === 'One-time') {
                            $totalFees += (float)$cf['amount'];
                        }
                    }

                    // Create Invoice for the full amount
                    $invoiceId = $invoiceModel->save([
                        'student_id' => $data['student_id'],
                        'admission_id' => $admissionId,
                        'title' => 'Admission & Registration Fees',
                        'total_amount' => $totalFees,
                        'paid_amount' => 0,
                        'discount_amount' => 0,
                        'due_date' => $data['admission_date'],
                        'status' => 'Pending'
                    ]);

                    // If initial payment is provided, record it
                    if (!empty($_POST['initial_payment']) && $_POST['initial_payment'] > 0) {
                        $paymentModel = new \App\Models\FeePayment();
                        
                        // Check if there's a discount (Total Fees - Amount Paid)
                        // But wait, the admin might want to keep the rest as due.
                        // For now, we record exactly what was paid.
                        $amountPaid = (float)$_POST['initial_payment'];
                        
                        $paymentModel->save([
                            'student_id' => $data['student_id'],
                            'admission_id' => $admissionId,
                            'invoice_id' => $invoiceId,
                            'amount' => $amountPaid,
                            'discount' => 0, // Admin can add discount later via Fee Management
                            'payment_date' => $data['admission_date'],
                            'payment_method' => $_POST['payment_method'] ?? 'Cash',
                            'fee_type' => 'Admission Fee',
                            'remarks' => 'Initial payment during admission'
                        ]);
                    }
                }

                $db->commit();
                $_SESSION['toast'] = ['message' => $data['id'] ? 'Admission updated!' : 'New admission recorded!', 'type' => 'success'];
            } catch (\Exception $e) {
                if (isset($db)) $db->rollBack();
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/admissions');
        exit;
    }

    public function downloadPdf() {
        if (!Auth::hasPermission('admissions')) {
            redirect('/login');
            exit;
        }

        if (!isset($_GET['id'])) {
            redirect('/admin/admissions');
            exit;
        }

        $db = \App\Core\Database::getInstance();
        
        // Fetch detailed admission data
        $stmt = $db->prepare("SELECT a.*, s.name as student_name, s.student_id as student_id_code, s.phone as student_phone, 
                                     s.email as student_email, s.address as student_address, s.photo as student_photo,
                                     s.guardian_name, s.guardian_phone,
                                     c.name as course_name, c.duration_months as course_duration,
                                     b.name as batch_name, b.start_time as batch_start_time, b.end_time as batch_end_time
                              FROM admissions a
                              JOIN students s ON a.student_id = s.id
                              JOIN courses c ON a.course_id = c.id
                              LEFT JOIN batches b ON a.batch_id = b.id
                              WHERE a.id = :id LIMIT 1");
        $stmt->execute(['id' => $_GET['id']]);
        $admission = $stmt->fetch();

        if (!$admission) {
            redirect('/admin/admissions');
            exit;
        }

        // Fetch associated invoice
        $stmtInv = $db->prepare("SELECT * FROM invoices WHERE admission_id = :admission_id LIMIT 1");
        $stmtInv->execute(['admission_id' => $admission['id']]);
        $invoice = $stmtInv->fetch();

        // Get Settings
        $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);
        
        ob_start();
        include __DIR__ . '/../../views/admin/admission_pdf.php';
        $html = ob_get_clean();

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

        if (ob_get_length()) ob_end_clean();

        $filename = "Admission-" . str_replace(' ', '-', $admission['student_name']) . ".pdf";
        $dompdf->stream($filename, ["Attachment" => false]);
        exit;
    }

    public function delete() {
        if (!Auth::hasPermission('admissions')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            $admissionModel = new Admission();
            $admissionModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Admission record removed.', 'type' => 'info'];
        }
        redirect('/admin/admissions');
        exit;
    }
}
