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

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

// Get search parameters
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? '';

$show_results = false;
$students_data = [];
$class_name = '';

// Get classes for dropdown
$stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
$classes = $stmt->fetchAll();

// Get available sessions
$stmt = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC");
$sessions = $stmt->fetchAll();

// Get available exam types
$stmt = $pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type");
$exam_types = $stmt->fetchAll();

if ($class_id && $session && $exam_type) {
    $show_results = true;
    
    // Get class name for display
    $stmt = $pdo->prepare("SELECT name, section FROM classes WHERE id = ?");
    $stmt->execute([$class_id]);
    $class_info = $stmt->fetch();
    $class_name = $class_info ? $class_info['name'] . ' ' . $class_info['section'] : '';
    
    // Get all students in this class
    $stmt = $pdo->prepare(
        "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
        FROM students s
        WHERE s.class_id = ? AND s.status = 'active'
        ORDER BY s.roll_number, s.first_name, s.last_name"
    );
    $stmt->execute([$class_id]);
    $students = $stmt->fetchAll();
    
    // For each student, calculate their GPA with 4th subject rules
    foreach ($students as $student) {
        $student_id = $student['id'];
        
        // Get all subjects for this student in this class/session/exam
        $stmt = $pdo->prepare(
            "SELECT r.*, s.name as subject_name, ss.is_fourth_subject
            FROM results r
            JOIN subjects s ON r.subject_id = s.id
            JOIN student_subjects ss ON r.subject_id = ss.subject_id AND r.student_id = ss.student_id
            WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
            ORDER BY s.name"
        );
        $stmt->execute([$student_id, $session, $exam_type]);
        $results = $stmt->fetchAll();
        
        // Separate main subjects and 4th subject
        $main_subjects = [];
        $fourth_subject = null;
        $total_grade_points = 0;
        $main_subject_count = 0;
        
        foreach ($results as $result) {
            if (!empty($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                $fourth_subject = $result;
            } else {
                $main_subjects[] = $result;
                $main_subject_count++;
            }
        }
        
        // Calculate GPA for main subjects
        $main_subject_gpa = 0;
        if ($main_subject_count > 0) {
            foreach ($main_subjects as $subject) {
                $grade_point = getGradePoint($subject['grade']);
                $total_grade_points += $grade_point;
            }
            $main_subject_gpa = $total_grade_points / $main_subject_count;
        }
        
        // Apply 4th subject rules
        $final_gpa = $main_subject_gpa;
        $fourth_subject_contribution = 0;
        
        if ($fourth_subject) {
            $fourth_subject_point = getGradePoint($fourth_subject['grade']);
            
            // If 4th subject point is <= 2.00, add 0 points
            // If 4th subject point is > 2.00, add (point - 2.00) points
            if ($fourth_subject_point > 2.00) {
                $fourth_subject_contribution = $fourth_subject_point - 2.00;
                $final_gpa = $main_subject_gpa + $fourth_subject_contribution;
                
                // Ensure GPA doesn't exceed 5.00
                if ($final_gpa > 5.00) {
                    $final_gpa = 5.00;
                }
            }
        }
        
        // Determine pass/fail status
        $is_passed = true;
        $failed_subjects = [];
        
        // Check if student failed in any main subject
        foreach ($main_subjects as $subject) {
            if ($subject['grade'] == 'F') {
                $is_passed = false;
                $failed_subjects[] = $subject['subject_name'];
            }
        }
        
        // If student has 4th subject, check if they failed in it
        if ($fourth_subject && $fourth_subject['grade'] == 'F') {
            $failed_subjects[] = $fourth_subject['subject_name'] . ' (৪র্থ বিষয়)';
        }
        
        // Add to students data
        $students_data[] = [
            'id' => $student['id'],
            'student_id' => $student['student_id'],
            'first_name' => $student['first_name'],
            'last_name' => $student['last_name'],
            'roll_number' => $student['roll_number'],
            'main_subjects' => $main_subjects,
            'fourth_subject' => $fourth_subject,
            'main_subject_gpa' => $main_subject_gpa,
            'fourth_subject_contribution' => $fourth_subject_contribution,
            'final_gpa' => $final_gpa,
            'is_passed' => $is_passed,
            'failed_subjects' => $failed_subjects
        ];
    }
}

// Function to convert grade to grade point
function getGradePoint($grade) {
    switch ($grade) {
        case 'A+': return 5.00;
        case 'A': return 4.00;
        case 'A-': return 3.50;
        case 'B': return 3.00;
        case 'C': return 2.00;
        case 'D': return 1.00;
        case 'F': return 0.00;
        default: return 0.00;
    }
}
?>

<!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="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        
        .report-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            margin-bottom: 25px;
            overflow: hidden;
        }
        
        .report-header {
            background: linear-gradient(135deg, #0d6efd 0%, #0b5ed7 100%);
            color: white;
            padding: 25px;
            text-align: center;
        }
        
        .search-panel {
            background: #e9ecef;
            padding: 25px;
            border-radius: 8px;
            margin-bottom: 25px;
        }
        
        .student-row.passed {
            background-color: #d4edda;
        }
        
        .student-row.failed {
            background-color: #f8d7da;
        }
        
        .gpa-badge {
            font-size: 1.1rem;
            font-weight: 700;
        }
        
        .passed-badge {
            background-color: #198754;
            color: white;
        }
        
        .failed-badge {
            background-color: #dc3545;
            color: white;
        }
        
        .print-header {
            display: none;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .print-header {
                display: block;
                text-align: center;
                margin-bottom: 20px;
            }
            
            .report-card {
                box-shadow: none;
                border: 1px solid #000;
            }
            
            .report-header {
                background: #0d6efd !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .student-row.passed {
                background-color: #d4edda !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .student-row.failed {
                background-color: #f8d7da !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <!-- Print Header -->
        <div class="print-header">
            <h2>৪র্থ বিষয় সহ ফলাফল</h2>
            <p><?php echo $show_results ? htmlspecialchars($class_name) . " - " . htmlspecialchars($session) . " (" . htmlspecialchars(ucfirst($exam_type)) . ")" : ""; ?></p>
        </div>
        
        <div class="report-card">
            <div class="report-header">
                <h1><i class="fas fa-graduation-cap"></i> ৪র্থ বিষয় সহ ফলাফল</h1>
                <p class="mb-0">৪র্থ বিষয়ের পয়েন্ট অনুযায়ী জিপিএ হিসাব</p>
            </div>
            
            <div class="container">
                <div class="text-center mb-4 no-print">
                    <button onclick="window.print()" class="btn btn-success btn-lg">
                        <i class="fas fa-print"></i> প্রিন্ট করুন
                    </button>
                    <a href="index.php" class="btn btn-primary btn-lg">
                        <i class="fas fa-arrow-left"></i> রিপোর্ট ড্যাশবোর্ড
                    </a>
                </div>
                
                <div class="search-panel no-print">
                    <h4 class="mb-4"><i class="fas fa-filter"></i> ফিল্টার করুন</h4>
                    <form method="GET" action="" class="row g-3">
                        <div class="col-md-4">
                            <label for="class_id" class="form-label">শ্রেণী</label>
                            <select id="class_id" name="class_id" class="form-select" required>
                                <option value="">শ্রেণী নির্বাচন করুন</option>
                                <?php foreach ($classes as $class): ?>
                                    <option value="<?php echo htmlspecialchars($class['id']); ?>" <?php echo $class_id == $class['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($class['name'] . ' ' . $class['section']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="session" class="form-label">সেশন</label>
                            <select id="session" name="session" class="form-select" required>
                                <option value="">সেশন নির্বাচন করুন</option>
                                <?php foreach ($sessions as $session_item): ?>
                                    <option value="<?php echo htmlspecialchars($session_item['session']); ?>" <?php echo $session == $session_item['session'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($session_item['session']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="exam_type" class="form-label">পরীক্ষার ধরন</label>
                            <select id="exam_type" name="exam_type" class="form-select" required>
                                <option value="">পরীক্ষা নির্বাচন করুন</option>
                                <?php foreach ($exam_types as $exam_type_item): ?>
                                    <option value="<?php echo htmlspecialchars($exam_type_item['exam_type']); ?>" <?php echo $exam_type == $exam_type_item['exam_type'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars(ucfirst($exam_type_item['exam_type'])); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-search"></i> দেখুন
                            </button>
                        </div>
                    </form>
                </div>
                
                <?php if ($show_results): ?>
                    <div class="mb-4">
                        <h3 class="text-center mb-4">
                            <?php echo htmlspecialchars($class_name); ?> - <?php echo htmlspecialchars($session); ?> (<?php echo htmlspecialchars(ucfirst($exam_type)); ?>)
                        </h3>
                        
                        <?php if (!empty($students_data)): ?>
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead class="table-primary">
                                        <tr>
                                            <th>রোল নম্বর</th>
                                            <th>শিক্ষার্থী আইডি</th>
                                            <th>নাম</th>
                                            <th>প্রধান বিষয়সমূহ (জিপিএ)</th>
                                            <th>৪র্থ বিষয়</th>
                                            <th>৪র্থ বিষয় অবদান</th>
                                            <th>চূড়ান্ত জিপিএ</th>
                                            <th>ফলাফল</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($students_data as $student): ?>
                                            <tr class="student-row <?php echo $student['is_passed'] ? 'passed' : 'failed'; ?>">
                                                <td class="text-center"><?php echo htmlspecialchars($student['roll_number']); ?></td>
                                                <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                                <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                                <td>
                                                    <div>
                                                        <?php foreach ($student['main_subjects'] as $subject): ?>
                                                            <div>
                                                                <?php echo htmlspecialchars($subject['subject_name']); ?>: 
                                                                <strong><?php echo htmlspecialchars($subject['grade']); ?></strong>
                                                                (<?php echo number_format(getGradePoint($subject['grade']), 2); ?>)
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                    <div class="mt-2">
                                                        <strong>প্রধান বিষয় জিপিএ: <?php echo number_format($student['main_subject_gpa'], 2); ?></strong>
                                                    </div>
                                                </td>
                                                <td>
                                                    <?php if ($student['fourth_subject']): ?>
                                                        <?php echo htmlspecialchars($student['fourth_subject']['subject_name']); ?>: 
                                                        <strong><?php echo htmlspecialchars($student['fourth_subject']['grade']); ?></strong>
                                                        (<?php echo number_format(getGradePoint($student['fourth_subject']['grade']), 2); ?>)
                                                    <?php else: ?>
                                                        <em>৪র্থ বিষয় নেই</em>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="text-center">
                                                    <?php if ($student['fourth_subject']): ?>
                                                        <?php if ($student['fourth_subject_contribution'] > 0): ?>
                                                            <span class="badge bg-success">+<?php echo number_format($student['fourth_subject_contribution'], 2); ?></span>
                                                        <?php else: ?>
                                                            <span class="badge bg-secondary">0.00</span>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary">N/A</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="text-center">
                                                    <span class="gpa-badge"><?php echo number_format($student['final_gpa'], 2); ?></span>
                                                </td>
                                                <td class="text-center">
                                                    <?php if ($student['is_passed']): ?>
                                                        <span class="badge passed-badge">পাশ</span>
                                                    <?php else: ?>
                                                        <span class="badge failed-badge">ফেল</span>
                                                        <?php if (!empty($student['failed_subjects'])): ?>
                                                            <div class="mt-1 small text-muted">
                                                                ফেল বিষয়: <?php echo implode(', ', array_map('htmlspecialchars', $student['failed_subjects'])); ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Summary Statistics -->
                            <div class="row mt-4">
                                <div class="col-md-4">
                                    <div class="card text-white bg-success">
                                        <div class="card-body">
                                            <h5 class="card-title"><i class="fas fa-user-graduate"></i> পাশ করেছে</h5>
                                            <h2>
                                                <?php 
                                                $passed_count = count(array_filter($students_data, function($student) { return $student['is_passed']; }));
                                                echo $passed_count;
                                                ?>
                                            </h2>
                                            <p class="mb-0">মোট ছাত্র-ছাত্রী: <?php echo count($students_data); ?></p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card text-white bg-danger">
                                        <div class="card-body">
                                            <h5 class="card-title"><i class="fas fa-exclamation-triangle"></i> ফেল করেছে</h5>
                                            <h2>
                                                <?php 
                                                $failed_count = count(array_filter($students_data, function($student) { return !$student['is_passed']; }));
                                                echo $failed_count;
                                                ?>
                                            </h2>
                                            <p class="mb-0">মোট ছাত্র-ছাত্রী: <?php echo count($students_data); ?></p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card text-white bg-primary">
                                        <div class="card-body">
                                            <h5 class="card-title"><i class="fas fa-percentage"></i> গড় জিপিএ</h5>
                                            <h2>
                                                <?php 
                                                $total_gpa = array_sum(array_column($students_data, 'final_gpa'));
                                                $average_gpa = count($students_data) > 0 ? $total_gpa / count($students_data) : 0;
                                                echo number_format($average_gpa, 2);
                                                ?>
                                            </h2>
                                            <p class="mb-0">সর্বোচ্চ জিপিএ: 5.00</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info text-center">
                                <i class="fas fa-info-circle"></i> এই শ্রেণী, সেশন এবং পরীক্ষার জন্য কোন ডেটা পাওয়া যায়নি।
                            </div>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="alert alert-info text-center">
                        <i class="fas fa-info-circle"></i> ফিল্টার নির্বাচন করে রিপোর্ট দেখুন
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

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