<?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
$student_id = $_GET['student_id'] ?? '';
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? '';

$student = null;
$results = [];
$subjects = [];
$merit_position = null;

if ($student_id && $session && $exam_type) {
    // Get student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section 
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if ($student) {
        // Get results for the student
        $stmt = $pdo->prepare("
            SELECT r.*, sub.name as subject_name
            FROM results r
            LEFT JOIN subjects sub ON r.subject_id = sub.id
            WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
            ORDER BY sub.name
        ");
        $stmt->execute([$student_id, $session, $exam_type]);
        $results = $stmt->fetchAll();
        
        // Calculate totals
        $total_marks = 0;
        $total_obtained = 0;
        $total_subjects = count($results);
        $passed_subjects = 0;
        
        foreach ($results as $result) {
            $total_marks += 100; // Assuming 100 marks per subject
            $total_obtained += $result['marks_obtained'];
            if ($result['grade'] != 'F') {
                $passed_subjects++;
            }
        }
        
        $percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;
        $overall_grade = calculateOverallGrade($percentage, $passed_subjects, $total_subjects);
        
        // Calculate merit position
        if ($student && $session && $exam_type) {
            // Get all students in the same class with their total marks
            $stmt = $pdo->prepare("
                SELECT s.id, s.first_name, s.last_name, s.roll_number,
                       SUM(r.marks_obtained) as total_obtained
                FROM students s
                JOIN results r ON s.id = r.student_id
                WHERE s.class_id = ? AND r.session = ? AND r.exam_type = ?
                GROUP BY s.id, s.first_name, s.last_name, s.roll_number
                ORDER BY total_obtained DESC
            ");
            $stmt->execute([$student['class_id'], $session, $exam_type]);
            $class_results = $stmt->fetchAll();
            
            // Find the position of current student
            $position = 1;
            foreach ($class_results as $class_result) {
                if ($class_result['id'] == $student_id) {
                    $merit_position = $position;
                    break;
                }
                $position++;
            }
        }
    }
}

function calculateOverallGrade($percentage, $passed_subjects, $total_subjects) {
    // If failed in any subject, overall grade is F
    if ($passed_subjects < $total_subjects) {
        return 'F';
    }
    
    if ($percentage >= 80) return 'A+';
    elseif ($percentage >= 70) return 'A';
    elseif ($percentage >= 60) return 'A-';
    elseif ($percentage >= 50) return 'B';
    elseif ($percentage >= 40) return 'C';
    elseif ($percentage >= 33) return 'D';
    else return 'F';
}

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;
        default: return 0.00;
    }
}

// Get all students for dropdown
$stmt = $pdo->query("
    SELECT s.id, s.student_id, s.first_name, s.last_name, c.name as class_name 
    FROM students s 
    JOIN classes c ON s.class_id = c.id 
    WHERE s.status = 'active'
    ORDER BY c.name, s.first_name, s.last_name
");
$all_students = $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();
?>

<!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">
    <style>
        .marksheet {
            border: 2px solid #000;
            padding: 20px;
            margin: 20px 0;
            background: white;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        
        .school-logo {
            width: 80px;
            height: 80px;
            border: 2px solid #000;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 10px;
            font-size: 24px;
            background: #f8f9fa;
        }
        
        .student-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 8px;
        }
        
        .info-label {
            font-weight: bold;
            min-width: 120px;
        }
        
        .info-value {
            border-bottom: 1px solid #000;
            flex: 1;
            padding-left: 10px;
        }
        
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .marks-table th,
        .marks-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
        }
        
        .marks-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        
        .result-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #000;
        }
        
        .signature-section {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 30px;
            margin-top: 40px;
            text-align: center;
        }
        
        .signature-box {
            border-top: 1px solid #000;
            padding-top: 10px;
            margin-top: 50px;
        }
        
        .grade-scale {
            font-size: 10px;
            margin-top: 20px;
        }
        
        @media print {
            .no-print { display: none !important; }
            .container-fluid { max-width: 100% !important; }
            body { font-size: 12px; }
            .marksheet { page-break-inside: avoid; }
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <?php if ($student_id && $session && $exam_type): ?>
        <div class="text-center mb-3 no-print">
            <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
        </div>
        
        <div class="marksheet">
            <div class="school-header">
                <div class="school-logo">
                    <i class="fas fa-graduation-cap"></i>
                </div>
                <h3>কুড়ুলগাছি মাধ্যমিক বিদ্যালয়</h3>
                <p>দামুড়হুদা, চুয়াডাঙ্গা, বাংলাদেশ</p>
                <h4>একাডেমিক ট্রান্সক্রিপ্ট</h4>
            </div>
            
            <div class="student-info">
                <div>
                    <div class="info-row">
                        <div class="info-label">শিক্ষার্থী আইডি</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['student_id']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পিতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['father_name'] ?? ''); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মাতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['mother_name'] ?? ''); ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">রোল নম্বর</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['roll_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শ্রেণী</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">সেশন</div>
                        <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পরীক্ষার ধরন</div>
                        <div class="info-value"><?php echo htmlspecialchars(ucfirst($exam_type)); ?></div>
                    </div>
                </div>
            </div>
            
            <table class="marks-table">
                <thead>
                    <tr>
                        <th>বিষয়</th>
                        <th>পূর্ণ নম্বর</th>
                        <th>পাস নম্বর</th>
                        <th>প্রাপ্ত নম্বর</th>
                        <th>গ্রেড</th>
                        <th>পয়েন্ট</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $result): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($result['subject_name']); ?></td>
                        <td>100</td>
                        <td>40</td>
                        <td><?php echo htmlspecialchars($result['marks_obtained']); ?></td>
                        <td><?php echo htmlspecialchars($result['grade']); ?></td>
                        <td><?php echo number_format(getGradePoint($result['grade']), 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর</div>
                        <div class="info-value"><?php echo $total_obtained; ?>/<?php echo $total_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ</div>
                        <div class="info-value"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value"><?php echo $overall_grade; ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">পয়েন্ট</div>
                        <div class="info-value"><?php echo number_format(getGradePoint($overall_grade), 2); ?></div>
                    </div>
                    <?php if ($merit_position): ?>
                    <div class="info-row">
                        <div class="info-label">মেরিট পজিশন</div>
                        <div class="info-value"><?php echo $merit_position; ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="grade-scale">
                <strong>গ্রেড স্কেল:</strong> A+ (80-100), A (70-79), A- (60-69), B (50-59), C (40-49), D (33-39), F (0-32)
            </div>
            
            <div class="signature-section">
                <div>
                    <div class="signature-box">শিক্ষার্থীর স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box">শিক্ষকের স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box">অধ্যাপকের স্বাক্ষর</div>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">মার্কশীট অনুসন্ধান করুন</h4>
            </div>
            <div class="card-body">
                <form method="GET" action="" class="row g-3">
                    <div class="col-md-4">
                        <label for="student_id" class="form-label">শিক্ষার্থী</label>
                        <select id="student_id" name="student_id" class="form-select" required>
                            <option value="">শিক্ষার্থী নির্বাচন করুন</option>
                            <?php foreach ($all_students as $student_item): ?>
                                <option value="<?php echo htmlspecialchars($student_item['id']); ?>">
                                    <?php echo htmlspecialchars($student_item['first_name'] . ' ' . $student_item['last_name'] . ' (' . $student_item['class_name'] . ')'); ?>
                                </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 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 htmlspecialchars($exam_type_item['exam_type']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary d-block w-100">
                            <i class="fas fa-search"></i> দেখুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>