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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Only teachers and admins can access this page
if ($user_role !== 'teacher' && $user_role !== 'admin') {
    // Redirect students to their results page
    if (isset($_GET['id'])) {
        header('Location: view_assignment_results.php?id=' . $_GET['id']);
    } else {
        header('Location: assignments.php');
    }
    exit();
}

// Check if assignment ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: assignments.php');
    exit();
}

$assignment_id = $_GET['id'];

// Fetch assignment details
try {
    $stmt = $pdo->prepare("
        SELECT a.*, c.name as class_name, c.section as class_section, s.name as subject_name 
        FROM assignments a
        JOIN classes c ON a.class_id = c.id
        JOIN subjects s ON a.subject_id = s.id
        WHERE a.id = ?
    ");
    $stmt->execute([$assignment_id]);
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$assignment) {
        header('Location: assignments.php');
        exit();
    }
    
    // Fetch submissions for this assignment
    $stmt = $pdo->prepare("
        SELECT asub.*, s.first_name, s.last_name, s.roll_number
        FROM assignment_submissions asub
        JOIN students s ON asub.student_id = s.id
        WHERE asub.assignment_id = ?
        ORDER BY asub.created_at DESC
    ");
    $stmt->execute([$assignment_id]);
    $submissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    error_log("Error fetching assignment submissions: " . $e->getMessage());
    $error_message = "Error loading submissions: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অ্যাসাইনমেন্ট জমা - অনলাইন শিক্ষা</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .submission-card {
            border-radius: 15px;
            overflow: hidden;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .submission-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .submission-header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 20px;
        }
        
        .submission-body {
            padding: 20px;
        }
        
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-submitted {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-graded {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .modal-content {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .grade-input {
            width: 100px;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="sidebar-container">
        <?php echo renderSidebar('online_learning/assignments.php', $user_role, $user_name); ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-file-upload me-2"></i>
                    অ্যাসাইনমেন্ট জমা
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / অনলাইন শিক্ষা / অ্যাসাইনমেন্ট / জমা
                </p>
            </div>
            
            <!-- Content Body -->
            <div class="content-body">
                <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-12">
                        <div class="card submission-card">
                            <div class="submission-header">
                                <h2><?php echo htmlspecialchars($assignment['title']); ?></h2>
                                <p><?php echo htmlspecialchars($assignment['subject_name']); ?> - <?php echo htmlspecialchars($assignment['class_name'] . ' - ' . $assignment['class_section']); ?></p>
                                <p>জমা দেওয়ার শেষ তারিখ: <?php echo date('d F, Y h:i A', strtotime($assignment['due_date'])); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-list me-2"></i>
                                    জমা তালিকা
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($submissions) > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead>
                                                <tr>
                                                    <th>ছাত্র/ছাত্রী</th>
                                                    <th>রোল নম্বর</th>
                                                    <th>জমা দেওয়ার তারিখ</th>
                                                    <th>ফাইল</th>
                                                    <th>মন্তব্য</th>
                                                    <th>অবস্থা</th>
                                                    <th>কার্যক্রম</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($submissions as $submission): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($submission['first_name'] . ' ' . $submission['last_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($submission['roll_number']); ?></td>
                                                        <td><?php echo date('d F, Y h:i A', strtotime($submission['created_at'])); ?></td>
                                                        <td>
                                                            <?php if ($submission['file_upload_id']): ?>
                                                                <a href="../uploads/download.php?id=<?php echo $submission['file_upload_id']; ?>" class="btn btn-sm btn-outline-primary">
                                                                    <i class="fas fa-download"></i> ডাউনলোড
                                                                </a>
                                                            <?php else: ?>
                                                                নেই
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($submission['feedback']); ?></td>
                                                        <td>
                                                            <?php 
                                                            $status_text = '';
                                                            $status_class = '';
                                                            switch ($submission['status']) {
                                                                case 'submitted':
                                                                    $status_text = 'জমা দেওয়া হয়েছে';
                                                                    $status_class = 'status-submitted';
                                                                    break;
                                                                case 'graded':
                                                                    $status_text = 'মূল্যায়ন করা হয়েছে';
                                                                    $status_class = 'status-graded';
                                                                    break;
                                                                case 'returned':
                                                                    $status_text = 'ফেরত দেওয়া হয়েছে';
                                                                    $status_class = 'status-graded';
                                                                    break;
                                                                default:
                                                                    $status_text = 'চলছে';
                                                                    $status_class = 'status-pending';
                                                            }
                                                            ?>
                                                            <span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                                        </td>
                                                        <td>
                                                            <button class="btn btn-sm btn-primary" onclick="gradeSubmission(<?php echo $submission['id']; ?>)">
                                                                <i class="fas fa-star"></i> মূল্যায়ন
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center py-5">
                                        <i class="fas fa-file-alt fa-3x mb-3 text-muted"></i>
                                        <h4>এখনও কোন জমা পাওয়া যায়নি</h4>
                                        <p class="text-muted">ছাত্র-ছাত্রীদের এখনও এই অ্যাসাইনমেন্টটি জমা দেওয়া হয়নি।</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-3">
                    <a href="assignments.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left me-2"></i>
                        অ্যাসাইনমেন্ট তালিকায় ফিরে যান
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Grading Modal -->
    <div class="modal fade" id="gradeModal" tabindex="-1" aria-labelledby="gradeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="gradeModalLabel">অ্যাসাইনমেন্ট মূল্যায়ন</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="submissionId">
                    <div class="mb-3">
                        <label for="gradeInput" class="form-label">প্রাপ্ত নম্বর (সর্বোচ্চ <?php echo $assignment['max_marks']; ?>)</label>
                        <input type="number" class="form-control grade-input" id="gradeInput" min="0" max="<?php echo $assignment['max_marks']; ?>" step="0.01" placeholder="প্রাপ্ত নম্বর">
                    </div>
                    <div class="mb-3">
                        <label for="feedbackInput" class="form-label">প্রতিক্রিয়া</label>
                        <textarea class="form-control" id="feedbackInput" rows="4" placeholder="ছাত্র-ছাত্রীকে প্রতিক্রিয়া দিন"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="button" class="btn btn-primary" id="saveGradeBtn">সংরক্ষণ</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function gradeSubmission(submissionId) {
            // Set the submission ID in the modal
            document.getElementById('submissionId').value = submissionId;
            
            // Clear previous values
            document.getElementById('gradeInput').value = '';
            document.getElementById('feedbackInput').value = '';
            
            // Show the modal
            var gradeModal = new bootstrap.Modal(document.getElementById('gradeModal'));
            gradeModal.show();
        }
        
        // Save grade when button is clicked
        document.getElementById('saveGradeBtn').addEventListener('click', function() {
            const submissionId = document.getElementById('submissionId').value;
            const grade = document.getElementById('gradeInput').value;
            const feedback = document.getElementById('feedbackInput').value;
            
            // Validate input
            if (grade === '' || isNaN(grade)) {
                alert('দয়া করে একটি বৈধ নম্বর প্রদান করুন');
                return;
            }
            
            const maxMarks = <?php echo $assignment['max_marks']; ?>;
            if (grade < 0 || grade > maxMarks) {
                alert('নম্বর ০ থেকে ' + maxMarks + ' এর মধ্যে হতে হবে');
                return;
            }
            
            // Send grading data to API
            fetch('api/grade_submission.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    submission_id: submissionId,
                    grade: parseFloat(grade),
                    feedback: feedback
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('মূল্যায়ন সফলভাবে সংরক্ষিত হয়েছে');
                    // Reload the page to show updated status
                    location.reload();
                } else {
                    alert('ত্রুটি: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('মূল্যায়ন সংরক্ষণে ত্রুটি হয়েছে');
            });
        });
    </script>
</body>
</html>