<?php
session_start();
require_once '../../config/database.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit();
}

try {
    $user_id = $_SESSION['user_id'];
    $user_role = $_SESSION['user_role'];
    
    // Get query parameters
    $class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
    $subject_id = isset($_GET['subject_id']) ? (int)$_GET['subject_id'] : 0;
    $category = isset($_GET['category']) ? $_GET['category'] : '';
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    
    // Build query based on user role
    $where_conditions = [];
    $params = [];
    
    if ($user_role === 'student') {
        // For students, get materials for their class
        $stmt = $pdo->prepare("SELECT class_id FROM students WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $student = $stmt->fetch();
        
        if ($student) {
            $where_conditions[] = "lm.class_id = ?";
            $params[] = $student['class_id'];
            $where_conditions[] = "lm.status = 'active'";
        } else {
            echo json_encode(['success' => false, 'message' => 'Student record not found']);
            exit();
        }
    } else {
        // For teachers/admins, get all active materials
        $where_conditions[] = "lm.status = 'active'";
    }
    
    // Add filters if provided
    if ($class_id > 0) {
        $where_conditions[] = "lm.class_id = ?";
        $params[] = $class_id;
    }
    
    if ($subject_id > 0) {
        $where_conditions[] = "lm.subject_id = ?";
        $params[] = $subject_id;
    }
    
    if (!empty($category)) {
        $where_conditions[] = "lm.category = ?";
        $params[] = $category;
    }
    
    if (!empty($search)) {
        $where_conditions[] = "(lm.title LIKE ? OR lm.description LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    $where_clause = '';
    if (!empty($where_conditions)) {
        $where_clause = "WHERE " . implode(" AND ", $where_conditions);
    }
    
    // Get learning materials with related data
    $stmt = $pdo->prepare("
        SELECT 
            lm.*,
            c.name as class_name,
            s.name as subject_name,
            fu.original_name as file_name,
            fu.file_type,
            fu.file_size,
            COALESCE(s_tbl.first_name, t_tbl.first_name, u.username) as first_name,
            COALESCE(s_tbl.last_name, t_tbl.last_name, '') as last_name,
            COALESCE(view_stats.views, 0) as view_count,
            COALESCE(download_stats.downloads, 0) as download_count
        FROM learning_materials lm
        JOIN classes c ON lm.class_id = c.id
        JOIN subjects s ON lm.subject_id = s.id
        JOIN file_uploads fu ON lm.file_upload_id = fu.id
        JOIN users u ON lm.created_by = u.id
        LEFT JOIN students s_tbl ON lm.created_by = s_tbl.user_id
        LEFT JOIN teachers t_tbl ON lm.created_by = t_tbl.user_id
        LEFT JOIN (
            SELECT material_id, COUNT(*) as views
            FROM learning_materials_views
            WHERE action = 'view'
            GROUP BY material_id
        ) view_stats ON lm.id = view_stats.material_id
        LEFT JOIN (
            SELECT material_id, COUNT(*) as downloads
            FROM learning_materials_views
            WHERE action = 'download'
            GROUP BY material_id
        ) download_stats ON lm.id = download_stats.material_id
        $where_clause
        ORDER BY lm.created_at DESC
        LIMIT 50
    ");
    
    $stmt->execute($params);
    $materials = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Function to get specific students for a material
    function getSpecificStudents($pdo, $material_id) {
        try {
            $stmt = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, s.student_id, s.roll_number, c.name as class_name FROM learning_materials_specific_students lms JOIN students s ON lms.student_id = s.id JOIN classes c ON s.class_id = c.id WHERE lms.material_id = ?");
            $stmt->execute([$material_id]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return [];
        }
    }
    
    // Format the data for frontend
    $formatted_materials = [];
    foreach ($materials as $material) {
        // Determine file icon based on file type
        $file_type = strtolower($material['file_type']);
        $icon_class = 'fas fa-file';
        
        if (strpos($file_type, 'pdf') !== false) {
            $icon_class = 'fas fa-file-pdf';
        } elseif (strpos($file_type, 'word') !== false || strpos($file_type, 'doc') !== false) {
            $icon_class = 'fas fa-file-word';
        } elseif (strpos($file_type, 'powerpoint') !== false || strpos($file_type, 'ppt') !== false) {
            $icon_class = 'fas fa-file-powerpoint';
        } elseif (strpos($file_type, 'video') !== false) {
            $icon_class = 'fas fa-video';
        } elseif (strpos($file_type, 'audio') !== false) {
            $icon_class = 'fas fa-music';
        }
        
        // Format category for display
        $category_display = '';
        switch ($material['category']) {
            case 'lecture_notes': $category_display = 'লেকচার নোট'; break;
            case 'presentation': $category_display = 'প্রেজেন্টেশন'; break;
            case 'video_lecture': $category_display = 'ভিডিও লেকচার'; break;
            case 'audio_lecture': $category_display = 'অডিও লেকচার'; break;
            case 'assignment': $category_display = 'অ্যাসাইনমেন্ট'; break;
            case 'practice_questions': $category_display = 'প্রাক্টিস প্রশ্ন'; break;
            default: $category_display = $material['category'];
        }
        
        $formatted_materials[] = [
            'id' => $material['id'],
            'title' => $material['title'],
            'description' => $material['description'],
            'class_name' => $material['class_name'],
            'subject_name' => $material['subject_name'],
            'category' => $material['category'],
            'category_display' => $category_display,
            'file_name' => $material['file_name'],
            'file_type' => $material['file_type'],
            'file_size' => $material['file_size'],
            'icon_class' => $icon_class,
            'created_by' => $material['first_name'] . ' ' . $material['last_name'],
            'created_at' => $material['created_at'],
            'view_count' => $material['view_count'],
            'download_count' => $material['download_count'],
            'allow_download' => $material['allow_download'],
            'access_control' => $material['access_control'],
            'specific_students' => ($material['access_control'] === 'specific_students') ? getSpecificStudents($pdo, $material['id']) : []
        ];
    }
    
    echo json_encode(['success' => true, 'materials' => $formatted_materials]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error fetching learning materials: ' . $e->getMessage()]);
}
?>