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

// Check if user is logged in and is admin/teacher
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'teacher')) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    // Get POST data
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $class_id = $_POST['class_id'] ?? '';
    $subject_id = $_POST['subject_id'] ?? '';
    $due_date = $_POST['due_date'] ?? '';
    $max_marks = $_POST['max_marks'] ?? 20;
    $instructions = $_POST['instructions'] ?? '';
    
    // Validate required fields
    if (empty($title) || empty($class_id) || empty($subject_id) || empty($due_date)) {
        echo json_encode(['success' => false, 'message' => 'Title, class, subject, and due date are required']);
        exit();
    }
    
    // Get teacher ID from session
    $teacherStmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $teacherStmt->execute([$_SESSION['user_id']]);
    $teacher = $teacherStmt->fetch();
    
    // If no teacher record found, check if user is admin
    if (!$teacher && $_SESSION['user_role'] === 'admin') {
        // For admin, we'll use a default teacher or create a temporary one
        // First, check if there's any teacher in the system
        $anyTeacherStmt = $pdo->query("SELECT id FROM teachers LIMIT 1");
        $anyTeacher = $anyTeacherStmt->fetch();
        
        if ($anyTeacher) {
            $teacher = $anyTeacher;
        } else {
            // If no teachers exist, we'll need to handle this case
            echo json_encode(['success' => false, 'message' => 'No teachers found in system. Please create a teacher account first.']);
            exit();
        }
    }
    
    if (!$teacher) {
        echo json_encode(['success' => false, 'message' => 'Teacher record not found. Only teachers and admins can create assignments.']);
        exit();
    }
    
    // Debug: Log the data we're about to insert
    error_log("Creating assignment with data: " . json_encode([
        'title' => $title,
        'description' => $description,
        'class_id' => $class_id,
        'subject_id' => $subject_id,
        'teacher_id' => $teacher['id'],
        'due_date' => $due_date,
        'max_marks' => $max_marks,
        'instructions' => $instructions
    ]));
    
    // Insert assignment into database
    $stmt = $pdo->prepare("
        INSERT INTO assignments (title, description, class_id, subject_id, teacher_id, due_date, max_marks, instructions, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $result = $stmt->execute([
        $title,
        $description,
        $class_id,
        $subject_id,
        $teacher['id'],
        $due_date,
        $max_marks,
        $instructions,
        'published' // status
    ]);
    
    if ($result) {
        $assignmentId = $pdo->lastInsertId();
        echo json_encode([
            'success' => true, 
            'message' => 'Assignment created successfully', 
            'assignment_id' => $assignmentId
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to create assignment']);
    }
    
} catch (Exception $e) {
    error_log("Assignment creation error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>