<?php
/**
 * Parent Portal - Student Results
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in as parent
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'parent') {
    header('Location: ../parent_login.php');
    exit;
}

// Get parent information
$stmt = $pdo->prepare("SELECT * FROM parents WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$parent = $stmt->fetch();

if (!$parent) {
    header('Location: ../parent_register.php');
    exit;
}

// Get associated students
try {
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name
        FROM students s
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE s.id IN (
            SELECT student_id FROM parent_students WHERE parent_id = ?
        ) AND s.status = 'active'
    ");
    $stmt->execute([$parent['id']]);
    $students = $stmt->fetchAll();
} catch (Exception $e) {
    $students = [];
}

// Get selected student
$selected_student_id = $_GET['student_id'] ?? ($students[0]['id'] ?? null);

// Get results for selected student
$results = [];
if ($selected_student_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT r.*, sub.name as subject_name, sub.code as subject_code
            FROM results r
            JOIN subjects sub ON r.subject_id = sub.id
            WHERE r.student_id = ?
            ORDER BY r.exam_date DESC, sub.name
        ");
        $stmt->execute([$selected_student_id]);
        $results = $stmt->fetchAll();
    } catch (Exception $e) {
        $results = [];
    }
}
?>

<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .parent-sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }
        .parent-sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 15px 20px;
            border-radius: 8px;
            margin: 5px 0;
            text-decoration: none;
            display: block;
        }
        .parent-sidebar .nav-link:hover, .parent-sidebar .nav-link.active {
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .result-card {
            border-left: 4px solid #28a745;
        }
        .grade-a { background-color: #d4edda; border-color: #28a745; }
        .grade-b { background-color: #cce5ff; border-color: #007bff; }
        .grade-c { background-color: #fff3cd; border-color: #ffc107; }
        .grade-d { background-color: #f8d7da; border-color: #dc3545; }
        .grade-f { background-color: #f8d7da; border-color: #dc3545; }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Parent Sidebar -->
            <nav class="col-md-2 d-none d-md-block parent-sidebar p-3">
                <div class="text-center mb-4">
                    <div class="bg-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width:80px;height:80px;">
                        <i class="fas fa-user-tie fa-2x text-primary"></i>
                    </div>
                    <h6 class="mb-0"><?= htmlspecialchars($parent['father_name']) ?></h6>
                    <small>অভিভাবক</small>
                </div>
                
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">
                            <i class="fas fa-home me-2"></i> ড্যাশবোর্ড
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="results.php">
                            <i class="fas fa-chart-line me-2"></i> ফলাফল
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="subjects.php">
                            <i class="fas fa-book me-2"></i> বিষয়সমূহ
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="fees.php">
                            <i class="fas fa-money-bill-wave me-2"></i> ফি পেমেন্ট
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="events.php">
                            <i class="fas fa-calendar-alt me-2"></i> ইভেন্ট
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="attendance.php">
                            <i class="fas fa-clipboard-check me-2"></i> উপস্থিতি
                        </a>
                    </li>
                    <li class="nav-item mt-4">
                        <a class="nav-link text-warning" href="../parent_logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> লগআউট
                        </a>
                    </li>
                </ul>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-10 ms-sm-auto px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-chart-line text-success"></i> শিক্ষার্থীর ফলাফল</h2>
                    <div class="text-muted">
                        <?= date('l, d F Y', strtotime('now')) ?>
                    </div>
                </div>
                
                <?php if (count($students) > 0): ?>
                <!-- Student Selection -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-filter"></i> শিক্ষার্থী নির্বাচন করুন</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET">
                            <div class="row">
                                <div class="col-md-6">
                                    <select name="student_id" class="form-select" onchange="this.form.submit()">
                                        <?php foreach ($students as $student): ?>
                                            <option value="<?= $student['id'] ?>" <?= $selected_student_id == $student['id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?> - 
                                                <?= htmlspecialchars($student['class_name'] ?? 'N/A') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if ($selected_student_id && count($results) > 0): ?>
                <!-- Results Table -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-clipboard-list"></i> পরীক্ষার ফলাফল</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>পূর্ণ নম্বর</th>
                                        <th>গ্রেড</th>
                                        <th>পাস মার্ক</th>
                                        <th>তারিখ</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($results as $result): 
                                        $percentage = $result['total_marks'] > 0 ? ($result['marks_obtained'] / $result['total_marks']) * 100 : 0;
                                        $grade_class = 'grade-f';
                                        if ($percentage >= 80) $grade_class = 'grade-a';
                                        elseif ($percentage >= 70) $grade_class = 'grade-b';
                                        elseif ($percentage >= 60) $grade_class = 'grade-c';
                                        elseif ($percentage >= 50) $grade_class = 'grade-d';
                                    ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($result['subject_name']) ?></strong><br>
                                            <small class="text-muted">কোড: <?= htmlspecialchars($result['subject_code']) ?></small>
                                        </td>
                                        <td><?= htmlspecialchars($result['exam_type']) ?></td>
                                        <td>
                                            <span class="badge bg-primary"><?= $result['marks_obtained'] ?></span>
                                        </td>
                                        <td><?= $result['total_marks'] ?></td>
                                        <td>
                                            <span class="badge <?= $grade_class ?>"><?= htmlspecialchars($result['grade'] ?? 'N/A') ?></span>
                                        </td>
                                        <td><?= $result['pass_marks'] ?? 'N/A' ?></td>
                                        <td><?= date('d-m-Y', strtotime($result['exam_date'])) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Statistics Summary -->
                <div class="row mt-4">
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-primary"><?= count($results) ?></h3>
                                <p class="text-muted mb-0">মোট বিষয়</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-success">
                                    <?= count(array_filter($results, function($r) { return $r['grade'] == 'A' || $r['grade'] == 'A+'; })) ?>
                                </h3>
                                <p class="text-muted mb-0">এ গ্রেড</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-warning">
                                    <?= count(array_filter($results, function($r) { return $r['marks_obtained'] >= ($r['pass_marks'] ?? 0); })) ?>
                                </h3>
                                <p class="text-muted mb-0">পাশকৃত</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-info">
                                    <?php 
                                        $avg_percentage = count($results) > 0 ? 
                                            array_sum(array_map(function($r) { 
                                                return $r['total_marks'] > 0 ? ($r['marks_obtained'] / $r['total_marks']) * 100 : 0; 
                                            }, $results)) / count($results) : 0;
                                        echo round($avg_percentage, 1) . '%';
                                    ?>
                                </h3>
                                <p class="text-muted mb-0">গড় পারসেন্টেজ</p>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="alert alert-info">
                    <h5><i class="fas fa-info-circle"></i> ফলাফল পাওয়া যায়নি</h5>
                    <p>এখনও কোনো ফলাফল প্রকাশিত হয়নি বা তথ্য আপডেট করা হয়নি।</p>
                </div>
                <?php endif; ?>
                
                <?php else: ?>
                <div class="alert alert-info">
                    <h5><i class="fas fa-info-circle"></i> কোনো শিক্ষার্থী খুঁজে পাওয়া যায়নি</h5>
                    <p>সিস্টেমে আপনার শিক্ষার্থীর একাউন্ট অ্যাকটিভ করতে স্কুল অফিসে যোগাযোগ করুন।</p>
                </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>