<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Student;
use App\Models\Course;
use App\Models\Batch;
use App\Models\Invoice;
use App\Models\FeePayment;

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

        $db = \App\Core\Database::getInstance();
        
        $params = [
            'search' => $_GET['search'] ?? '',
            'course_id' => $_GET['course_id'] ?? '',
            'batch_id' => $_GET['batch_id'] ?? '',
        ];

        // Query to get students with their total due amounts
        $sql = "SELECT s.*, 
                (SELECT SUM(total_amount) FROM invoices WHERE student_id = s.id AND status != 'Cancelled') as total_invoiced,
                (SELECT SUM(paid_amount) FROM invoices WHERE student_id = s.id AND status != 'Cancelled') as total_paid,
                (SELECT SUM(discount_amount) FROM invoices WHERE student_id = s.id AND status != 'Cancelled') as total_discount
                FROM students s
                WHERE 1=1";
        
        $binds = [];
        if (!empty($params['search'])) {
            $sql .= " AND (s.name LIKE :search OR s.phone LIKE :search OR s.email LIKE :search OR s.student_id LIKE :search)";
            $binds['search'] = '%' . $params['search'] . '%';
        }

        if (!empty($params['course_id'])) {
            $sql .= " AND EXISTS (SELECT 1 FROM admissions WHERE student_id = s.id AND course_id = :course_id)";
            $binds['course_id'] = $params['course_id'];
        }

        if (!empty($params['batch_id'])) {
            $sql .= " AND EXISTS (SELECT 1 FROM admissions WHERE student_id = s.id AND batch_id = :batch_id)";
            $binds['batch_id'] = $params['batch_id'];
        }

        $sql .= " ORDER BY s.name ASC";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($binds);
        $students = $stmt->fetchAll();

        $courses = $db->query("SELECT id, name FROM courses WHERE status = 'Active'")->fetchAll();
        $batches = $db->query("SELECT id, name, course_id FROM batches WHERE status IN ('Upcoming', 'Ongoing')")->fetchAll();

        $title = 'Fees Management';
        require_once __DIR__ . '/../../views/admin/fees_list.php';
    }

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

        $studentId = $_GET['id'] ?? null;
        if (!$studentId) {
            redirect('/admin/fees');
            exit;
        }

        $studentModel = new Student();
        $student = $studentModel->find($studentId);
        if (!$student) {
            redirect('/admin/fees');
            exit;
        }

        $db = \App\Core\Database::getInstance();
        
        // Fetch student totals
        $stmt = $db->prepare("SELECT 
                SUM(total_amount) as total_invoiced,
                SUM(paid_amount) as total_paid,
                SUM(discount_amount) as total_discount
                FROM invoices 
                WHERE student_id = :student_id AND status != 'Cancelled'");
        $stmt->execute(['student_id' => $studentId]);
        $totals = $stmt->fetch();
        
        $student['total_invoiced'] = $totals['total_invoiced'] ?: 0;
        $student['total_paid'] = $totals['total_paid'] ?: 0;
        $student['total_discount'] = $totals['total_discount'] ?: 0;
        $student['total_due'] = max(0, $student['total_invoiced'] - $student['total_paid'] - $student['total_discount']);

        // Get all pending/partial invoices for this student
        $stmt = $db->prepare("SELECT i.*, c.name as course_name 
                              FROM invoices i 
                              LEFT JOIN admissions a ON i.admission_id = a.id 
                              LEFT JOIN courses c ON a.course_id = c.id 
                              WHERE i.student_id = :student_id AND i.status IN ('Pending', 'Partial') 
                              ORDER BY i.due_date ASC");
        $stmt->execute(['student_id' => $studentId]);
        $pendingInvoices = $stmt->fetchAll();

        // Get payment history
        $stmt = $db->prepare("SELECT fp.*, i.title as invoice_title, i.id as invoice_id 
                              FROM fee_payments fp 
                              JOIN invoices i ON fp.invoice_id = i.id 
                              WHERE fp.student_id = :student_id 
                              ORDER BY fp.payment_date DESC");
        $stmt->execute(['student_id' => $studentId]);
        $payments = $stmt->fetchAll();

        $title = 'Fees for ' . $student['name'];
        require_once __DIR__ . '/../../views/admin/fees_student_view.php';
    }

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

        try {
            $count = \App\Core\InvoiceGenerator::generateMonthly();
            $_SESSION['toast'] = ['message' => "Generated $count new monthly invoices!", 'type' => 'success'];
        } catch (\Exception $e) {
            $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
        }

        redirect('/admin/fees');
        exit;
    }

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $paymentModel = new FeePayment();
            $invoiceModel = new Invoice();
            $invoice = $invoiceModel->find($_POST['invoice_id']);

            if (!$invoice) {
                $_SESSION['toast'] = ['message' => 'Invoice not found.', 'type' => 'error'];
                redirect($_SERVER['HTTP_REFERER']);
                exit;
            }

            $data = [
                'student_id' => $invoice['student_id'],
                'admission_id' => $invoice['admission_id'],
                'invoice_id' => $_POST['invoice_id'],
                'amount' => (float)($_POST['amount'] ?: 0),
                'discount' => (float)($_POST['discount'] ?: 0),
                'payment_date' => $_POST['payment_date'],
                'payment_method' => $_POST['payment_method'],
                'fee_type' => $invoice['title'],
                'remarks' => $_POST['remarks'] ?? '',
            ];

            try {
                $paymentModel->save($data);
                $_SESSION['toast'] = ['message' => 'Payment collected successfully!', 'type' => 'success'];
                redirect('/admin/fees/view?id=' . $invoice['student_id']);
                exit;
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/fees');
        exit;
    }
}
