<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Student;

class StudentPortalController {
    
    private function getStudent($user) {
        $db = \App\Core\Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM students WHERE email = :email LIMIT 1");
        $stmt->execute(['email' => $user['email']]);
        return $stmt->fetch();
    }

    public function fees() {
        if (!Auth::check() || Auth::user()['role'] !== 'student') {
            redirect('/login');
            exit;
        }

        $user = Auth::user();
        $student = $this->getStudent($user);
        $db = \App\Core\Database::getInstance();
        $studentId = $student['id'];

        // Stats for student
        $student['total_billed'] = $db->query("SELECT SUM(total_amount) FROM invoices WHERE student_id = $studentId AND status != 'Cancelled'")->fetchColumn() ?: 0;
        $student['total_paid'] = $db->query("SELECT SUM(amount) FROM fee_payments WHERE student_id = $studentId")->fetchColumn() ?: 0;
        $student['total_due'] = $db->query("SELECT SUM(total_amount - paid_amount - discount_amount) FROM invoices WHERE student_id = $studentId AND status != 'Cancelled'")->fetchColumn() ?: 0;

        $invoices = $db->query("SELECT * FROM invoices WHERE student_id = $studentId AND status != 'Cancelled' ORDER BY created_at DESC")->fetchAll();
        
        $payments = $db->query("SELECT fp.*, i.title as invoice_title 
                                FROM fee_payments fp 
                                JOIN invoices i ON fp.invoice_id = i.id 
                                WHERE fp.student_id = $studentId 
                                ORDER BY fp.payment_date DESC")->fetchAll();

        // Get settings for currency etc
        $settingsStmt = $db->query("SELECT * FROM settings");
        $allSettings = $settingsStmt->fetchAll();
        $siteSettings = [];
        foreach ($allSettings as $s) {
            $siteSettings[$s['key_name']] = $s['key_value'];
        }

        $title = 'My Fees & Payments';
        require_once __DIR__ . '/../../views/student/fees.php';
    }

    public function courses() {
        if (!Auth::check() || Auth::user()['role'] !== 'student') {
            redirect('/login');
            exit;
        }

        $user = Auth::user();
        $student = $this->getStudent($user);
        $db = \App\Core\Database::getInstance();
        $studentId = $student['id'];

        $admissions = $db->query("SELECT a.*, 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 courses c ON a.course_id = c.id 
                                  JOIN batches b ON a.batch_id = b.id
                                  WHERE a.student_id = $studentId 
                                  ORDER BY a.admission_date DESC")->fetchAll();

        $title = 'My Courses';
        require_once __DIR__ . '/../../views/student/courses.php';
    }

    public function materials() {
        if (!Auth::check() || Auth::user()['role'] !== 'student') {
            redirect('/login');
            exit;
        }

        $user = Auth::user();
        $student = $this->getStudent($user);
        $db = \App\Core\Database::getInstance();
        $studentId = $student['id'];

        $materials = $db->query("SELECT DISTINCT sm.*, c.name as course_name 
                                 FROM study_materials sm 
                                 JOIN courses c ON sm.course_id = c.id 
                                 JOIN admissions a ON c.id = a.course_id 
                                 WHERE a.student_id = $studentId AND sm.is_active = 1 
                                 ORDER BY sm.created_at DESC")->fetchAll();

        $title = 'Study Materials';
        require_once __DIR__ . '/../../views/student/materials.php';
    }

    public function download() {
        if (!Auth::check() || Auth::user()['role'] !== 'student') {
            redirect('/login');
            exit;
        }

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

        $id = $_GET['id'];
        $db = \App\Core\Database::getInstance();
        
        // Ensure student has access to this material
        $user = Auth::user();
        $student = $this->getStudent($user);
        $studentId = $student['id'];

        $stmt = $db->prepare("SELECT sm.* FROM study_materials sm 
                              JOIN admissions a ON sm.course_id = a.course_id 
                              WHERE sm.id = :id AND a.student_id = :student_id LIMIT 1");
        $stmt->execute(['id' => $id, 'student_id' => $studentId]);
        $material = $stmt->fetch();

        if (!$material || $material['type'] !== 'file' || !$material['file_path']) {
            $_SESSION['toast'] = ['message' => 'Material not found or access denied.', 'type' => 'error'];
            redirect('/student/materials');
            exit;
        }

        $filePath = __DIR__ . '/../../public' . $material['file_path'];
        
        if (!file_exists($filePath)) {
            $_SESSION['toast'] = ['message' => 'File not found on server.', 'type' => 'error'];
            redirect('/student/materials');
            exit;
        }

        // Serve the file
        $fileName = basename($filePath);
        $mimeType = mime_content_type($filePath);

        header('Content-Description: File Transfer');
        header('Content-Type: ' . $mimeType);
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }

    public function profile() {
        if (!Auth::check() || Auth::user()['role'] !== 'student') {
            redirect('/login');
            exit;
        }

        $user = Auth::user();
        $student = $this->getStudent($user);
        $db = \App\Core\Database::getInstance();
        
        // Fetch admissions with course info
        $admissions = $db->query("SELECT a.*, c.name as course_name 
                                  FROM admissions a 
                                  JOIN courses c ON a.course_id = c.id 
                                  WHERE a.student_id = {$student['id']}")->fetchAll();

        $title = 'My Profile';
        require_once __DIR__ . '/../../views/student/profile.php';
    }
}
