<?php
require_once APP_PATH . '/Core/BaseController.php';
require_once APP_PATH . '/Models/University.php';
require_once APP_PATH . '/Models/Scholarship.php';
require_once APP_PATH . '/Models/Mentor.php';
require_once APP_PATH . '/Models/Notification.php';
require_once APP_PATH . '/Models/Message.php';

class DashboardController extends BaseController {

    public function index(): void {
        $this->requireAuth();
        $user = Auth::user();
        $role = $user['role'];

        $data = ['title' => 'Dashboard — BOAFO', 'user' => $user];

        if ($role === 'student') {
            $data = array_merge($data, $this->studentDashboardData($user['id']));
        } elseif ($role === 'mentor') {
            $data = array_merge($data, $this->mentorDashboardData($user['id']));
        } elseif ($role === 'tutor') {
            $data = array_merge($data, $this->tutorDashboardData($user['id']));
        } elseif ($role === 'admin') {
            $this->redirect(APP_URL . '/admin');
        }

        $this->view('dashboard.' . $role, $data);
    }

    private function studentDashboardData(int $userId): array {
        $db = Database::getInstance();

        // Student profile
        $stmt = $db->prepare("SELECT * FROM student_profiles WHERE user_id = ?");
        $stmt->execute([$userId]);
        $profile = $stmt->fetch() ?: [];

        // WASSCE count
        $stmt2 = $db->prepare("SELECT COUNT(*) FROM wassce_results WHERE user_id = ?");
        $stmt2->execute([$userId]);
        $wassce_count = (int) $stmt2->fetchColumn();

        // Saved universities
        $stmt3 = $db->prepare("SELECT COUNT(*) FROM saved_universities WHERE user_id = ?");
        $stmt3->execute([$userId]);
        $saved_unis = (int) $stmt3->fetchColumn();

        // Saved scholarships
        $stmt4 = $db->prepare("SELECT COUNT(*) FROM saved_scholarships WHERE user_id = ?");
        $stmt4->execute([$userId]);
        $saved_schs = (int) $stmt4->fetchColumn();

        // Active mentorships
        $stmt5 = $db->prepare("SELECT COUNT(*) FROM mentorship_requests WHERE student_id = ? AND status = 'accepted'");
        $stmt5->execute([$userId]);
        $active_mentors = (int) $stmt5->fetchColumn();

        // Upcoming sessions
        $stmt6 = $db->prepare(
            "SELECT s.*, u.first_name, u.last_name FROM sessions s
             JOIN users u ON u.id = s.mentor_id
             WHERE s.student_id = ? AND s.scheduled_at >= NOW() AND s.status IN ('pending','confirmed')
             ORDER BY s.scheduled_at ASC LIMIT 3"
        );
        $stmt6->execute([$userId]);
        $upcoming_sessions = $stmt6->fetchAll();

        // Unread messages
        $msgModel = new Message();
        // Notifications
        $notifModel = new Notification();

        // Featured scholarships
        $schModel = new Scholarship();
        $featured_scholarships = $schModel->getFeatured(3);

        // Featured universities
        $uniModel = new University();
        $featured_universities = $uniModel->getFeatured(3);

        // Recent notifications
        $notifications = $notifModel->getForUser($userId, 5);
        $unread_notifications = $notifModel->unreadCount($userId);

        // Profile completion percentage
        $completion = $this->calculateProfileCompletion($profile, $wassce_count);

        return compact(
            'profile', 'wassce_count', 'saved_unis', 'saved_schs',
            'active_mentors', 'upcoming_sessions', 'featured_scholarships',
            'featured_universities', 'notifications', 'unread_notifications',
            'completion'
        );
    }

    private function mentorDashboardData(int $userId): array {
        $db = Database::getInstance();

        $stmt = $db->prepare("SELECT mp.*, uni.name AS university_name FROM mentor_profiles mp LEFT JOIN universities uni ON uni.id = mp.university_id WHERE mp.user_id = ?");
        $stmt->execute([$userId]);
        $profile = $stmt->fetch() ?: [];

        $stmt2 = $db->prepare("SELECT COUNT(*) FROM mentorship_requests WHERE mentor_id = ? AND status = 'pending'");
        $stmt2->execute([$userId]);
        $pending_requests = (int) $stmt2->fetchColumn();

        $stmt3 = $db->prepare(
            "SELECT mr.*, u.first_name, u.last_name, u.avatar
             FROM mentorship_requests mr
             JOIN users u ON u.id = mr.student_id
             WHERE mr.mentor_id = ? AND mr.status = 'pending'
             ORDER BY mr.created_at DESC LIMIT 5"
        );
        $stmt3->execute([$userId]);
        $requests = $stmt3->fetchAll();

        $stmt4 = $db->prepare(
            "SELECT s.*, u.first_name, u.last_name FROM sessions s
             JOIN users u ON u.id = s.student_id
             WHERE s.mentor_id = ? AND s.scheduled_at >= NOW() AND s.status IN ('pending','confirmed')
             ORDER BY s.scheduled_at ASC LIMIT 3"
        );
        $stmt4->execute([$userId]);
        $upcoming_sessions = $stmt4->fetchAll();

        $notifModel = new Notification();
        $notifications = $notifModel->getForUser($userId, 5);
        $unread_notifications = $notifModel->unreadCount($userId);

        return compact('profile', 'pending_requests', 'requests', 'upcoming_sessions', 'notifications', 'unread_notifications');
    }

    private function tutorDashboardData(int $userId): array {
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM tutor_profiles WHERE user_id = ?");
        $stmt->execute([$userId]);
        $profile = $stmt->fetch() ?: [];

        $notifModel = new Notification();
        $notifications = $notifModel->getForUser($userId, 5);

        return compact('profile', 'notifications');
    }

    private function calculateProfileCompletion(array $profile, int $wassce_count): int {
        $fields = ['date_of_birth','gender','country_id','shs_school','shs_program','graduation_year','intended_program','career_interests'];
        $filled = array_filter($fields, fn($f) => !empty($profile[$f]));
        $score = (count($filled) / count($fields)) * 70;
        if ($wassce_count >= 6) $score += 30;
        elseif ($wassce_count > 0) $score += ($wassce_count / 6) * 30;
        return min(100, (int) round($score));
    }
}
