<?php
// kullanici/optik-form.php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';

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

$user_id = $_SESSION['user_id'];
$exam_id = intval($_GET['exam_id']);
$order_id = intval($_GET['order_id']);

// 1. Sınav Bilgilerini ve Mevcut Kitapçık Türlerini Çek
$examStmt = $db->prepare("
    SELECT e.*, p.name as product_name,
    (SELECT COUNT(*) FROM exam_analysis_keys WHERE exam_id = e.id AND b_question_no IS NOT NULL) as has_b,
    (SELECT COUNT(*) FROM exam_analysis_keys WHERE exam_id = e.id AND c_question_no IS NOT NULL) as has_c,
    (SELECT COUNT(*) FROM exam_analysis_keys WHERE exam_id = e.id AND d_question_no IS NOT NULL) as has_d
    FROM exam_analysis_exams e
    JOIN products p ON e.product_id = p.id
    WHERE e.id = ?");
$examStmt->execute([$exam_id]);
$exam = $examStmt->fetch(PDO::FETCH_ASSOC);

if (!$exam) { die("Sınav bulunamadı."); }

// 2. Dersleri ve Gerçek Soru Numaralarını Çek
$keysStmt = $db->prepare("
    SELECT lesson_name, a_question_no 
    FROM exam_analysis_keys 
    WHERE exam_id = ? 
    ORDER BY id ASC");
$keysStmt->execute([$exam_id]);
$all_keys = $keysStmt->fetchAll(PDO::FETCH_ASSOC);

// Derslere göre soru numaralarını grupla
$lessons = [];
foreach($all_keys as $key) {
    $lname = $key['lesson_name'];
    if(!isset($lessons[$lname])) {
        $lessons[$lname] = [];
    }
    $lessons[$lname][] = $key['a_question_no'];
}

// --- DİNAMİK ŞIK MANTIĞI ---
// Sınav LGS ise E şıkkını diziden çıkarıyoruz
$siklar = ($exam['exam_type'] == 'LGS') ? ['A', 'B', 'C', 'D'] : ['A', 'B', 'C', 'D', 'E'];

$page_title = "Dijital Optik Form";
require_once '../header.php';
?>

<style>
    /* Optik Form Estetiği */
    .optik-row { border-bottom: 1px solid #f1f3f5; padding: 12px 0; transition: all 0.2s; }
    .optik-row:hover { background-color: #f8f9fa; }
    .btn-check:checked + .btn-outline-primary { background-color: #0d6efd !important; color: white !important; border-color: #0d6efd !important; box-shadow: 0 4px 10px rgba(13,110,253,0.3); }
    .btn-group-optik .btn { width: 38px; height: 38px; border-radius: 50% !important; margin: 0 4px; display: inline-flex; align-items: center; justify-content: center; font-weight: bold; font-size: 14px; }
    #lessonTabs .nav-link { border-radius: 30px; margin-right: 8px; margin-bottom: 10px; font-weight: 600; color: #495057; background: #f8f9fa; border: 1px solid #dee2e6; padding: 8px 20px; }
    #lessonTabs .nav-link.active { background: #0d6efd !important; color: #fff !important; border-color: #0d6efd; }
    .sticky-submit-box { position: sticky; bottom: 0; background: rgba(255,255,255,0.9); backdrop-filter: blur(10px); padding: 15px; border-top: 1px solid #eee; z-index: 1000; border-radius: 0 0 15px 15px; }
</style>

<main class="container py-5 text-dark">
    <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-sm rounded-4 mb-4">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
                        <div>
                            <h2 class="h4 fw-bold mb-1 text-primary"><i class="bi bi-pencil-square me-2"></i>Dijital Optik Form</h2>
                            <p class="text-muted small mb-0"><?= htmlspecialchars($exam['product_name']) ?> <span class="badge bg-secondary ms-2"><?= $exam['exam_type'] ?></span></p>
                        </div>
                        <a href="kullanici/deneme-analiz.php" class="btn btn-outline-secondary btn-sm rounded-pill px-3">Vazgeç ve Dön</a>
                    </div>
                </div>
            </div>

            <form action="kullanici/ajax-optik-kaydet.php" method="POST" id="optikForm">
                <input type="hidden" name="exam_id" value="<?= $exam_id ?>">
                <input type="hidden" name="order_id" value="<?= $order_id ?>">

                <div class="card border-0 shadow-sm rounded-4 mb-4 bg-light">
                    <div class="card-body text-center py-4">
                        <h6 class="fw-bold mb-3 text-dark text-uppercase" style="letter-spacing: 1px;">Kitapçık Türünüzü Seçin</h6>
                        <div class="btn-group" role="group">
                            <input type="radio" class="btn-check" name="booklet_type" id="b_a" value="A" required checked>
                            <label class="btn btn-outline-primary px-4 fw-bold" for="b_a">A</label>

                            <?php if($exam['has_b'] > 0): ?>
                                <input type="radio" class="btn-check" name="booklet_type" id="b_b" value="B">
                                <label class="btn btn-outline-primary px-4 fw-bold" for="b_b">B</label>
                            <?php endif; ?>

                            <?php if($exam['has_c'] > 0): ?>
                                <input type="radio" class="btn-check" name="booklet_type" id="b_c" value="C">
                                <label class="btn btn-outline-primary px-4 fw-bold" for="b_c">C</label>
                            <?php endif; ?>

                            <?php if($exam['has_d'] > 0): ?>
                                <input type="radio" class="btn-check" name="booklet_type" id="b_d" value="D">
                                <label class="btn btn-outline-primary px-4 fw-bold" for="b_d">D</label>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <ul class="nav nav-pills mb-4 justify-content-start" id="lessonTabs" role="tablist">
                    <?php 
                    $tabIndex = 0;
                    foreach ($lessons as $lesson_name => $q_numbers): 
                        $tabId = "lesson_" . md5($lesson_name);
                    ?>
                        <li class="nav-item">
                            <button class="nav-link <?= $tabIndex === 0 ? 'active' : '' ?>" id="<?= $tabId ?>-tab" data-bs-toggle="pill" data-bs-target="#<?= $tabId ?>" type="button" role="tab">
                                <?= htmlspecialchars($lesson_name) ?> <span class="badge bg-secondary ms-1"><?= count($q_numbers) ?></span>
                            </button>
                        </li>
                    <?php 
                    $tabIndex++;
                    endforeach; 
                    ?>
                </ul>

                <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                    <div class="card-body p-0">
                        <div class="tab-content" id="lessonTabsContent">
                            <?php 
                            $paneIndex = 0;
                            foreach ($lessons as $lesson_name => $q_numbers): 
                                $tabId = "lesson_" . md5($lesson_name);
                            ?>
                                <div class="tab-pane fade <?= $paneIndex === 0 ? 'show active' : '' ?> p-4" id="<?= $tabId ?>" role="tabpanel">
                                    <div class="row justify-content-center">
                                        <div class="col-md-10 col-xl-8">
                                            <div class="text-center mb-4">
                                                <h5 class="fw-bold text-dark mb-1"><?= htmlspecialchars($lesson_name) ?></h5>
                                                <small class="text-muted">Lütfen soruları sırasıyla işaretleyin.</small>
                                            </div>
                                            
                                            <?php foreach ($q_numbers as $q_no): 
                                                $input_name = "answers[" . base64_encode($lesson_name) . "][{$q_no}]";
                                            ?>
                                                <div class="optik-row d-flex align-items-center justify-content-between">
                                                    <div class="fw-bold text-secondary" style="width: 70px;">Soru <?= $q_no ?></div>
                                                    <div class="btn-group-optik" role="group">
                                                        <?php foreach($siklar as $harf): ?>
                                                            <input type="radio" class="btn-check" name="<?= $input_name ?>" id="ans_<?= md5($lesson_name) ?>_<?= $q_no ?>_<?= $harf ?>" value="<?= $harf ?>">
                                                            <label class="btn btn-outline-primary" for="ans_<?= md5($lesson_name) ?>_<?= $q_no ?>_<?= $harf ?>"><?= $harf ?></label>
                                                        <?php endforeach; ?>
                                                        
                                                        <input type="radio" class="btn-check" name="<?= $input_name ?>" id="ans_<?= md5($lesson_name) ?>_<?= $q_no ?>_empty" value="" checked>
                                                        <label class="btn btn-outline-secondary" for="ans_<?= md5($lesson_name) ?>_<?= $q_no ?>_empty" title="Boş Bırak"><i class="bi bi-eraser-fill"></i></label>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php 
                            $paneIndex++;
                            endforeach; 
                            ?>
                        </div>
                    </div>
                    
                    <div class="sticky-submit-box text-center">
                        <button type="submit" class="btn btn-success btn-lg px-5 rounded-pill fw-bold shadow">
                            <i class="bi bi-check2-circle me-2"></i>Analizi Bitir ve Kaydet
                        </button>
                    </div>
                </div>
            </form>

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

<script>
    document.getElementById('optikForm').onsubmit = function() {
        return confirm('Tüm derslerdeki işaretlemeleriniz bitti mi? Analiz sonuçlarınız hesaplanacaktır.');
    };
</script>

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