 <?php
// Development helper: log errors to a file; avoid exposing details in browser
if (!defined('APP_DEBUG')) { define('APP_DEBUG', true); }
if (APP_DEBUG) {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    ini_set('log_errors', '1');
    ini_set('error_reporting', E_ALL);
    $logPath = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'php_errors.log';
    if (!file_exists($logPath)) { @touch($logPath); }
    ini_set('error_log', $logPath);
}
/**
 * Assignments Management
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/SecurityHelper.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit;
}

// Check admin role - support both new and legacy session variables
$user_role = $_SESSION['user_role'] ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin' && $user_role !== 'teacher')) {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="../../login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

$success_message = '';
$error_message = '';

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    SecurityHelper::validatePost();
    
    try {
        // Add assignment
        if (isset($_POST['add_assignment'])) {
            $stmt = $pdo->prepare("
                INSERT INTO lms_assignments (course_id, lesson_id, title, description, instructions, 
                    max_marks, due_date, attachment_url, allow_late_submission, status, created_by, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NOW())
            ");
            $stmt->execute([
                intval($_POST['course_id']),
                $_POST['lesson_id'] ?: null,
                sanitize($_POST['title']),
                sanitize($_POST['description'] ?? ''),
                sanitize($_POST['instructions'] ?? ''),
                floatval($_POST['max_marks'] ?? 100),
                $_POST['due_date'] ?: null,
                sanitize($_POST['attachment_url'] ?? ''),
                isset($_POST['allow_late_submission']) ? 1 : 0,
                $_SESSION['user_id']
            ]);
            $success_message = '✅ অ্যাসাইনমেন্ট সফলভাবে তৈরি হয়েছে!';
        }
        
        // Update assignment
        if (isset($_POST['update_assignment'])) {
            $stmt = $pdo->prepare("
                UPDATE lms_assignments 
                SET course_id=?, lesson_id=?, title=?, description=?, instructions=?, 
                    max_marks=?, due_date=?, attachment_url=?, allow_late_submission=?, 
                    status=?, updated_at=NOW()
                WHERE id=?
            ");
            $stmt->execute([
                intval($_POST['course_id']),
                $_POST['lesson_id'] ?: null,
                sanitize($_POST['title']),
                sanitize($_POST['description'] ?? ''),
                sanitize($_POST['instructions'] ?? ''),
                floatval($_POST['max_marks'] ?? 100),
                $_POST['due_date'] ?: null,
                sanitize($_POST['attachment_url'] ?? ''),
                isset($_POST['allow_late_submission']) ? 1 : 0,
                $_POST['status'],
                intval($_POST['assignment_id'])
            ]);
            $success_message = '✅ অ্যাসাইনমেন্ট সফলভাবে আপডেট হয়েছে!';
        }
        
        // Delete assignment
        if (isset($_POST['delete_assignment'])) {
            $stmt = $pdo->prepare("DELETE FROM lms_assignments WHERE id=?");
            $stmt->execute([intval($_POST['assignment_id'])]);
            $success_message = '✅ অ্যাসাইনমেন্ট মুছে ফেলা হয়েছে!';
        }
        
        // Grade submission
        if (isset($_POST['grade_submission'])) {
            $stmt = $pdo->prepare("
                UPDATE assignment_submissions 
                SET marks_obtained=?, feedback=?, graded_by=?, graded_at=NOW(), status='graded'
                WHERE id=?
            ");
            $stmt->execute([
                floatval($_POST['marks_obtained']),
                sanitize($_POST['feedback'] ?? ''),
                $_SESSION['user_id'],
                intval($_POST['submission_id'])
            ]);
            $success_message = '✅ চেকিং সম্পন্ন হয়েছে!';
        }
        
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get all assignments with related data
$assignments = $pdo->query("
    SELECT a.*, c.course_name, c.course_code,
            NULL as created_by_name,
           (SELECT COUNT(*) FROM assignment_submissions WHERE assignment_id = a.id) as total_submissions,
           (SELECT COUNT(*) FROM assignment_submissions WHERE assignment_id = a.id AND status='graded') as graded_count
    FROM lms_assignments a
    LEFT JOIN courses c ON a.course_id = c.id
    LEFT JOIN users s ON a.created_by = s.id
    ORDER BY a.created_at DESC
")->fetchAll();

// Get data for dropdowns
$courses = $pdo->query("SELECT id, course_name, course_code FROM courses WHERE status='active' ORDER BY course_name")->fetchAll();

// Get submissions for selected assignment
$selected_assignment_id = $_GET['assignment_id'] ?? null;
$submissions = [];
if ($selected_assignment_id) {
    $submissions = $pdo->prepare("
        SELECT asub.*, NULL as student_name,
               st.roll_number, st.class_id, cl.name as class_name
        FROM assignment_submissions asub
        LEFT JOIN students st ON asub.student_id = st.id
        LEFT JOIN classes cl ON st.class_id = cl.id
        WHERE asub.assignment_id=?
        ORDER BY asub.submitted_at DESC
    ");
    $submissions->execute([$selected_assignment_id]);
    $submissions = $submissions->fetchAll();
    
    $selected_assignment = $pdo->prepare("SELECT * FROM lms_assignments WHERE id=?");
    $selected_assignment->execute([$selected_assignment_id]);
    $selected_assignment = $selected_assignment->fetch();
}

// Edit mode
$edit_assignment = null;
if (isset($_GET['edit']) && $_GET['edit']) {
    $edit_assignment = $pdo->prepare("SELECT * FROM lms_assignments WHERE id=?");
    $edit_assignment->execute([intval($_GET['edit'])]);
    $edit_assignment = $edit_assignment->fetch();
}

// Get lessons for course
function getCourseLessons($pdo, $course_id) {
    return $pdo->prepare("
        SELECT cl.* FROM course_lessons cl
        JOIN course_modules cm ON cl.module_id = cm.id
        WHERE cm.course_id=?
        ORDER BY cm.sort_order, cl.sort_order
    ");
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অ্যাসাইনমেন্ট ব্যবস্থাপনা - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <main class="col-md-12 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">📝 অ্যাসাইনমেন্ট ব্যবস্থাপনা</h1>
                    <div>
                        <a href="index.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> ফিরে যান
                        </a>
                    </div>
                </div>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <?= $success_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <?= $error_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <!-- View Submissions -->
                <?php if ($selected_assignment_id && !empty($submissions)): ?>
                <div class="card mb-4">
                    <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">📤 জমা দেওয়া অ্যাসাইনমেন্ট - <?= htmlspecialchars($selected_assignment['title'] ?? '') ?></h5>
                        <div>
                            <span class="badge bg-light text-dark">মোট: <?= count($submissions) ?></span>
                            <a href="?" class="btn btn-light btn-sm ms-2">বন্ধ করুন</a>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>ছাত্রের নাম</th>
                                        <th>রোল</th>
                                        <th>ক্লাস</th>
                                        <th>জমা তারিখ</th>
                                        <th>উত্তর</th>
                                        <th>ফাইল</th>
                                        <th>স্ট্যাটাস</th>
                                        <th>নম্বর</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($submissions as $submission): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($submission['student_name']) ?></td>
                                        <td><?= htmlspecialchars($submission['roll_number']) ?></td>
                                        <td><?= htmlspecialchars($submission['class_name'] ?? '-') ?></td>
                                        <td><?= date('d M Y, h:i A', strtotime($submission['submitted_at'])) ?></td>
                                        <td>
                                            <?php if ($submission['submission_text']): ?>
                                            <button type="button" class="btn btn-sm btn-outline-info" data-bs-toggle="modal" data-bs-target="#viewText<?= $submission['id'] ?>">
                                                <i class="fas fa-file-alt"></i> দেখুন
                                            </button>
                                            <?php else: ?>
                                            <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($submission['attachment_url']): ?>
                                            <a href="<?= htmlspecialchars($submission['attachment_url']) ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-download"></i> ডাউনলোড
                                            </a>
                                            <?php else: ?>
                                            <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $submission['status'] == 'graded' ? 'success' : ($submission['status'] == 'submitted' ? 'warning' : 'info') ?>">
                                                <?= $submission['status'] == 'graded' ? 'চেক করা হয়েছে' : ($submission['status'] == 'submitted' ? 'জমা দেওয়া' : 'ড্রাফট') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($submission['marks_obtained'] !== null): ?>
                                                <strong><?= $submission['marks_obtained'] ?> / <?= $selected_assignment['max_marks'] ?></strong>
                                            <?php else: ?>
                                                <span class="text-muted">চেক করা হয়নি</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($submission['status'] != 'graded'): ?>
                                            <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#gradeModal<?= $submission['id'] ?>">
                                                <i class="fas fa-check"></i> চেক করুন
                                            </button>
                                            <?php else: ?>
                                            <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#gradeModal<?= $submission['id'] ?>">
                                                <i class="fas fa-edit"></i> পরিবর্তন
                                            </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- View Text Modals -->
                <?php foreach ($submissions as $submission): ?>
                    <?php if ($submission['submission_text']): ?>
                    <div class="modal fade" id="viewText<?= $submission['id'] ?>" tabindex="-1">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">ছাত্রের উত্তর - <?= htmlspecialchars($submission['student_name']) ?></h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="p-3 bg-light rounded">
                                        <?= nl2br(htmlspecialchars($submission['submission_text'])) ?>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Grade Modal -->
                    <div class="modal fade" id="gradeModal<?= $submission['id'] ?>" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">✓ চেক করুন - <?= htmlspecialchars($submission['student_name']) ?></h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <form method="POST">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="submission_id" value="<?= $submission['id'] ?>">
                                    <div class="modal-body">
                                        <div class="mb-3">
                                            <label class="form-label">প্রাপ্ত নম্বর (সর্বোচ্চ <?= $selected_assignment['max_marks'] ?>)</label>
                                            <input type="number" name="marks_obtained" class="form-control" 
                                                   max="<?= $selected_assignment['max_marks'] ?>" step="0.5" required
                                                   value="<?= $submission['marks_obtained'] ?? '' ?>">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">মন্তব্য / ফিডব্যাক</label>
                                            <textarea name="feedback" class="form-control" rows="3"><?= htmlspecialchars($submission['feedback'] ?? '') ?></textarea>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                                        <button type="submit" name="grade_submission" class="btn btn-success">সংরক্ষণ করুন</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
                <?php endif; ?>
                
                <!-- Add/Edit Assignment Form -->
                <div class="card mb-4">
                    <div class="card-header <?= $edit_assignment ? 'bg-warning' : 'bg-primary' ?> text-white">
                        <h5 class="mb-0"><?= $edit_assignment ? '✏️ অ্যাসাইনমেন্ট সম্পাদনা' : '➕ নতুন অ্যাসাইনমেন্ট তৈরি করুন' ?></h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <?= csrf_field() ?>
                            <input type="hidden" name="assignment_id" value="<?= $edit_assignment['id'] ?? '' ?>">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">শিরোনাম <span class="text-danger">*</span></label>
                                    <input type="text" name="title" class="form-control" required
                                           value="<?= htmlspecialchars($edit_assignment['title'] ?? '') ?>">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">কোর্স <span class="text-danger">*</span></label>
                                    <select name="course_id" class="form-select" required>
                                        <option value="">-- নির্বাচন --</option>
                                        <?php foreach ($courses as $c): ?>
                                        <option value="<?= $c['id'] ?>" <?= ($edit_assignment['course_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['course_name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">স্ট্যাটাস</label>
                                    <select name="status" class="form-select">
                                        <option value="active" <?= ($edit_assignment['status'] ?? '') == 'active' ? 'selected' : '' ?>>সক্রিয়</option>
                                        <option value="inactive" <?= ($edit_assignment['status'] ?? '') == 'inactive' ? 'selected' : '' ?>>নিষ্ক্রিয়</option>
                                        <option value="archived" <?= ($edit_assignment['status'] ?? '') == 'archived' ? 'selected' : '' ?>>আর্কাইভ</option>
                                    </select>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">বিবরণ</label>
                                    <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($edit_assignment['description'] ?? '') ?></textarea>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">নির্দেশাবলী</label>
                                    <textarea name="instructions" class="form-control" rows="3"><?= htmlspecialchars($edit_assignment['instructions'] ?? '') ?></textarea>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">সর্বোচ্চ নম্বর</label>
                                    <input type="number" name="max_marks" class="form-control" value="<?= $edit_assignment['max_marks'] ?? 100 ?>" min="1">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">জমার শেষ তারিখ</label>
                                    <input type="datetime-local" name="due_date" class="form-control"
                                           value="<?= isset($edit_assignment['due_date']) ? date('Y-m-d\TH:i', strtotime($edit_assignment['due_date'])) : '' ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">সংযুক্তি URL (ঐচ্ছিক)</label>
                                    <input type="url" name="attachment_url" class="form-control" placeholder="https://..."
                                           value="<?= htmlspecialchars($edit_assignment['attachment_url'] ?? '') ?>">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <div class="form-check">
                                        <input type="checkbox" name="allow_late_submission" class="form-check-input" id="lateSubmit"
                                               <?= ($edit_assignment['allow_late_submission'] ?? 0) ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="lateSubmit">দেরিতে জমা দেওয়ার অনুমতি দিন</label>
                                    </div>
                                </div>
                            </div>
                            <button type="submit" name="<?= $edit_assignment ? 'update_assignment' : 'add_assignment' ?>" class="btn <?= $edit_assignment ? 'btn-warning' : 'btn-primary' ?>">
                                <?= $edit_assignment ? '✏️ আপডেট করুন' : '➕ তৈরি করুন' ?>
                            </button>
                            <?php if ($edit_assignment): ?>
                            <a href="?" class="btn btn-secondary">বাতিল করুন</a>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
                
                <!-- Assignments List -->
                <div class="card">
                    <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">📋 সকল অ্যাসাইনমেন্ট</h5>
                        <span class="badge bg-light text-dark">মোট: <?= count($assignments) ?></span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>শিরোনাম</th>
                                        <th>কোর্স</th>
                                        <th>সর্বোচ্চ নম্বর</th>
                                        <th>শেষ তারিখ</th>
                                        <th>জমা</th>
                                        <th>চেক করা</th>
                                        <th>স্ট্যাটাস</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($assignments as $assignment): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($assignment['title']) ?></strong></td>
                                        <td><?= htmlspecialchars($assignment['course_name'] ?? '-') ?></td>
                                        <td><?= $assignment['max_marks'] ?></td>
                                        <td><?= $assignment['due_date'] ? date('d M Y, h:i A', strtotime($assignment['due_date'])) : 'নেই' ?></td>
                                        <td><span class="badge bg-info"><?= $assignment['total_submissions'] ?></span></td>
                                        <td><span class="badge bg-success"><?= $assignment['graded_count'] ?> / <?= $assignment['total_submissions'] ?></span></td>
                                        <td>
                                            <span class="badge bg-<?= $assignment['status'] == 'active' ? 'success' : ($assignment['status'] == 'inactive' ? 'warning' : 'secondary') ?>">
                                                <?= $assignment['status'] == 'active' ? 'সক্রিয়' : ($assignment['status'] == 'inactive' ? 'নিষ্ক্রিয়' : 'আর্কাইভ') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="?assignment_id=<?= $assignment['id'] ?>" class="btn btn-sm btn-info" title="জমাসমূহ দেখুন">
                                                <i class="fas fa-eye"></i> জমাসমূহ
                                            </a>
                                            <a href="?edit=<?= $assignment['id'] ?>" class="btn btn-sm btn-warning" title="সম্পাদনা">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিত যে এই অ্যাসাইনমেন্টটি মুছে ফেলতে চান?');">
                                                <?= csrf_field() ?>
                                                <input type="hidden" name="assignment_id" value="<?= $assignment['id'] ?>">
                                                <button type="submit" name="delete_assignment" class="btn btn-sm btn-danger" title="মুছুন">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($assignments)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center text-muted py-4">
                                            <i class="fas fa-clipboard-list fa-2x mb-2"></i><br>
                                            কোনো অ্যাসাইনমেন্ট পাওয়া যায়নি
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
