<?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();
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    $user_id = $_SESSION['user_id'];
    $user_role = $_SESSION['user_role'];
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    if (!$input || !isset($input['id']) || !isset($input['action'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }
    
    $material_id = (int)$input['id'];
    $action = $input['action']; // 'view' or 'download'
    
    // Validate action
    if (!in_array($action, ['view', 'download'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        exit();
    }
    
    // Get material details
    $stmt = $pdo->prepare("
        SELECT lm.*, fu.id as file_id
        FROM learning_materials lm
        JOIN file_uploads fu ON lm.file_upload_id = fu.id
        WHERE lm.id = ? AND lm.status = 'active'
    ");
    $stmt->execute([$material_id]);
    $material = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$material) {
        echo json_encode(['success' => false, 'message' => 'Learning material not found']);
        exit();
    }
    
    // Check access permissions
    if ($user_role === 'student') {
        // Students can only access materials for their class
        $stmt = $pdo->prepare("SELECT class_id FROM students WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $student = $stmt->fetch();
        
        if (!$student || $material['class_id'] != $student['class_id']) {
            echo json_encode(['success' => false, 'message' => 'Access denied']);
            exit();
        }
        
        // Check specific access controls
        if ($material['access_control'] === 'specific_students') {
            // In a real implementation, you would check if this student is in the allowed list
            // For now, we'll allow access as this would require additional tables
        }
        
        // Check if download is allowed
        if ($action === 'download' && !$material['allow_download']) {
            echo json_encode(['success' => false, 'message' => 'Download not allowed for this material']);
            exit();
        }
    }
    
    // Log the access
    $stmt = $pdo->prepare("
        INSERT INTO learning_materials_views (material_id, user_id, action)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE created_at = CURRENT_TIMESTAMP
    ");
    $stmt->execute([$material_id, $user_id, $action]);
    
    // Return file download URL
    if ($action === 'download') {
        echo json_encode([
            'success' => true, 
            'message' => 'Access granted',
            'download_url' => '../uploads/download.php?id=' . $material['file_id']
        ]);
    } else {
        echo json_encode([
            'success' => true, 
            'message' => 'Access granted',
            'view_url' => '../uploads/download.php?id=' . $material['file_id']
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error accessing learning material: ' . $e->getMessage()]);
}
?>