<?php
/**
 * Student Progress Management
 */

// DEBUG: Show all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// Ensure a single session is started
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 {
        // Update progress manually
        if (isset($_POST['update_progress'])) {
            $stmt = $pdo->prepare("
                INSERT INTO student_lesson_progress (student_id, lesson_id, course_id, is_completed, completion_date, time_spent_minutes)
                VALUES (?, ?, ?, 1, NOW(), ?)
                ON DUPLICATE KEY UPDATE is_completed=1, completion_date=NOW(), time_spent_minutes=VALUES(time_spent_minutes)
            ");
            $stmt->execute([
                intval($_POST['student_id']),
                intval($_POST['lesson_id']),
                intval($_POST['course_id']),
                intval($_POST['time_spent'] ?? 0)
            ]);
            $success_message = '✅ অগ্রগতি আপডেট হয়েছে!';
        }
        
    } catch(Exception $e) {
        // Log the detailed error for debugging, but show generic message to user
        error_log('Student_progress.php: POST update_progress error: ' . $e->getMessage());
        $error_message = '❌ ত্রুটি ঘটেছে। প্রচেষ্টা করুন পরে আবার।';
    }
}

// Get filter parameters
$course_filter = $_GET['course_id'] ?? '';
$class_filter = $_GET['class_id'] ?? '';
$student_filter = $_GET['student_id'] ?? '';

// DEBUG: Log filter parameters
error_log('Student_progress.php: Filters - course=' . $course_filter . ', class=' . $class_filter . ', student=' . $student_filter);

// Get all courses
try {
    $courses = $pdo->query("SELECT id, course_name, course_code FROM courses ORDER BY course_name")->fetchAll();
} catch (Exception $e) {
    error_log('Student_progress.php: Error loading courses: ' . $e->getMessage());
    $courses = [];
}

// Get all classes
try {
    $classes = $pdo->query("SELECT id, name FROM classes WHERE status='active' ORDER BY name")->fetchAll();
} catch (Exception $e) {
    error_log('Student_progress.php: Error loading classes: ' . $e->getMessage());
    $classes = [];
}

// Build query for student progress
$where_conditions = [];
$params = [];

if ($course_filter) {
    $where_conditions[] = "se.course_id=?";
    $params[] = $course_filter;
}

if ($class_filter) {
    $where_conditions[] = "s.class_id=?";
    $params[] = $class_filter;
}

if ($student_filter) {
    $where_conditions[] = "s.id=?";
    $params[] = $student_filter;
}

$where_clause = $where_conditions ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get student enrollments with progress data
$students_query = "
    SELECT s.id as student_id, CONCAT('Student ', s.id) as student_name,
           s.roll_number, cl.name as class_name, cl.id as class_id,
           c.id as course_id, c.course_name, c.course_code,
           se.enrollment_date, se.status as enrollment_status,
           (SELECT COUNT(*) FROM course_lessons WHERE course_id = c.id) as total_lessons,
           (SELECT COUNT(*) FROM student_lesson_progress WHERE student_id = s.id AND course_id = c.id AND is_completed=1) as completed_lessons,
           (SELECT SUM(time_spent_minutes) FROM student_lesson_progress WHERE student_id = s.id AND course_id = c.id) as total_time_spent,
           (SELECT COUNT(*) FROM assignment_submissions WHERE student_id = s.id AND assignment_id IN (SELECT id FROM lms_assignments WHERE course_id = c.id)) as assignments_submitted,
           (SELECT AVG(marks_obtained) FROM assignment_submissions WHERE student_id = s.id AND assignment_id IN (SELECT id FROM lms_assignments WHERE course_id = c.id) AND status='graded') as avg_assignment_score,
           (SELECT COUNT(*) FROM live_class_attendance WHERE student_id = s.id AND live_class_id IN (SELECT id FROM live_classes WHERE course_id = c.id)) as live_classes_attended
    FROM student_enrollments se
    LEFT JOIN students s ON se.student_id = s.id
    LEFT JOIN classes cl ON s.class_id = cl.id
    LEFT JOIN courses c ON se.course_id = c.id
    $where_clause
    ORDER BY cl.name, s.id, c.course_name
";

try {
    $students_stmt = $pdo->prepare($students_query);
    $students_stmt->execute($params);
    $students = $students_stmt->fetchAll();
    // DEBUG: Log how many students were found
    error_log('Student_progress.php: Loaded ' . count($students) . ' students. Query params: ' . json_encode($params));
} catch (Exception $e) {
    error_log('Student_progress.php: Error loading students: ' . $e->getMessage());
    $students = [];
}

// Get students for dropdown - filtered by class if selected
try {
    if ($class_filter) {
        // If class is selected, show only students from that class
        $all_students_stmt = $pdo->prepare("
            SELECT s.id, CONCAT('Student ', s.id) as student_name, s.roll_number, cl.name as class_name
            FROM students s
            LEFT JOIN classes cl ON s.class_id = cl.id
            WHERE s.status='active' AND s.class_id = ?
            ORDER BY cl.name, s.id
        ");
        $all_students_stmt->execute([$class_filter]);
        $all_students = $all_students_stmt->fetchAll();
    } else {
        // If no class selected, show all students
        $all_students = $pdo->query("
            SELECT s.id, CONCAT('Student ', s.id) as student_name, s.roll_number, cl.name as class_name
            FROM students s
            LEFT JOIN classes cl ON s.class_id = cl.id
            WHERE s.status='active'
            ORDER BY cl.name, s.id
        ")->fetchAll();
    }
    // DEBUG: Log how many students are in dropdown
    error_log('Student_progress.php: Loaded ' . count($all_students) . ' students for dropdown (class_filter=' . ($class_filter ?: 'none') . ')');
} catch (Exception $e) {
    error_log('Student_progress.php: Error loading all_students: ' . $e->getMessage());
    $all_students = [];
}

// Get detailed progress for selected student
$selected_student_id = $_GET['view_student'] ?? null;
$selected_course_id = $_GET['view_course'] ?? null;
$student_details = null;
$lesson_progress = [];
$assignment_progress = [];

if ($selected_student_id && $selected_course_id) {
    try {
        $student_details = $pdo->prepare("
            SELECT s.*, cl.name as class_name,
                   c.course_name, c.course_code, c.id as course_id,
                   se.enrollment_date
            FROM students s
            LEFT JOIN classes cl ON s.class_id = cl.id
            JOIN student_enrollments se ON s.id = se.student_id
            JOIN courses c ON se.course_id = c.id
            WHERE s.id=? AND c.id=?
        ");
        $student_details->execute([$selected_student_id, $selected_course_id]);
        $student_details = $student_details->fetch();
        
        if ($student_details) {
            // Get lesson progress
            $lesson_progress = $pdo->prepare("
                SELECT cl.*, cm.module_name, 
                       COALESCE(slp.is_completed, 0) as is_completed,
                       slp.completion_date, slp.time_spent_minutes
                FROM course_lessons cl
                JOIN course_modules cm ON cl.module_id = cm.id
                LEFT JOIN student_lesson_progress slp ON cl.id = slp.lesson_id AND slp.student_id=?
                WHERE cl.course_id=?
                ORDER BY cm.sort_order, cl.sort_order
            ");
            $lesson_progress->execute([$selected_student_id, $selected_course_id]);
            $lesson_progress = $lesson_progress->fetchAll();
            
            // Get assignment progress
            $assignment_progress = $pdo->prepare("
                SELECT la.*, 
                       COALESCE(asub.id, 0) as has_submitted,
                       asub.submitted_at, asub.marks_obtained, asub.status
                FROM lms_assignments la
                LEFT JOIN assignment_submissions asub ON la.id = asub.assignment_id AND asub.student_id=?
                WHERE la.course_id=? AND la.status='active'
                ORDER BY la.due_date DESC
            ");
            $assignment_progress->execute([$selected_student_id, $selected_course_id]);
            $assignment_progress = $assignment_progress->fetchAll();
        }
    } catch (Exception $e) {
        error_log('Student_progress.php: Error loading student details/progress: ' . $e->getMessage());
        $student_details = null;
        $lesson_progress = [];
        $assignment_progress = [];
    }
}

// Calculate overall statistics
$total_enrolled = count($students);
$avg_progress = 0;
if ($total_enrolled > 0) {
    $total_progress = 0;
    foreach ($students as $student) {
        $progress = $student['total_lessons'] > 0 ? ($student['completed_lessons'] / $student['total_lessons']) * 100 : 0;
        $total_progress += $progress;
    }
    $avg_progress = round($total_progress / $total_enrolled, 1);
}

// DEBUG: Log successful page load
error_log('Student_progress.php: Page loaded successfully. Students: ' . $total_enrolled . ', Courses: ' . count($courses) . ', Classes: ' . count($classes));
?>
<!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">
    <style>
        .progress-ring {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
        }
        .progress-high { background: #28a745; }
        .progress-medium { background: #ffc107; color: #000 !important; }
        .progress-low { background: #dc3545; }
    </style>
</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; ?>
                
                <!-- Filter Section -->
                <div class="card mb-4">
                    <div class="card-header bg-light">
                        <h5 class="mb-0">🔍 ফিল্টার</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row">
                            <div class="col-md-3 mb-2">
                                <label class="form-label">কোর্স</label>
                                <select name="course_id" class="form-select">
                                    <option value="">সব কোর্স</option>
                                    <?php foreach ($courses as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= $course_filter == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['course_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label class="form-label">ক্লাস</label>
                                <select name="class_id" class="form-select">
                                    <option value="">সব ক্লাস</option>
                                    <?php foreach ($classes as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= $class_filter == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label class="form-label">ছাত্র</label>
                                <select name="student_id" class="form-select">
                                    <option value="">সব ছাত্র</option>
                                    <?php foreach ($all_students as $s): ?>
                                    <option value="<?= $s['id'] ?>" <?= $student_filter == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['student_name']) ?> (<?= $s['class_name'] ?? '-' ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3 mb-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-filter"></i> ফিল্টার করুন
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="card bg-primary text-white">
                            <div class="card-body text-center">
                                <h5>মোট নথিভুক্ত ছাত্র</h5>
                                <h2><?= $total_enrolled ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card bg-success text-white">
                            <div class="card-body text-center">
                                <h5>গড় অগ্রগতি</h5>
                                <h2><?= $avg_progress ?>%</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card bg-info text-white">
                            <div class="card-body text-center">
                                <h5>সক্রিয় কোর্স</h5>
                                <h2><?= count($courses) ?></h2>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Student Progress Table -->
                <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($students) ?> জন</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>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($students as $student): 
                                        $progress_percent = $student['total_lessons'] > 0 ? round(($student['completed_lessons'] / $student['total_lessons']) * 100, 1) : 0;
                                        $progress_class = $progress_percent >= 70 ? 'progress-high' : ($progress_percent >= 40 ? 'progress-medium' : 'progress-low');
                                    ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($student['student_name']) ?></strong></td>
                                        <td><?= htmlspecialchars($student['roll_number']) ?></td>
                                        <td><?= htmlspecialchars($student['class_name'] ?? '-') ?></td>
                                        <td><?= htmlspecialchars($student['course_name']) ?></td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="progress-ring <?= $progress_class ?> me-2" style="width: 40px; height: 40px; font-size: 12px;">
                                                    <?= round($progress_percent) ?>%
                                                </div>
                                                <small class="text-muted"><?= $student['completed_lessons'] ?>/<?= $student['total_lessons'] ?> পাঠ</small>
                                            </div>
                                        </td>
                                        <td><?= round(($student['total_time_spent'] ?? 0) / 60, 1) ?> ঘণ্টা</td>
                                        <td>
                                            <span class="badge bg-primary"><?= $student['assignments_submitted'] ?> জমা</span>
                                            <?php if ($student['avg_assignment_score']): ?>
                                            <br><small class="text-muted">গড়: <?= round($student['avg_assignment_score'], 1) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td><span class="badge bg-success"><?= $student['live_classes_attended'] ?> ক্লাস</span></td>
                                        <td>
                                            <a href="?view_student=<?= $student['student_id'] ?>&view_course=<?= $student['course_id'] ?>" class="btn btn-sm btn-info" title="বিস্তারিত দেখুন">
                                                <i class="fas fa-chart-line"></i> বিস্তারিত
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($students)): ?>
                                    <tr>
                                        <td colspan="9" class="text-center text-muted py-4">
                                            <i class="fas fa-user-graduate fa-2x mb-2"></i><br>
                                            কোনো ছাত্র পাওয়া যায়নি
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Student Detailed Progress Modal -->
                <?php if ($student_details): ?>
                <div class="modal show" id="studentDetailModal" tabindex="-1" style="display: block;">
                    <div class="modal-dialog modal-xl">
                        <div class="modal-content">
                            <div class="modal-header bg-primary text-white">
                                <h5 class="modal-title">📊 <?= htmlspecialchars($student_details['first_name'] . ' ' . $student_details['last_name']) ?> - বিস্তারিত অগ্রগতি</h5>
                                <a href="?<?= http_build_query(array_diff_key($_GET, array_flip(['view_student', 'view_course']))) ?>" class="btn-close btn-close-white"></a>
                            </div>
                            <div class="modal-body">
                                <div class="row mb-4">
                                    <div class="col-md-6">
                                        <h6>👤 ছাত্রের তথ্য</h6>
                                        <p><strong>নাম:</strong> <?= htmlspecialchars($student_details['first_name'] . ' ' . $student_details['last_name']) ?></p>
                                        <p><strong>রোল:</strong> <?= htmlspecialchars($student_details['roll_number']) ?></p>
                                        <p><strong>ক্লাস:</strong> <?= htmlspecialchars($student_details['class_name'] ?? '-') ?></p>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>📚 কোর্স তথ্য</h6>
                                        <p><strong>কোর্স:</strong> <?= htmlspecialchars($student_details['course_name']) ?> (<?= $student_details['course_code'] ?>)</p>
                                        <p><strong>নথিভুক্তির তারিখ:</strong> <?= date('d M Y', strtotime($student_details['enrollment_date'])) ?></p>
                                        <?php 
                                        $completed = count(array_filter($lesson_progress, fn($l) => $l['is_completed']));
                                        $total = count($lesson_progress);
                                        $percent = $total > 0 ? round(($completed / $total) * 100, 1) : 0;
                                        ?>
                                        <p><strong>অগ্রগতি:</strong> <?= $completed ?>/<?= $total ?> পাঠ (<?= $percent ?>%)</p>
                                    </div>
                                </div>
                                
                                <!-- Lesson Progress -->
                                <h6 class="mb-3">📖 পাঠের অগ্রগতি</h6>
                                <div class="table-responsive mb-4">
                                    <table class="table table-sm table-bordered">
                                        <thead class="table-light">
                                            <tr>
                                                <th>মডিউল</th>
                                                <th>পাঠ</th>
                                                <th>সময়কাল</th>
                                                <th>সম্পন্ন</th>
                                                <th>সময় ব্যয়</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $current_module = '';
                                            foreach ($lesson_progress as $lesson): 
                                                if ($current_module != $lesson['module_name']):
                                                    $current_module = $lesson['module_name'];
                                            ?>
                                            <tr class="table-secondary">
                                                <td colspan="5"><strong><?= htmlspecialchars($lesson['module_name']) ?></strong></td>
                                            </tr>
                                            <?php endif; ?>
                                            <tr>
                                                <td></td>
                                                <td><?= htmlspecialchars($lesson['lesson_title']) ?></td>
                                                <td><?= $lesson['duration_minutes'] ?> মিনিট</td>
                                                <td>
                                                    <?php if ($lesson['is_completed']): ?>
                                                        <span class="badge bg-success">✓ সম্পন্ন</span>
                                                        <br><small class="text-muted"><?= date('d M Y', strtotime($lesson['completion_date'])) ?></small>
                                                    <?php else: ?>
                                                        <span class="badge bg-warning">⏳ চলমান</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?= $lesson['time_spent_minutes'] ?? 0 ?> মিনিট</td>
                                            </tr>
                                            <?php endforeach; ?>
                                            <?php if (empty($lesson_progress)): ?>
                                            <tr>
                                                <td colspan="5" class="text-center text-muted">কোনো পাঠ যোগ করা হয়নি</td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                
                                <!-- Assignment Progress -->
                                <h6 class="mb-3">📝 অ্যাসাইনমেন্ট অগ্রগতি</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm table-bordered">
                                        <thead class="table-light">
                                            <tr>
                                                <th>অ্যাসাইনমেন্ট</th>
                                                <th>জমার শেষ তারিখ</th>
                                                <th>স্ট্যাটাস</th>
                                                <th>জমার তারিখ</th>
                                                <th>নম্বর</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($assignment_progress as $assignment): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($assignment['title']) ?></td>
                                                <td><?= $assignment['due_date'] ? date('d M Y, h:i A', strtotime($assignment['due_date'])) : 'নেই' ?></td>
                                                <td>
                                                    <?php if ($assignment['has_submitted']): ?>
                                                        <span class="badge bg-success">✓ জমা দেওয়া</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-warning">⏳ জমা হয়নি</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?= $assignment['submitted_at'] ? date('d M Y, h:i A', strtotime($assignment['submitted_at'])) : '-' ?></td>
                                                <td>
                                                    <?php if ($assignment['marks_obtained'] !== null): ?>
                                                        <strong><?= $assignment['marks_obtained'] ?> / <?= $assignment['max_marks'] ?></strong>
                                                    <?php else: ?>
                                                        <span class="text-muted">চেক করা হয়নি</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                            <?php if (empty($assignment_progress)): ?>
                                            <tr>
                                                <td colspan="5" class="text-center text-muted">কোনো অ্যাসাইনমেন্ট নেই</td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <a href="?<?= http_build_query(array_diff_key($_GET, array_flip(['view_student', 'view_course']))) ?>" class="btn btn-secondary">বন্ধ করুন</a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-backdrop show" style="display: block;"></div>
                <?php endif; ?>
                
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
