<?php
require_once 'config/database.php';

echo "Inserting test data...\n";

// Check if class "ONE" exists
$stmt = $pdo->prepare("SELECT id FROM classes WHERE name = ?");
$stmt->execute(['ONE']);
$class = $stmt->fetch();

if (!$class) {
    echo "Class 'ONE' not found. Creating it...\n";
    $stmt = $pdo->prepare("INSERT INTO classes (name, section) VALUES (?, ?)");
    $stmt->execute(['ONE', 'A']);
    $class_id = $pdo->lastInsertId();
} else {
    $class_id = $class['id'];
}
echo "Class ID for 'ONE': " . $class_id . "\n";

// Check if student with roll 101 exists for this class and session 2025
$stmt = $pdo->prepare("SELECT id FROM students WHERE roll_number = ? AND class_id = ? AND session = ?");
$stmt->execute([101, $class_id, '2025']);
$student = $stmt->fetch();

if (!$student) {
    echo "Creating student with roll 101...\n";
    $stmt = $pdo->prepare("INSERT INTO students (first_name, last_name, roll_number, class_id, session, father_name, mother_name, date_of_birth) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute(['Test', 'Student', 101, $class_id, '2025', 'Test Father', 'Test Mother', '2010-01-01']);
    $student_id = $pdo->lastInsertId();
} else {
    $student_id = $student['id'];
}
echo "Student ID: " . $student_id . "\n";

// Insert some sample results for this student
echo "Inserting sample results...\n";

// Get some subjects
$stmt = $pdo->query("SELECT id FROM subjects LIMIT 5");
$subjects = $stmt->fetchAll();

$exam_type = 'midterm';

foreach ($subjects as $index => $subject) {
    $subject_id = $subject['id'];
    
    // Generate random marks
    $marks = rand(40, 100);
    
    // Determine grade based on marks
    if ($marks >= 80) $grade = 'A+';
    elseif ($marks >= 70) $grade = 'A';
    elseif ($marks >= 60) $grade = 'A-';
    elseif ($marks >= 50) $grade = 'B';
    elseif ($marks >= 40) $grade = 'C';
    else $grade = 'F';
    
    // Insert result
    $stmt = $pdo->prepare("INSERT INTO results (student_id, subject_id, marks_obtained, grade, session, exam_type) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$student_id, $subject_id, $marks, $grade, '2025', $exam_type]);
    
    echo "Inserted result for subject ID " . $subject_id . ": " . $marks . " marks, grade " . $grade . "\n";
}

// Insert result publication record
echo "Inserting result publication record...\n";
$stmt = $pdo->prepare("INSERT IGNORE INTO result_publications (session, exam_type, class_id, status, publish_date) VALUES (?, ?, ?, ?, ?)");
$stmt->execute(['2025', $exam_type, $class_id, 'published', date('Y-m-d')]);

echo "Test data inserted successfully!\n";
?>