<?php
/**
 * Kullanıcı Paneli - Deneme Analiz Karnesi
 * Konum: /magaza/kullanici/deneme-analiz-sonuc.php
 */

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

if (!isset($_SESSION['user_id']) || !isset($_GET['id'])) {
    header("Location: deneme-analiz.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$result_id = intval($_GET['id']);

// 1. Analiz Verilerini ve Sınav Bilgilerini Çek
$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.id = ? AND r.user_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$result_id, $user_id]);
$res = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$res) { die("Analiz kaydı bulunamadı."); }

// JSON Verisini Çöz (Ders ve Konu Detayları Burada)
$analysis_data = json_decode($res['raw_answers_json'], true);

// Sınav türüne göre yanlış katsayısı (LGS'de 3 yanlış 1 doğruyu, YKS'de 4 yanlış 1 doğruyu götürür)
$yanlis_katsayisi = (strtoupper($res['exam_type']) == 'LGS') ? 3 : 4;

// --- GRAFİK İÇİN VERİ HAZIRLIĞI ---
$chart_labels = [];
$chart_corrects = [];
$chart_incorrects = [];
$chart_nets = [];

foreach ($analysis_data as $lesson_name => $data) {
    $chart_labels[] = $lesson_name;
    $chart_corrects[] = $data['dogru'];
    $chart_incorrects[] = $data['yanlis'];
    $net = $data['dogru'] - ($data['yanlis'] / $yanlis_katsayisi);
    $chart_nets[] = round($net, 2);
}
// -----------------------------------

$page_title = "Sınav Sonuç Karnesi";
require_once '../header.php';
?>

<style>
    /* Modern Tasarım İçin Özel CSS Dokunuşları */
    .bg-gradient-primary { 
        background: linear-gradient(135deg, #0d6efd 0%, #0a58ca 100%) !important; 
        position: relative;
    }
    .bg-gradient-primary::after {
        content: '';
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        background: url('data:image/svg+xml;utf8,<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" stroke="rgba(255,255,255,0.1)" stroke-width="2" fill="none"/></svg>') repeat;
        opacity: 0.5;
        pointer-events: none;
    }
    .karne-stat-box {
        transition: all 0.3s ease;
        border: 1px solid transparent;
    }
    .karne-stat-box:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.05);
    }
    .icon-square {
        width: 48px;
        height: 48px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        font-size: 1.25rem;
    }
    .table-modern th {
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        border-bottom: 2px solid #f1f3f5;
        color: #6c757d;
    }
    .table-modern td {
        padding: 1rem 0.5rem;
        vertical-align: middle;
        border-bottom: 1px solid #f8f9fa;
        color: #495057;
    }
    .table-modern tr:hover td {
        background-color: #fcfcfc;
    }
    .progress-modern {
        height: 10px;
        border-radius: 20px;
        background-color: #e9ecef;
        overflow: visible;
    }
    .progress-modern .progress-bar {
        border-radius: 20px;
        position: relative;
    }
</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="card border-0 shadow-lg rounded-4 mb-5 overflow-hidden">
                <div class="row g-0">
                    <div class="col-md-5 bg-gradient-primary text-white d-flex flex-column align-items-center justify-content-center p-5 text-center">
                        <div style="z-index: 1;">
                            <span class="d-block small fw-bold mb-2" style="letter-spacing: 2px; color: rgba(255,255,255,0.8);">TOPLAM NET</span>
                            <h1 class="display-2 fw-bolder mb-3 text-white"><?= number_format($res['net_score'], 2) ?></h1>
                            <span class="badge bg-white text-primary px-4 py-2 rounded-pill shadow-sm fs-6">
                                <i class="bi bi-bookmark-star-fill me-1"></i> <?= $res['exam_type'] ?> DENEMESİ
                            </span>
                        </div>
                    </div>
                    
                    <div class="col-md-7 bg-white p-5 d-flex flex-column justify-content-center">
                        <h3 class="fw-bold text-dark mb-1"><?= htmlspecialchars($res['exam_name']) ?></h3>
                        <p class="text-muted small mb-4">Bu denemedeki genel doğru, yanlış ve boş dağılımınız.</p>
                        
                        <div class="row g-3 text-center mb-4">
                            <div class="col-4">
                                <div class="karne-stat-box bg-success bg-opacity-10 border-success border-opacity-25 rounded-4 p-3 h-100">
                                    <h2 class="text-success fw-bolder mb-0"><?= $res['total_correct'] ?></h2>
                                    <span class="text-success small fw-bold text-uppercase" style="letter-spacing: 1px;">Doğru</span>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="karne-stat-box bg-danger bg-opacity-10 border-danger border-opacity-25 rounded-4 p-3 h-100">
                                    <h2 class="text-danger fw-bolder mb-0"><?= $res['total_incorrect'] ?></h2>
                                    <span class="text-danger small fw-bold text-uppercase" style="letter-spacing: 1px;">Yanlış</span>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="karne-stat-box bg-secondary bg-opacity-10 border-secondary border-opacity-25 rounded-4 p-3 h-100">
                                    <h2 class="text-secondary fw-bolder mb-0"><?= $res['total_empty'] ?></h2>
                                    <span class="text-secondary small fw-bold text-uppercase" style="letter-spacing: 1px;">Boş</span>
                                </div>
                            </div>
                        </div>

                        <div>
                            <a href="kullanici/deneme-analiz.php" class="btn btn-light border shadow-sm rounded-pill px-4 fw-medium text-dark">
                                <i class="bi bi-arrow-left me-2"></i>Analizlere Dön
                            </a>
                            
                            <a href="kullanici/deneme-gelisim.php" class="btn btn-light border shadow-sm rounded-pill px-4 fw-medium text-dark">
                                <i class="bi bi-arrow-left me-2"></i>Deneme Gelişim
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card border-0 shadow-sm rounded-4 mb-5">
                <div class="card-header bg-transparent border-0 pt-4 pb-0 px-4">
                    <h5 class="fw-bold mb-0 text-dark d-flex align-items-center">
                        <i class="bi bi-bar-chart-fill me-2 text-primary"></i> Ders Bazlı Performans Grafiği
                    </h5>
                    <p class="text-muted small mt-1">Derslerinize ait Doğru, Yanlış ve Net sayılarının karşılaştırması.</p>
                </div>
                <div class="card-body px-4 pb-4">
                    <div style="position: relative; height:350px; width:100%">
                        <canvas id="performanceChart"></canvas>
                    </div>
                </div>
            </div>

            <div class="d-flex align-items-center mb-4 px-2">
                <div class="icon-square bg-dark bg-opacity-10 text-dark me-3">
                    <i class="bi bi-journal-text"></i>
                </div>
                <div>
                    <h4 class="fw-bold mb-0 text-dark">Ders ve Konu Analizi</h4>
                    <span class="text-muted small">Ders bazlı netlerinizi ve konu eksiklerinizi detaylı inceleyin.</span>
                </div>
            </div>
            
            <div class="row g-4">
                <?php foreach ($analysis_data as $lesson_name => $data): 
                    $lesson_total = $data['dogru'] + $data['yanlis'] + $data['bos'];
                    $success_rate = ($lesson_total > 0) ? ($data['dogru'] / $lesson_total) * 100 : 0;
                    
                    // Ders bazlı net hesaplama
                    $lesson_net = $data['dogru'] - ($data['yanlis'] / $yanlis_katsayisi);
                    
                    // Konuları Grupla
                    $topic_summary = [];
                    foreach ($data['konu_detay'] as $detay) {
                        $t_name = $detay['konu'];
                        if (!isset($topic_summary[$t_name])) {
                            $topic_summary[$t_name] = ['d' => 0, 'y' => 0, 'b' => 0];
                        }
                        if ($detay['durum'] == 'DOGRU') $topic_summary[$t_name]['d']++;
                        elseif ($detay['durum'] == 'YANLIS') $topic_summary[$t_name]['y']++;
                        else $topic_summary[$t_name]['b']++;
                    }
                ?>
                <div class="col-12">
                    <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 d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <h5 class="fw-bold mb-0 text-primary d-flex align-items-center">
                                <i class="bi bi-journal-bookmark-fill me-2 text-primary opacity-75"></i> <?= htmlspecialchars($lesson_name) ?>
                            </h5>
                            <div>
                                <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-3 py-2 rounded-pill me-1" title="Doğru Sayısı">
                                    <?= $data['dogru'] ?> D
                                </span>
                                <span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 px-3 py-2 rounded-pill me-1" title="Yanlış Sayısı">
                                    <?= $data['yanlis'] ?> Y
                                </span>
                                <span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-3 py-2 rounded-pill" title="Ders Neti">
                                    <i class="bi bi-bullseye me-1"></i><?= number_format($lesson_net, 2) ?> Net
                                </span>
                            </div>
                        </div>

                        <div class="card-body px-4 pt-4 pb-4">
                            
                            <div class="d-flex justify-content-between align-items-end mb-2">
                                <span class="small fw-bold text-muted">Ders Başarısı (Doğru Oranı)</span>
                                <span class="small fw-bold text-primary">%<?= number_format($success_rate, 0) ?></span>
                            </div>
                            <div class="progress progress-modern mb-4 shadow-sm">
                                <div class="progress-bar bg-primary" role="progressbar" style="width: <?= $success_rate ?>%" aria-valuenow="<?= $success_rate ?>" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-borderless table-modern align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th style="width: 50%;">Konu Adı</th>
                                            <th class="text-center" style="width: 15%;">Toplam Soru</th>
                                            <th class="text-center" style="width: 15%;">Doğru / Yanlış</th>
                                            <th class="text-end" style="width: 20%;">Durum Tavsiyesi</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($topic_summary as $t_name => $s): 
                                            $total_q = $s['d'] + $s['y'] + $s['b'];
                                            $rate = ($s['d'] / $total_q) * 100;
                                            
                                            // Tavsiye Mantığı ve Rozetler
                                            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 fw-bold w-100 text-center"><i class="bi bi-stars me-1"></i> Harika, Devam!</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 fw-bold w-100 text-center"><i class="bi bi-exclamation-triangle-fill me-1"></i> Biraz Tekrar Et</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 fw-bold w-100 text-center"><i class="bi bi-book-half me-1"></i> Mutlaka Çalış!</span>';
                                            }
                                        ?>
                                        <tr>
                                            <td class="fw-semibold text-dark">
                                                <?= htmlspecialchars($t_name) ?>
                                            </td>
                                            <td class="text-center fw-bold text-muted bg-light rounded-3">
                                                <?= $total_q ?>
                                            </td>
                                            <td class="text-center">
                                                <span class="text-success fw-bold"><?= $s['d'] ?></span> 
                                                <span class="text-muted mx-1">/</span> 
                                                <span class="text-danger fw-bold"><?= $s['y'] ?></span>
                                            </td>
                                            <td class="text-end">
                                                <?= $badge ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

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

<script>
document.addEventListener("DOMContentLoaded", function() {
    const ctx = document.getElementById('performanceChart').getContext('2d');
    
    // PHP'den gelen JSON verileri
    const labels = <?= json_encode($chart_labels) ?>;
    const dataCorrects = <?= json_encode($chart_corrects) ?>;
    const dataIncorrects = <?= json_encode($chart_incorrects) ?>;
    const dataNets = <?= json_encode($chart_nets) ?>;

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Doğru',
                    data: dataCorrects,
                    backgroundColor: 'rgba(25, 135, 84, 0.85)', // Success
                    borderRadius: 4,
                },
                {
                    label: 'Yanlış',
                    data: dataIncorrects,
                    backgroundColor: 'rgba(220, 53, 69, 0.85)', // Danger
                    borderRadius: 4,
                },
                {
                    label: 'Net',
                    data: dataNets,
                    backgroundColor: 'rgba(13, 110, 253, 0.85)', // Primary
                    borderRadius: 4,
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false,
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        font: {
                            family: "'Poppins', sans-serif",
                            weight: '600'
                        }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0,0,0,0.8)',
                    titleFont: { family: "'Poppins', sans-serif", size: 14 },
                    bodyFont: { family: "'Poppins', sans-serif", size: 13 },
                    padding: 12,
                    cornerRadius: 8
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0,0,0,0.05)',
                        drawBorder: false
                    },
                    ticks: {
                        font: { family: "'Poppins', sans-serif" }
                    }
                },
                x: {
                    grid: {
                        display: false,
                        drawBorder: false
                    },
                    ticks: {
                        font: { family: "'Poppins', sans-serif", weight: '500' }
                    }
                }
            }
        }
    });
});
</script>

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