<?php
/**
 * Dashboard Configuration File
 * Includes all necessary configurations and functions for dashboard operations
 */

// Prevent direct access
defined('ROOT_PATH') or die('Direct script access denied');

// Dashboard-specific configurations
define('DASHBOARD_ASSETS_URL', BASE_URL . 'assets/dashboard/');
define('MAX_FILE_UPLOAD_SIZE', 5 * 1024 * 1024); // 5MB
define('PROFILE_PHOTO_DIR', ROOT_PATH . '/uploads/profile-photos/');
define('STUDENT_DOCS_DIR', ROOT_PATH . '/uploads/students/');

// Dashboard user roles
define('ROLE_STUDENT', 'student');
define('ROLE_COUNSELOR', 'counselor');
define('ROLE_ADMIN', 'admin');

// Include necessary files
require_once ROOT_PATH . '/includes/functions.php';
require_once ROOT_PATH . '/includes/auth.php';

/**
 * Verify user is logged in and has dashboard access
 */
function verifyDashboardAccess() {
    if (!isLoggedIn()) {
        header("Location: " . BASE_URL . "dashboard/login.php");
        exit;
    }
}

/**
 * Check if user has specific role access
 */
function checkRoleAccess($requiredRole) {
    if ($_SESSION['user']['user_type'] !== $requiredRole) {
        $_SESSION['error'] = "You don't have permission to access this section";
        header("Location: " . BASE_URL . "dashboard/");
        exit;
    }
}

/**
 * Get dashboard navigation based on user role
 */
function getDashboardNavigation() {
    $nav = [];
    $userType = $_SESSION['user']['user_type'] ?? '';
    
    switch ($userType) {
        case ROLE_STUDENT:
            $nav = [
                'dashboard' => ['url' => 'student/', 'icon' => 'fas fa-tachometer-alt', 'label' => 'Dashboard'],
                'profile' => ['url' => 'student/profile.php', 'icon' => 'fas fa-user', 'label' => 'My Profile'],
                'applications' => ['url' => 'student/applications.php', 'icon' => 'fas fa-file-alt', 'label' => 'Applications'],
                'documents' => ['url' => 'student/documents.php', 'icon' => 'fas fa-file-upload', 'label' => 'Documents'],
                'messages' => ['url' => 'student/messages.php', 'icon' => 'fas fa-envelope', 'label' => 'Messages'],
                'payments' => ['url' => 'student/payments.php', 'icon' => 'fas fa-credit-card', 'label' => 'Payments'],
                'appointments' => ['url' => 'student/appointments.php', 'icon' => 'fas fa-calendar-check', 'label' => 'Appointments'],
                'visa' => ['url' => 'student/visa.php', 'icon' => 'fas fa-passport', 'label' => 'Visa Status']
            ];
            break;
            
        case ROLE_COUNSELOR:
            $nav = [
                'dashboard' => ['url' => 'counselor/', 'icon' => 'fas fa-tachometer-alt', 'label' => 'Dashboard'],
                'students' => ['url' => 'counselor/students.php', 'icon' => 'fas fa-users', 'label' => 'My Students'],
                'applications' => ['url' => 'counselor/applications.php', 'icon' => 'fas fa-file-alt', 'label' => 'Applications'],
                'appointments' => ['url' => 'counselor/appointments.php', 'icon' => 'fas fa-calendar-check', 'label' => 'Appointments'],
                'messages' => ['url' => 'counselor/messages.php', 'icon' => 'fas fa-envelope', 'label' => 'Messages']
            ];
            break;
            
        case ROLE_ADMIN:
            $nav = [
                'dashboard' => ['url' => 'admin/', 'icon' => 'fas fa-tachometer-alt', 'label' => 'Dashboard'],
                'students' => ['url' => 'admin/students.php', 'icon' => 'fas fa-user-graduate', 'label' => 'Students'],
                'counselors' => ['url' => 'admin/counselors.php', 'icon' => 'fas fa-chalkboard-teacher', 'label' => 'Counselors'],
                'applications' => ['url' => 'admin/applications.php', 'icon' => 'fas fa-file-alt', 'label' => 'Applications'],
                'universities' => ['url' => 'admin/universities.php', 'icon' => 'fas fa-university', 'label' => 'Universities'],
                'documents' => ['url' => 'admin/documents.php', 'icon' => 'fas fa-file-upload', 'label' => 'Documents'],
                'payments' => ['url' => 'admin/payments.php', 'icon' => 'fas fa-money-check-alt', 'label' => 'Payments'],
                'reports' => ['url' => 'admin/reports.php', 'icon' => 'fas fa-chart-bar', 'label' => 'Reports'],
                'visa' => ['url' => 'admin/visa.php', 'icon' => 'fas fa-passport', 'label' => 'Visa Tracking'],
                'settings' => ['url' => 'admin/settings.php', 'icon' => 'fas fa-cog', 'label' => 'Settings']
            ];
            break;
    }
    
    return $nav;
}

/**
 * Get current user's dashboard data
 */
function getDashboardData() {
    global $pdo;
    $userId = $_SESSION['user']['id'];
    $userType = $_SESSION['user']['user_type'];
    $data = [];

    switch ($userType) {
        case ROLE_STUDENT:
            // Get student's application count
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM applications WHERE student_id = ?");
            $stmt->execute([$userId]);
            $data['application_count'] = $stmt->fetchColumn();

            // Get unread messages
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM messages WHERE receiver_id = ? AND is_read = 0");
            $stmt->execute([$userId]);
            $data['unread_messages'] = $stmt->fetchColumn();

            // Get upcoming appointments
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM appointments 
                                  WHERE student_id = ? AND scheduled_time > NOW() 
                                  AND status = 'scheduled'");
            $stmt->execute([$userId]);
            $data['upcoming_appointments'] = $stmt->fetchColumn();
            break;

        case ROLE_COUNSELOR:
            // Get assigned students count
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE assigned_counselor_id = ?");
            $stmt->execute([$userId]);
            $data['student_count'] = $stmt->fetchColumn();

            // Get pending applications
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM applications 
                                  WHERE counselor_id = ? AND application_status = 'under_review'");
            $stmt->execute([$userId]);
            $data['pending_applications'] = $stmt->fetchColumn();

            // Get today's appointments
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM appointments 
                                  WHERE counselor_id = ? AND DATE(scheduled_time) = CURDATE() 
                                  AND status = 'scheduled'");
            $stmt->execute([$userId]);
            $data['todays_appointments'] = $stmt->fetchColumn();
            break;

        case ROLE_ADMIN:
            // Get total students
            $data['total_students'] = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();

            // Get pending documents
            $data['pending_documents'] = $pdo->query(
                "SELECT COUNT(*) FROM student_documents WHERE status = 'pending'"
            )->fetchColumn();

            // Get recent applications
            $data['recent_applications'] = $pdo->query(
                "SELECT COUNT(*) FROM applications WHERE DATE(created_at) = CURDATE()"
            )->fetchColumn();

            // Get pending payments
            $data['pending_payments'] = $pdo->query(
                "SELECT COUNT(*) FROM payments WHERE status = 'pending'"
            )->fetchColumn();
            break;
    }

    return $data;
}

// Initialize dashboard session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Verify dashboard access for all dashboard pages
verifyDashboardAccess();