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

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

$user_id    = $_SESSION['user_id'];
$exam_id    = intval($_POST['exam_id']);
$order_id   = intval($_POST['order_id']);
$booklet    = $_POST['booklet_type']; // A, B, C, D
$answers    = $_POST['answers'];      // Base64 ders adı ve soru no içeren dizi

try {
    $db->beginTransaction();

    // 1. Sınavın Net Hesaplama Kuralını Belirle (TYT/AYT: 1/4, LGS: 1/3)
    $examInfoStmt = $db->prepare("SELECT exam_type FROM exam_analysis_exams WHERE id = ?");
    $examInfoStmt->execute([$exam_id]);
    $examType = $examInfoStmt->fetchColumn();

    $wrong_to_minus = ($examType == 'LGS') ? 3 : 4; // LGS ise 3 yanlış 1 doğru, TYT/AYT ise 4 yanlış 1 doğru

    // 2. Bu Sınava Ait Doğru Cevap Anahtarını Çek
    $keysStmt = $db->prepare("SELECT * FROM exam_analysis_keys WHERE exam_id = ?");
    $keysStmt->execute([$exam_id]);
    $all_keys = $keysStmt->fetchAll(PDO::FETCH_ASSOC);

    $total_correct = 0;
    $total_incorrect = 0;
    $total_empty = 0;
    $detailed_analysis = []; // Ders bazlı detayları tutacağız

    // 3. Hesaplama Döngüsü
    foreach ($all_keys as $key) {
        $lesson = $key['lesson_name'];
        $encoded_lesson = base64_encode($lesson);
        
        // Kitapçığa göre öğrencinin bakması gereken soru numarasını bul
        $target_question_no = $key['a_question_no']; // Varsayılan A
        if ($booklet == 'B') $target_question_no = $key['b_question_no'];
        if ($booklet == 'C') $target_question_no = $key['c_question_no'];
        if ($booklet == 'D') $target_question_no = $key['d_question_no'];

        // Öğrencinin bu derse ve bu soruya verdiği cevabı al
        $student_answer = isset($answers[$encoded_lesson][$target_question_no]) ? $answers[$encoded_lesson][$target_question_no] : "";

        // Analiz dizisinde dersi hazırla
        if (!isset($detailed_analysis[$lesson])) {
            $detailed_analysis[$lesson] = ['dogru' => 0, 'yanlis' => 0, 'bos' => 0, 'konu_detay' => []];
        }

        // SORU İPTAL EDİLMİŞSE (Hesaplamaya katma)
        if ($key['is_canceled'] == 1) {
            continue; 
        }

        // Karşılaştırma
        if (empty($student_answer)) {
            $total_empty++;
            $detailed_analysis[$lesson]['bos']++;
            $status = 'BOS';
        } elseif ($student_answer == $key['correct_answer']) {
            $total_correct++;
            $detailed_analysis[$lesson]['dogru']++;
            $status = 'DOGRU';
        } else {
            $total_incorrect++;
            $detailed_analysis[$lesson]['yanlis']++;
            $status = 'YANLIS';
        }

        // Konu Analizi İçin Veri Biriktir
        $detailed_analysis[$lesson]['konu_detay'][] = [
            'konu' => $key['topic_name'],
            'durum' => $status,
            'dogru_cevap' => $key['correct_answer'],
            'ogrenci_cevap' => $student_answer
        ];
    }

    // 4. Net Skoru Hesapla
    $net_score = $total_correct - ($total_incorrect / $wrong_to_minus);
    if ($net_score < 0) $net_score = 0; // Net eksiye düşmesin

    // 5. Veritabanına Kaydet (Daha önce varsa güncelle, yoksa ekle)
    $checkStmt = $db->prepare("SELECT id FROM exam_analysis_student_results WHERE user_id = ? AND exam_id = ?");
    $checkStmt->execute([$user_id, $exam_id]);
    $existing_id = $checkStmt->fetchColumn();

    $raw_json = json_encode($detailed_analysis, JSON_UNESCAPED_UNICODE);

    if ($existing_id) {
        $updateSql = "UPDATE exam_analysis_student_results SET 
                      order_id = ?, booklet_type = ?, total_correct = ?, total_incorrect = ?, 
                      total_empty = ?, net_score = ?, raw_answers_json = ?, created_at = NOW() 
                      WHERE id = ?";
        $db->prepare($updateSql)->execute([$order_id, $booklet, $total_correct, $total_incorrect, $total_empty, $net_score, $raw_json, $existing_id]);
        $result_id = $existing_id;
    } else {
        $insertSql = "INSERT INTO exam_analysis_student_results 
                      (user_id, exam_id, order_id, booklet_type, total_correct, total_incorrect, total_empty, net_score, raw_answers_json) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $db->prepare($insertSql)->execute([$user_id, $exam_id, $order_id, $booklet, $total_correct, $total_incorrect, $total_empty, $net_score, $raw_json]);
        $result_id = $db->lastInsertId();
    }

    $db->commit();

    // İşlem başarılı, karne sayfasına yönlendir
    header("Location: deneme-analiz-sonuc.php?id=" . $result_id);

} catch (Exception $e) {
    $db->rollBack();
    die("Hata oluştu: " . $e->getMessage());
}