<?php
session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';

// Check if user is logged in and is a teacher
require_teacher();

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? $_SESSION['username'] ?? 'শিক্ষক';

// Only teachers can access this page
if ($user_role !== 'teacher') {
    header('Location: ../index.php');
    exit();
}

// Get teacher ID
$teacher_id = null;
$stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
$stmt->execute([$user_id]);
$teacher = $stmt->fetch();
if ($teacher) {
    $teacher_id = $teacher['id'];
} else {
    // Redirect if not a valid teacher
    header('Location: dashboard.php');
    exit();
}

// Get teacher's assigned classes and subjects
$assigned_classes = [];
$assigned_subjects = [];
$assigned_class_ids = [];

if ($teacher_id) {
    $assigned_class_ids = get_teacher_assigned_classes($teacher_id);

    // Get detailed class information
    if (!empty($assigned_class_ids)) {
        $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT DISTINCT c.id, c.name, c.section
            FROM classes c
            WHERE c.id IN ($placeholders) AND c.status = 'active'
            ORDER BY c.name, c.section
        ");
        $stmt->execute($assigned_class_ids);
        $assigned_classes = $stmt->fetchAll();
    }

    // Get assigned subjects
    $assigned_subjects = get_teacher_assigned_subjects($teacher_id, $assigned_class_ids);
    if (!empty($assigned_subjects)) {
        $placeholders = str_repeat('?,', count($assigned_subjects) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT DISTINCT s.id, s.name, s.code
            FROM subjects s
            WHERE s.id IN ($placeholders) AND s.status = 'active'
            ORDER BY s.name
        ");
        $stmt->execute($assigned_subjects);
        $assigned_subjects = $stmt->fetchAll();
    }
}

// Debug: Check if we have classes and subjects
// error_log("Teacher ID: $teacher_id, Classes: " . count($assigned_classes) . ", Subjects: " . count($assigned_subjects));

$report_data = [];
$report_type = '';
$selected_class_id = 0;
$selected_subject_id = 0;
$selected_session = '';
$selected_exam_type = '';

// Get academic sessions
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();

// Handle report generation
if (isset($_GET['generate']) && $_GET['generate'] == '1') {
    $report_type = $_GET['report_type'] ?? '';
    $selected_class_id = (int)$_GET['class_id'];
    $selected_subject_id = (int)$_GET['subject_id'];
    $selected_session = $_GET['session'] ?? '';
    $selected_exam_type = $_GET['exam_type'] ?? '';
    
    // Validate that teacher has access to this class and subject
    $access_validation = validate_teacher_class_subject_access($teacher_id, $selected_class_id, $selected_subject_id);
    if (!$access_validation['valid']) {
        $error_message = $access_validation['error'];
    } else {
        if ($report_type == 'marksheet') {
            // Generate marksheet report
            $stmt = $pdo->prepare("
                SELECT s.student_id, s.first_name, s.last_name, s.roll_number,
                       r.cq_marks, r.mcq_marks, r.practical_marks, r.assignment_marks, 
                       r.attendance_marks, r.marks_obtained, r.grade,
                       md.cq_marks as total_cq, md.mcq_marks as total_mcq, 
                       md.practical_marks as total_practical, md.assignment_marks as total_assignment,
                       md.attendance_marks as total_attendance, md.total_marks as total_marks
                FROM students s
                INNER JOIN student_subjects ss ON s.id = ss.student_id AND ss.subject_id = ?
                LEFT JOIN (
                    SELECT r1.* FROM results r1
                    INNER JOIN (
                        SELECT student_id, MAX(id) as max_id 
                        FROM results 
                        WHERE subject_id = ? AND session = ? AND exam_type = ?
                        GROUP BY student_id
                    ) r2 ON r1.student_id = r2.student_id AND r1.id = r2.max_id
                ) r ON s.id = r.student_id
                LEFT JOIN mark_distributions md ON md.subject_id = ? AND md.class_id = ? AND md.session = ? AND md.exam_type = ?
                WHERE s.class_id = ? AND s.session = ? AND s.status = 'active'
                ORDER BY s.roll_number, s.first_name
            ");
            $stmt->execute([
                $selected_subject_id, $selected_subject_id, $selected_session, $selected_exam_type,
                $selected_subject_id, $selected_class_id, $selected_session, $selected_exam_type,
                $selected_class_id, $selected_session
            ]);
            $report_data = $stmt->fetchAll();
        } elseif ($report_type == 'tabulation') {
            // Generate tabulation sheet report
            $stmt = $pdo->prepare("
                SELECT s.student_id, s.first_name, s.last_name, s.roll_number,
                       r.cq_marks, r.mcq_marks, r.practical_marks, r.assignment_marks, 
                       r.attendance_marks, r.marks_obtained, r.grade
                FROM students s
                INNER JOIN student_subjects ss ON s.id = ss.student_id AND ss.subject_id = ?
                LEFT JOIN (
                    SELECT r1.* FROM results r1
                    INNER JOIN (
                        SELECT student_id, MAX(id) as max_id 
                        FROM results 
                        WHERE subject_id = ? AND session = ? AND exam_type = ?
                        GROUP BY student_id
                    ) r2 ON r1.student_id = r2.student_id AND r1.id = r2.max_id
                ) r ON s.id = r.student_id
                WHERE s.class_id = ? AND s.session = ? AND s.status = 'active'
                ORDER BY s.roll_number, s.first_name
            ");
            $stmt->execute([
                $selected_subject_id, $selected_subject_id, $selected_session, $selected_exam_type,
                $selected_class_id, $selected_session
            ]);
            $report_data = $stmt->fetchAll();
        }
    }
}
?>

<!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">
    <style>
        .report-card {
            background: #fff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .report-table {
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }
        .grade-a-plus { background-color: #d4edda; }
        .grade-a { background-color: #c3e6cb; }
        .grade-a-minus { background-color: #b2dfdb; }
        .grade-b { background-color: #cce5ff; }
        .grade-c { background-color: #fff3cd; }
        .grade-d { background-color: #ffeaa7; }
        .grade-f { background-color: #f8d7da; }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <h2><i class="fas fa-chart-bar"></i> আমার রিপোর্ট</h2>
                <p class="text-muted">আপনার নির্ধারিত বিষয় ও ক্লাসের জন্য রিপোর্ট দেখুন</p>
            </div>
        </div>

        <!-- Messages -->
        <?php if (isset($error_message)): ?>
            <div class="row">
                <div class="col-12">
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Report Generation Form -->
        <div class="row">
            <div class="col-12">
                <div class="report-card">
                    <form method="GET" class="row g-3">
                        <input type="hidden" name="generate" value="1">
                        
                        <div class="col-md-3">
                            <label for="report_type" class="form-label">রিপোর্টের ধরণ <span class="text-danger">*</span></label>
                            <select class="form-select" id="report_type" name="report_type" required>
                                <option value="">রিপোর্ট নির্বাচন করুন</option>
                                <option value="marksheet" <?php echo (isset($_GET['report_type']) && $_GET['report_type'] == 'marksheet') ? 'selected' : ''; ?>>মার্কশীট</option>
                                <option value="tabulation" <?php echo (isset($_GET['report_type']) && $_GET['report_type'] == 'tabulation') ? 'selected' : ''; ?>>টেবুলেশন শীট</option>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="class_id" class="form-label">ক্লাস <span class="text-danger">*</span></label>
                            <select class="form-select" id="class_id" name="class_id" required>
                                <option value="">ক্লাস নির্বাচন করুন</option>
                                <?php foreach ($assigned_classes as $class): ?>
                                    <option value="<?php echo $class['id']; ?>" 
                                            <?php echo (isset($_GET['class_id']) && $_GET['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="subject_id" class="form-label">বিষয় <span class="text-danger">*</span></label>
                            <select class="form-select" id="subject_id" name="subject_id" required>
                                <option value="">বিষয় নির্বাচন করুন</option>
                                <?php foreach ($assigned_subjects as $subject): ?>
                                    <option value="<?php echo $subject['id']; ?>" 
                                            <?php echo (isset($_GET['subject_id']) && $_GET['subject_id'] == $subject['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="session" class="form-label">সেশন <span class="text-danger">*</span></label>
                            <select class="form-select" id="session" name="session" required>
                                <option value="">সেশন নির্বাচন করুন</option>
                                <?php foreach ($sessions as $sess): ?>
                                    <option value="<?php echo $sess['session_name']; ?>" 
                                            <?php echo (isset($_GET['session']) && $_GET['session'] == $sess['session_name']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($sess['session_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label for="exam_type" class="form-label">পরীক্ষার ধরণ <span class="text-danger">*</span></label>
                            <select class="form-select" id="exam_type" name="exam_type" required>
                                <option value="">পরীক্ষা নির্বাচন করুন</option>
                                <option value="midterm" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'midterm') ? 'selected' : ''; ?>>অর্ধবার্ষিক</option>
                                <option value="final" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'final') ? 'selected' : ''; ?>>বার্ষিক</option>
                                <option value="test" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'test') ? 'selected' : ''; ?>>টেস্ট</option>
                                <option value="assignment" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'assignment') ? 'selected' : ''; ?>>অ্যাসাইনমেন্ট</option>
                                <option value="practical" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'practical') ? 'selected' : ''; ?>>প্র্যাকটিক্যাল</option>
                            </select>
                        </div>
                        
                        <div class="col-md-9 text-end">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-chart-bar"></i> রিপোর্ট তৈরি করুন
                            </button>
                            <a href="dashboard.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরুন
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Marksheet Report -->
        <?php if (!empty($report_data) && $report_type == 'marksheet'): ?>
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5>
                                <i class="fas fa-file-signature"></i> মার্কশীট রিপোর্ট
                                <small class="text-muted">
                                    (ক্লাস: <?php 
                                        foreach ($assigned_classes as $class) {
                                            if ($class['id'] == $selected_class_id) {
                                                echo htmlspecialchars($class['name'] . ' - ' . $class['section']);
                                                break;
                                            }
                                        }
                                    ?>, 
                                    বিষয়: <?php 
                                        foreach ($assigned_subjects as $subject) {
                                            if ($subject['id'] == $selected_subject_id) {
                                                echo htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')');
                                                break;
                                            }
                                        }
                                    ?>, 
                                    সেশন: <?php echo htmlspecialchars($selected_session); ?>, 
                                    পরীক্ষা: <?php echo htmlspecialchars($selected_exam_type); ?>)
                                </small>
                            </h5>
                        </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 class="text-center">CQ</th>
                                            <th class="text-center">MCQ</th>
                                            <th class="text-center">Practical</th>
                                            <th class="text-center">Assignment</th>
                                            <th class="text-center">Attendance</th>
                                            <th class="text-center">Total</th>
                                            <th class="text-center">Grade</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($report_data as $record): ?>
                                            <tr class="<?php 
                                                switch ($record['grade']) {
                                                    case 'A+': echo 'grade-a-plus'; break;
                                                    case 'A': echo 'grade-a'; break;
                                                    case 'A-': echo 'grade-a-minus'; break;
                                                    case 'B': echo 'grade-b'; break;
                                                    case 'C': echo 'grade-c'; break;
                                                    case 'D': echo 'grade-d'; break;
                                                    case 'F': echo 'grade-f'; break;
                                                    default: echo '';
                                                }
                                            ?>">
                                                <td><?php echo htmlspecialchars($record['first_name'] . ' ' . $record['last_name']); ?></td>
                                                <td><?php echo htmlspecialchars($record['roll_number']); ?></td>
                                                <td><?php echo htmlspecialchars($record['student_id']); ?></td>
                                                <td class="text-center"><?php echo $record['cq_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['mcq_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['practical_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['assignment_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['attendance_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['marks_obtained'] ?? '-'; ?></td>
                                                <td class="text-center fw-bold"><?php echo $record['grade'] ?? '-'; ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="row mt-3">
                                <div class="col-12 text-end">
                                    <button class="btn btn-success" onclick="window.print()">
                                        <i class="fas fa-print"></i> প্রিন্ট করুন
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Tabulation Sheet Report -->
        <?php if (!empty($report_data) && $report_type == 'tabulation'): ?>
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5>
                                <i class="fas fa-table"></i> টেবুলেশন শীট রিপোর্ট
                                <small class="text-muted">
                                    (ক্লাস: <?php 
                                        foreach ($assigned_classes as $class) {
                                            if ($class['id'] == $selected_class_id) {
                                                echo htmlspecialchars($class['name'] . ' - ' . $class['section']);
                                                break;
                                            }
                                        }
                                    ?>, 
                                    বিষয়: <?php 
                                        foreach ($assigned_subjects as $subject) {
                                            if ($subject['id'] == $selected_subject_id) {
                                                echo htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')');
                                                break;
                                            }
                                        }
                                    ?>, 
                                    সেশন: <?php echo htmlspecialchars($selected_session); ?>, 
                                    পরীক্ষা: <?php echo htmlspecialchars($selected_exam_type); ?>)
                                </small>
                            </h5>
                        </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 class="text-center">CQ</th>
                                            <th class="text-center">MCQ</th>
                                            <th class="text-center">Practical</th>
                                            <th class="text-center">Assignment</th>
                                            <th class="text-center">Attendance</th>
                                            <th class="text-center">Total</th>
                                            <th class="text-center">Grade</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($report_data as $record): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($record['first_name'] . ' ' . $record['last_name']); ?></td>
                                                <td><?php echo htmlspecialchars($record['roll_number']); ?></td>
                                                <td><?php echo htmlspecialchars($record['student_id']); ?></td>
                                                <td class="text-center"><?php echo $record['cq_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['mcq_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['practical_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['assignment_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['attendance_marks'] ?? '-'; ?></td>
                                                <td class="text-center"><?php echo $record['marks_obtained'] ?? '-'; ?></td>
                                                <td class="text-center fw-bold"><?php echo $record['grade'] ?? '-'; ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="row mt-3">
                                <div class="col-12 text-end">
                                    <button class="btn btn-success" onclick="window.print()">
                                        <i class="fas fa-print"></i> প্রিন্ট করুন
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>