<?php
/**
 * Kullanıcı Paneli - Deneme Gelişim Raporu (Son 3 Deneme)
 * Konum: /magaza/kullanici/deneme-gelisim.php
 */

require_once '../includes/db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: ../giris.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// Hangi sınav türünün analizini yapıyoruz? (Varsayılan: TYT)
$allowed_types = ['TYT', 'AYT', 'LGS'];
$exam_type = isset($_GET['type']) && in_array(strtoupper($_GET['type']), $allowed_types) ? strtoupper($_GET['type']) : 'TYT';
$yanlis_katsayisi = ($exam_type == 'LGS') ? 3 : 4;

// Kullanıcının seçili sınav türündeki son 3 analizini çek (Eskiden yeniye sıralamak için önce DESC alıp sonra PHP'de ters çevireceğiz)
$sql = "SELECT r.*, e.name as exam_name, e.exam_type 
        FROM exam_analysis_student_results r
        JOIN exam_analysis_exams e ON r.exam_id = e.id
        WHERE r.user_id = ? AND e.exam_type = ? AND r.status = 1
        ORDER BY r.created_at DESC 
        LIMIT 3";
$stmt = $db->prepare($sql);
$stmt->execute([$user_id, $exam_type]);
$results_desc = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Kronolojik sıra (Deneme 1, Deneme 2, Deneme 3)
$results = array_reverse($results_desc);

// Grafikler ve Tablolar için veri hazırlığı
$trend_labels = [];
$trend_nets = [];

$subject_totals = []; // Ders bazlı toplamlar
$topic_totals = [];   // Konu bazlı toplamlar

foreach ($results as $index => $res) {
    // Çizgi Grafik Verisi (Gelişim)
    $trend_labels[] = $res['exam_name'];
    $trend_nets[] = (float)$res['net_score'];

    $analysis_data = json_decode($res['raw_answers_json'], true);
    if(!$analysis_data) continue;

    foreach ($analysis_data as $lesson_name => $data) {
        // Ders Ortalamaları İçin Toplama
        if (!isset($subject_totals[$lesson_name])) {
            $subject_totals[$lesson_name] = ['d' => 0, 'y' => 0, 'b' => 0, 'exam_count' => 0];
        }
        $subject_totals[$lesson_name]['d'] += $data['dogru'];
        $subject_totals[$lesson_name]['y'] += $data['yanlis'];
        $subject_totals[$lesson_name]['b'] += $data['bos'];
        $subject_totals[$lesson_name]['exam_count']++;

        // Konu Analizi İçin Toplama
        if (!isset($topic_totals[$lesson_name])) {
            $topic_totals[$lesson_name] = [];
        }

        foreach ($data['konu_detay'] as $detay) {
            $t_name = $detay['konu'];
            if (!isset($topic_totals[$lesson_name][$t_name])) {
                $topic_totals[$lesson_name][$t_name] = ['d' => 0, 'y' => 0, 'b' => 0];
            }
            if ($detay['durum'] == 'DOGRU') $topic_totals[$lesson_name][$t_name]['d']++;
            elseif ($detay['durum'] == 'YANLIS') $topic_totals[$lesson_name][$t_name]['y']++;
            else $topic_totals[$lesson_name][$t_name]['b']++;
        }
    }
}

// Ders Sütun Grafiği İçin Veri Hazırlığı
$bar_labels = [];
$bar_avg_nets = [];
foreach ($subject_totals as $lesson => $totals) {
    $bar_labels[] = $lesson;
    $avg_net = ($totals['d'] - ($totals['y'] / $yanlis_katsayisi)) / $totals['exam_count'];
    $bar_avg_nets[] = round($avg_net, 2);
}

// Konuları Başarı Oranına Göre Sıralama (En kötüler en üstte çıksın diye)
foreach ($topic_totals as $lesson => &$topics) {
    uasort($topics, function($a, $b) {
        $total_a = $a['d'] + $a['y'] + $a['b'];
        $total_b = $b['d'] + $b['y'] + $b['b'];
        $rate_a = ($total_a > 0) ? ($a['d'] / $total_a) : 0;
        $rate_b = ($total_b > 0) ? ($b['d'] / $total_b) : 0;
        return $rate_a <=> $rate_b; // Küçükten büyüğe (En zayıf konular önce)
    });
}
unset($topics);

$page_title = "Gelişim Raporu";
require_once '../header.php';
?>

<style>
    .bg-gradient-info { background: linear-gradient(135deg, #17a2b8 0%, #0dcaf0 100%) !important; color: white;}
    .nav-pills .nav-link { border-radius: 30px; font-weight: 600; color: #495057; background: #f8f9fa; border: 1px solid #dee2e6; margin-right: 10px; padding: 10px 25px; transition: all 0.3s;}
    .nav-pills .nav-link.active { background-color: #0d6efd; color: white; border-color: #0d6efd; box-shadow: 0 4px 10px rgba(13,110,253,0.3);}
    .table-modern th { font-size: 0.8rem; font-weight: 600; text-transform: uppercase; border-bottom: 2px solid #f1f3f5; color: #6c757d;}
    .table-modern td { vertical-align: middle; border-bottom: 1px solid #f8f9fa; padding: 12px 10px;}
    .table-modern tr:hover td { background-color: #fcfcfc;}
    .topic-badge { width: 100px; display: inline-block; text-align: center; }
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<main class="container py-5">
    <div class="row">
        
        <div class="col-lg-3 mb-4">
            <?php include 'sidebar.php'; ?>
        </div>

        <div class="col-lg-9">
            
            <div class="d-flex justify-content-between align-items-end mb-4 flex-wrap gap-3">
                <div>
                    <h2 class="h3 fw-bold mb-1 text-dark"><i class="bi bi-graph-up-arrow text-info me-2"></i>Gelişim Raporu</h2>
                    <p class="text-muted mb-0">Son 3 deneme sınavınıza ait performans ve konu eksiklikleri analizi.</p>
                </div>
            </div>

            <ul class="nav nav-pills mb-4 border-bottom pb-3">
                <li class="nav-item">
                    <a class="nav-link <?= $exam_type == 'TYT' ? 'active' : '' ?>" href="kullanici/deneme-gelisim.php?type=TYT">TYT Analizi</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $exam_type == 'AYT' ? 'active' : '' ?>" href="kullanici/deneme-gelisim.php?type=AYT">AYT Analizi</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $exam_type == 'LGS' ? 'active' : '' ?>" href="kullanici/deneme-gelisim.php?type=LGS">LGS Analizi</a>
                </li>
            </ul>

            <?php if (count($results) === 0): ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm border">
                    <i class="bi bi-clipboard-x text-muted opacity-25" style="font-size: 4rem;"></i>
                    <h5 class="fw-bold mt-3 text-dark">Yeterli Veri Yok</h5>
                    <p class="text-muted mb-0">Gelişim raporu oluşturulabilmesi için seçili sınav türünden analiz girmiş olmalısınız.</p>
                </div>
            <?php else: ?>

                <div class="row g-4 mb-5">
                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm rounded-4 h-100">
                            <div class="card-header bg-transparent border-0 pt-4 pb-0 px-4">
                                <h6 class="fw-bold text-dark mb-0">Toplam Net Gelişimi</h6>
                                <small class="text-muted">Son <?= count($results) ?> Deneme</small>
                            </div>
                            <div class="card-body px-4 pb-4">
                                <div style="height:250px;">
                                    <canvas id="trendChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm rounded-4 h-100">
                            <div class="card-header bg-transparent border-0 pt-4 pb-0 px-4">
                                <h6 class="fw-bold text-dark mb-0">Ders Bazlı Ortalama Netler</h6>
                                <small class="text-muted">Son <?= count($results) ?> Deneme Ortalaması</small>
                            </div>
                            <div class="card-body px-4 pb-4">
                                <div style="height:250px;">
                                    <canvas id="subjectChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="d-flex align-items-center mb-4 px-2">
                    <div class="bg-warning bg-opacity-10 text-warning rounded-3 d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px; font-size: 1.5rem;">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                    </div>
                    <div>
                        <h4 class="fw-bold mb-0 text-dark">Kritik Konu Analizi</h4>
                        <span class="text-muted small">Aşağıdaki tablolar son <?= count($results) ?> denemedeki performansınıza göre <b>en zayıf olduğunuz konulardan başlayarak</b> sıralanmıştır.</span>
                    </div>
                </div>

                <div class="row g-4">
                    <?php foreach ($topic_totals as $lesson_name => $topics): ?>
                        <div class="col-12">
                            <div class="card border-0 shadow-sm rounded-4">
                                <div class="card-header bg-white border-bottom-0 pt-4 px-4">
                                    <h5 class="fw-bold mb-0 text-primary"><i class="bi bi-journal-bookmark-fill me-2 opacity-50"></i><?= htmlspecialchars($lesson_name) ?></h5>
                                </div>
                                <div class="card-body px-4 pb-4">
                                    <div class="table-responsive">
                                        <table class="table table-modern table-borderless align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th style="width: 45%;">Konu Adı</th>
                                                    <th class="text-center">Sorulma Sayısı</th>
                                                    <th class="text-center">Doğru / Yanlış / Boş</th>
                                                    <th class="text-end">Başarı Durumu</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($topics as $t_name => $s): 
                                                    $total = $s['d'] + $s['y'] + $s['b'];
                                                    $rate = ($total > 0) ? round(($s['d'] / $total) * 100) : 0;
                                                    
                                                    if ($rate >= 80) {
                                                        $badge = '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-3 py-2 rounded-pill topic-badge"><i class="bi bi-check2-all me-1"></i> %'.$rate.'</span>';
                                                    } elseif ($rate >= 50) {
                                                        $badge = '<span class="badge bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25 px-3 py-2 rounded-pill topic-badge"><i class="bi bi-arrow-clockwise me-1"></i> %'.$rate.'</span>';
                                                    } else {
                                                        $badge = '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 px-3 py-2 rounded-pill topic-badge"><i class="bi bi-exclamation-circle-fill me-1"></i> %'.$rate.'</span>';
                                                    }
                                                ?>
                                                <tr>
                                                    <td class="fw-semibold text-dark"><?= htmlspecialchars($t_name) ?></td>
                                                    <td class="text-center text-muted fw-bold"><?= $total ?></td>
                                                    <td class="text-center">
                                                        <span class="text-success fw-bold"><?= $s['d'] ?></span> / 
                                                        <span class="text-danger fw-bold"><?= $s['y'] ?></span> / 
                                                        <span class="text-secondary fw-bold"><?= $s['b'] ?></span>
                                                    </td>
                                                    <td class="text-end"><?= $badge ?></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

            <?php endif; ?>

        </div>
    </div>
</main>

<?php if (count($results) > 0): ?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // 1. Çizgi Grafik (Net Gelişimi)
    const ctxTrend = document.getElementById('trendChart').getContext('2d');
    new Chart(ctxTrend, {
        type: 'line',
        data: {
            labels: <?= json_encode($trend_labels) ?>,
            datasets: [{
                label: 'Toplam Net',
                data: <?= json_encode($trend_nets) ?>,
                borderColor: '#0d6efd',
                backgroundColor: 'rgba(13, 110, 253, 0.1)',
                borderWidth: 3,
                pointBackgroundColor: '#0d6efd',
                pointRadius: 5,
                pointHoverRadius: 7,
                fill: true,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: false, grid: { borderDashOffset: [2], color: 'rgba(0,0,0,0.05)' } },
                x: { grid: { display: false } }
            }
        }
    });

    // 2. Sütun Grafik (Ders Ortalamaları)
    const ctxSubj = document.getElementById('subjectChart').getContext('2d');
    new Chart(ctxSubj, {
        type: 'bar',
        data: {
            labels: <?= json_encode($bar_labels) ?>,
            datasets: [{
                label: 'Ortalama Net',
                data: <?= json_encode($bar_avg_nets) ?>,
                backgroundColor: 'rgba(25, 135, 84, 0.85)',
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, grid: { borderDashOffset: [2], color: 'rgba(0,0,0,0.05)' } },
                x: { grid: { display: false } }
            }
        }
    });
});
</script>
<?php endif; ?>

<?php require_once '../footer.php'; ?>