<?php 
// Advanced Configuration
ini_set('display_errors', 1); error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
require_once 'db_connect.php';

// ==========================================
// 🛠️ DATABASE AUTO-PATCHER: Missing Tables
// ==========================================
try {
    // ১. টিচার ফিডব্যাক টেবিল
    $pdo->exec("CREATE TABLE IF NOT EXISTS `teacher_feedback` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `student_id` int(11) NOT NULL,
        `teacher_name` varchar(100) NOT NULL,
        `subject` varchar(100) NOT NULL,
        `comment` text NOT NULL,
        `rating` int(1) DEFAULT 5,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // ২. রেজাল্ট টেবিল
    $pdo->exec("CREATE TABLE IF NOT EXISTS `exam_results` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `student_id` int(11) NOT NULL,
        `exam_id` int(11) NOT NULL,
        `score` int(11) NOT NULL,
        `total_marks` int(11) DEFAULT 100,
        `status` varchar(50) DEFAULT 'Published',
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // ৩. এটেনডেন্স টেবিল
    $pdo->exec("CREATE TABLE IF NOT EXISTS `attendance` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `student_id` int(11) NOT NULL,
        `course_id` int(11) NOT NULL,
        `status` enum('present','absent') NOT NULL,
        `attendance_date` date NOT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(PDOException $e) {}

include 'includes/user_header.php'; 
if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 

$student_id = $_SESSION['student_id'] ?? null;
if (!$student_id) { echo "<script>window.location.href='login.php';</script>"; exit; }

// ==========================================
// ⚙️ REAL-TIME PERFORMANCE CALCULATIONS
// ==========================================

// 1. Fetch Student Info
$student = $pdo->query("SELECT name FROM students WHERE id = $student_id")->fetch();

// 2. Attendance Calculation
$att_stmt = $pdo->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN status='present' THEN 1 ELSE 0 END) as present FROM attendance WHERE student_id = ?");
$att_stmt->execute([$student_id]);
$att_data = $att_stmt->fetch();
$attendance_rate = ($att_data['total'] > 0) ? round(($att_data['present'] / $att_data['total']) * 100) : 0;

// 3. Exam Average
$exam_stmt = $pdo->prepare("SELECT AVG(score) as avg_score FROM exam_results WHERE student_id = ?");
$exam_stmt->execute([$student_id]);
$avg_marks = round($exam_stmt->fetch()['avg_score'] ?? 0);

// 4. Assignment Progress (Based on enrolled courses)
$assign_total = $pdo->query("SELECT COUNT(*) FROM assignments WHERE course_id IN (SELECT course_id FROM enrollments WHERE student_id = $student_id)")->fetchColumn();
$assign_done = $pdo->query("SELECT COUNT(*) FROM assignment_submissions WHERE student_id = $student_id")->fetchColumn();

// 5. Grade Logic
if($avg_marks >= 80) $overall_grade = "A+";
elseif($avg_marks >= 70) $overall_grade = "A";
elseif($avg_marks >= 60) $overall_grade = "B";
else $overall_grade = "C";

// 6. Chart Data (Last 5 Exam Results)
$chart_exams = $pdo->prepare("SELECT id, score FROM exam_results WHERE student_id = ? ORDER BY id DESC LIMIT 5");
$chart_exams->execute([$student_id]);
$exam_history = array_reverse($chart_exams->fetchAll(PDO::FETCH_ASSOC));

$labels = []; $scores = [];
foreach($exam_history as $row) {
    $labels[] = "Test-" . $row['id'];
    $scores[] = $row['score'];
}

// 7. Teacher Feedback
$feedback_stmt = $pdo->prepare("SELECT * FROM teacher_feedback WHERE student_id = ? ORDER BY id DESC LIMIT 3");
$feedback_stmt->execute([$student_id]);
$teacher_comments = $feedback_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    :root { --primary: #064e3b; --accent: #d4af37; --bg: #f8fafc; }
    .main-content { background-color: var(--bg); min-height: 100vh; padding-bottom: 50px; }
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    /* Summary Stats */
    .stat-card { background: #fff; border-radius: 20px; padding: 25px; border: 1px solid #e2e8f0; text-align: center; transition: 0.3s; box-shadow: 0 10px 30px rgba(0,0,0,0.02); }
    .stat-card:hover { transform: translateY(-5px); border-color: var(--primary); box-shadow: 0 15px 35px rgba(6, 78, 59, 0.08); }
    .stat-label { font-size: 11px; font-weight: 800; text-transform: uppercase; color: #64748b; letter-spacing: 1px; margin-bottom: 10px; }
    .stat-value { font-size: 32px; font-weight: 900; color: var(--primary); margin: 0; }

    .grade-badge-lg { background: linear-gradient(135deg, var(--accent) 0%, #b49124 100%); color: #fff; width: 65px; height: 65px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 26px; font-weight: 900; margin: 0 auto; box-shadow: 0 10px 20px rgba(212, 175, 55, 0.3); }

    /* Feedback Cards */
    .feedback-item { background: #fff; border-radius: 18px; padding: 20px; margin-bottom: 15px; border-left: 6px solid var(--accent); box-shadow: 0 5px 15px rgba(0,0,0,0.02); }
    .stars-color { color: var(--accent); font-size: 12px; }

    .btn-export { background: #ef4444; color: white; border-radius: 12px; padding: 12px 25px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; box-shadow: 0 8px 20px rgba(239, 68, 68, 0.2); text-decoration: none; }
    .btn-export:hover { background: #dc2626; color: white; transform: translateY(-2px); }

    #sidebarToggle { display: none; }
    @media (max-width: 991.98px) {
        #sidebarToggle { display: inline-flex; align-items: center; justify-content: center; width: 42px; height: 42px; background: #fff; border: 1px solid #ddd; border-radius: 10px; margin-right: 15px; cursor: pointer; color: var(--primary); }
    }

    @media print {
        .sidebar, .top-header, .btn-export, #sidebarToggle, .no-print { display: none !important; }
        .main-content { margin: 0 !important; padding: 0 !important; }
        .stat-card { border: 1px solid #eee !important; box-shadow: none !important; }
    }
</style>

<div class="main-content p-3 p-md-5">
    
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-5 fade-up">
        <div class="d-flex align-items-center">
            <div>
                <h2 class="fw-bold text-dark mb-1">Success Report</h2>
                <p class="text-muted fw-semibold mb-0">Analytics for <b><?= htmlspecialchars($student['name'] ?? 'Student') ?></b></p>
            </div>
        </div>
        <div class="mt-3 mt-md-0 no-print">
            <button onclick="window.print()" class="btn-export">
                <i class="fas fa-file-pdf me-2"></i> DOWNLOAD PDF
            </button>
        </div>
    </div>

    <div class="row g-4 mb-5 fade-up" style="animation-delay: 0.1s;">
        <div class="col-6 col-md-3">
            <div class="stat-card">
                <p class="stat-label">Avg. Marks</p>
                <h2 class="stat-value"><?= $avg_marks ?>%</h2>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-card">
                <p class="stat-label">Attendance</p>
                <h2 class="stat-value text-success"><?= $attendance_rate ?>%</h2>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-card">
                <p class="stat-label">Homework</p>
                <h2 class="stat-value text-info"><?= $assign_done ?>/<?= $assign_total ?></h2>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-card">
                <p class="stat-label">Ranking Grade</p>
                <div class="grade-badge-lg"><?= $overall_grade ?></div>
            </div>
        </div>
    </div>

    <div class="row g-4 fade-up" style="animation-delay: 0.2s;">
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm p-4" style="border-radius: 24px;">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold m-0"><i class="fas fa-chart-line text-primary me-2"></i> Exam Performance Trend</h5>
                    <span class="badge bg-light text-muted border px-3 py-2 rounded-pill small">Last 5 Exams</span>
                </div>
                <div style="height: 300px;">
                    <canvas id="progressChart"></canvas>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card border-0 shadow-sm p-4" style="border-radius: 24px; height: 100%;">
                <h5 class="fw-bold mb-4"><i class="fas fa-quote-left text-warning me-2"></i> Teacher's Mentorship</h5>
                
                <?php if(!empty($teacher_comments)): foreach($teacher_comments as $feedback): ?>
                    <div class="feedback-item">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-bold small text-dark"><?= htmlspecialchars($feedback['teacher_name']) ?></span>
                            <div class="stars-color">
                                <?php for($i=0; $i<$feedback['rating']; $i++) echo '<i class="fas fa-star"></i>'; ?>
                            </div>
                        </div>
                        <span class="badge bg-light text-primary border mb-3" style="font-size: 9px;"><?= htmlspecialchars($feedback['subject']) ?></span>
                        <p class="text-muted mb-2" style="font-size: 13px; line-height: 1.6; font-style: italic;">"<?= htmlspecialchars($feedback['comment']) ?>"</p>
                        <div class="text-end">
                            <small class="text-muted" style="font-size: 9px; font-weight: 700;"><?= date('d M Y', strtotime($feedback['created_at'])) ?></small>
                        </div>
                    </div>
                <?php endforeach; else: ?>
                    <div class="text-center py-5 opacity-25">
                        <i class="fas fa-comment-dots fa-4x mb-3"></i>
                        <p class="fw-bold">No remarks recorded yet.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Line Chart Initialization
        const ctx = document.getElementById('progressChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?= json_encode($labels) ?>,
                datasets: [{
                    label: 'Score Percentage',
                    data: <?= json_encode($scores) ?>,
                    borderColor: '#064e3b',
                    backgroundColor: 'rgba(6, 78, 59, 0.08)',
                    borderWidth: 4,
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: '#d4af37',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 6,
                    pointHoverRadius: 8
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { 
                        beginAtZero: true, 
                        max: 100, 
                        grid: { color: '#f1f5f9' },
                        ticks: { font: { weight: 'bold' } }
                    },
                    x: { grid: { display: false } }
                }
            }
        });

        // Sidebar Menu Toggle
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => {
                document.getElementById('sidebarMenu').classList.toggle('active');
            });
        }
    });
</script>

<?php include 'includes/user_footer.php'; ?>