<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Setting;

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

        $user = Auth::user();
        $settingModel = new Setting();
        $siteSettings = $settingModel->getAll();
        $title = 'Dashboard Overview';

        if ($user['role'] === 'admin' || $user['role'] === 'staff') {
            $db = \App\Core\Database::getInstance();
            
            $stats = [];
            // Common stats
            if (Auth::hasPermission('students')) {
                $stats['total_students'] = $db->query("SELECT COUNT(*) FROM students")->fetchColumn();
                $stats['active_students'] = $db->query("SELECT COUNT(*) FROM students WHERE status = 'Active'")->fetchColumn();
            }
            
            if (Auth::hasPermission('teachers')) {
                $stats['active_faculty'] = $db->query("SELECT COUNT(*) FROM teachers WHERE status = 'Active'")->fetchColumn();
            }

            if (Auth::hasPermission('fees_management')) {
                $stats['total_revenue'] = $db->query("SELECT SUM(amount) FROM fee_payments")->fetchColumn() ?: 0;
                $stats['total_dues'] = $db->query("SELECT SUM(total_amount - paid_amount - discount_amount) FROM invoices WHERE status != 'Cancelled'")->fetchColumn() ?: 0;
            }

            if (Auth::hasPermission('expenses')) {
                $stats['total_expenses'] = $db->query("SELECT SUM(amount) FROM expenses")->fetchColumn() ?: 0;
            }

            // Recent Activity
            $activities = [];
            if (Auth::hasPermission('admissions')) {
                $recentAdmissions = $db->query("SELECT 'Admission' as type, s.name as student_name, c.name as detail, a.created_at as date 
                                                FROM admissions a 
                                                JOIN students s ON a.student_id = s.id 
                                                JOIN courses c ON a.course_id = c.id 
                                                ORDER BY a.created_at DESC LIMIT 5")->fetchAll();
                $activities = array_merge($activities, $recentAdmissions);
            }

            if (Auth::hasPermission('fees_management')) {
                $recentPayments = $db->query("SELECT 'Payment' as type, s.name as student_name, i.title as detail, fp.amount, fp.created_at as date 
                                              FROM fee_payments fp 
                                              JOIN students s ON fp.student_id = s.id 
                                              JOIN invoices i ON fp.invoice_id = i.id 
                                              ORDER BY fp.created_at DESC LIMIT 5")->fetchAll();
                $activities = array_merge($activities, $recentPayments);
            }

            usort($activities, function($a, $b) {
                return strtotime($b['date']) - strtotime($a['date']);
            });
            $activities = array_slice($activities, 0, 6);

            // Today's Schedule
            $activeBatchesToday = [];
            if (Auth::hasPermission('batches')) {
                $today = date('D');
                $activeBatchesToday = $db->query("SELECT b.*, c.name as course_name, t.name as teacher_name 
                                                  FROM batches b 
                                                  JOIN courses c ON b.course_id = c.id 
                                                  JOIN teachers t ON b.teacher_id = t.id 
                                                  WHERE b.status = 'Ongoing' AND b.days LIKE '%$today%'")->fetchAll();
            }

            require_once __DIR__ . '/../../views/admin/dashboard.php';
        } else {
            $db = \App\Core\Database::getInstance();
            
            // Get student record linked to user
            $stmt = $db->prepare("SELECT * FROM students WHERE email = :email LIMIT 1");
            $stmt->execute(['email' => $user['email']]);
            $student = $stmt->fetch();

            if (!$student) {
                echo "<h1>Error</h1><p>Student record not found for your account.</p><a href='" . url('/logout') . "'>Logout</a>";
                exit;
            }

            // Student Stats
            $studentId = $student['id'];
            $admissions = $db->query("SELECT a.*, c.name as course_name, b.name as batch_name 
                                      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 AND a.status = 'Active'")->fetchAll();

            $stats = [
                'courses' => count($admissions),
                'total_paid' => $db->query("SELECT SUM(amount) FROM fee_payments WHERE student_id = $studentId")->fetchColumn() ?: 0,
                'total_due' => $db->query("SELECT SUM(total_amount - paid_amount - discount_amount) FROM invoices WHERE student_id = $studentId AND status != 'Cancelled'")->fetchColumn() ?: 0,
                'total_discount' => $db->query("SELECT SUM(discount) FROM fee_payments WHERE student_id = $studentId")->fetchColumn() ?: 0,
            ];

            // Today's Schedule
            $today = date('D');
            $todaySchedule = $db->query("SELECT b.*, c.name as course_name, t.name as teacher_name 
                                        FROM batches b 
                                        JOIN admissions a ON b.id = a.batch_id 
                                        JOIN courses c ON b.course_id = c.id 
                                        JOIN teachers t ON b.teacher_id = t.id 
                                        WHERE a.student_id = $studentId AND b.status = 'Ongoing' AND b.days LIKE '%$today%'")->fetchAll();

            // Recent Materials
            $recentMaterials = $db->query("SELECT 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 LIMIT 5")->fetchAll();

            // Financial Progress
            $totalBilled = $db->query("SELECT SUM(total_amount) FROM invoices WHERE student_id = $studentId AND status != 'Cancelled'")->fetchColumn() ?: 0;
            $totalPaid = $stats['total_paid'];
            $payProgress = $totalBilled > 0 ? min(100, round(($totalPaid / $totalBilled) * 100)) : 0;

            $lastPayment = $db->query("SELECT * FROM fee_payments WHERE student_id = $studentId ORDER BY payment_date DESC LIMIT 1")->fetch();

            require_once __DIR__ . '/../../views/student/dashboard.php';
        }
    }
}
