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

echo "<h1>🧪 Test POST Auto-Creation</h1>";

// Simulate the exact POST data from the log
$subject_id = 8;
$class_id = 11;
$session = '2024';
$exam_type = 'midterm';

echo "<h2>1. Testing Auto-Creation for:</h2>";
echo "<ul>";
echo "<li>Subject ID: $subject_id</li>";
echo "<li>Class ID: $class_id</li>";
echo "<li>Session: $session</li>";
echo "<li>Exam Type: $exam_type</li>";
echo "</ul>";

// Check if distribution exists
$stmt = $pdo->prepare("SELECT * FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?");
$stmt->execute([$subject_id, $class_id, $session, $exam_type]);
$mark_distribution = $stmt->fetch();

if ($mark_distribution) {
    echo "<div style='background: #fff3cd; padding: 15px; border-radius: 5px;'>";
    echo "<p>⚠️ Distribution already exists. Deleting for test...</p>";
    $delete_stmt = $pdo->prepare("DELETE FROM mark_distributions WHERE id = ?");
    $delete_stmt->execute([$mark_distribution['id']]);
    echo "<p>✅ Deleted existing distribution</p>";
    echo "</div>";
}

// Test auto-creation
echo "<h2>2. Testing Auto-Creation Logic</h2>";

try {
    // Set default marks based on exam type
    $default_marks = [
        'midterm' => ['cq' => 30, 'mcq' => 20, 'practical' => 15, 'assignment' => 10, 'attendance' => 5, 'total' => 80],
        'final' => ['cq' => 40, 'mcq' => 25, 'practical' => 20, 'assignment' => 10, 'attendance' => 5, 'total' => 100],
        'test' => ['cq' => 20, 'mcq' => 15, 'practical' => 10, 'assignment' => 5, 'attendance' => 0, 'total' => 50],
        'assignment' => ['cq' => 0, 'mcq' => 0, 'practical' => 0, 'assignment' => 20, 'attendance' => 0, 'total' => 20],
        'practical' => ['cq' => 0, 'mcq' => 0, 'practical' => 30, 'assignment' => 0, 'attendance' => 0, 'total' => 30]
    ];
    
    $marks = $default_marks[$exam_type] ?? $default_marks['midterm'];
    $overall_pass = $marks['total'] * 0.4; // 40% pass marks
    
    echo "<div style='background: #e7f3ff; padding: 15px; border-radius: 5px;'>";
    echo "<p><strong>Creating distribution with:</strong></p>";
    echo "<ul>";
    echo "<li>CQ: {$marks['cq']}</li>";
    echo "<li>MCQ: {$marks['mcq']}</li>";
    echo "<li>Practical: {$marks['practical']}</li>";
    echo "<li>Assignment: {$marks['assignment']}</li>";
    echo "<li>Attendance: {$marks['attendance']}</li>";
    echo "<li>Total: {$marks['total']}</li>";
    echo "<li>Pass Marks: $overall_pass</li>";
    echo "</ul>";
    echo "</div>";
    
    $create_stmt = $pdo->prepare("
        INSERT INTO mark_distributions 
        (subject_id, class_id, session, exam_type, cq_marks, mcq_marks, practical_marks, assignment_marks, attendance_marks, total_marks, overall_pass_marks, cq_pass_marks, mcq_pass_marks, practical_pass_marks)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $result = $create_stmt->execute([
        $subject_id, $class_id, $session, $exam_type,
        $marks['cq'], $marks['mcq'], $marks['practical'], $marks['assignment'], $marks['attendance'],
        $marks['total'], $overall_pass,
        $marks['cq'] * 0.4, $marks['mcq'] * 0.4, $marks['practical'] * 0.4
    ]);
    
    if ($result) {
        echo "<div style='background: #d4edda; padding: 15px; border-radius: 5px;'>";
        echo "<p>✅ <strong>SUCCESS!</strong> Mark distribution created</p>";
        echo "</div>";
        
        // Verify
        $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
        $created_distribution = $stmt->fetch();
        
        if ($created_distribution) {
            echo "<h3>3. Verification</h3>";
            echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px;'>";
            echo "<pre>" . print_r($created_distribution, true) . "</pre>";
            echo "</div>";
            
            // Now test marks save
            echo "<h3>4. Test Marks Save</h3>";
            
            // Simulate student marks from the log
            $student_marks = [
                1647 => ['cq' => 45, 'mcq' => 10, 'practical' => 0, 'assignment' => 0, 'attendance' => 0]
            ];
            
            try {
                $pdo->beginTransaction();
                
                foreach ($student_marks as $student_id => $marks) {
                    $cq_marks = max(0, min((float)($marks['cq'] ?? 0), $created_distribution['cq_marks']));
                    $mcq_marks = max(0, min((float)($marks['mcq'] ?? 0), $created_distribution['mcq_marks']));
                    $practical_marks = max(0, min((float)($marks['practical'] ?? 0), $created_distribution['practical_marks']));
                    $assignment_marks = max(0, min((float)($marks['assignment'] ?? 0), $created_distribution['assignment_marks']));
                    $attendance_marks = max(0, min((float)($marks['attendance'] ?? 0), $created_distribution['attendance_marks']));
                    
                    $total_marks = $cq_marks + $mcq_marks + $practical_marks + $assignment_marks + $attendance_marks;
                    
                    // Simple grade calculation
                    $percentage = ($total_marks / $created_distribution['total_marks']) * 100;
                    if ($percentage >= 80) $grade = 'A+';
                    elseif ($percentage >= 70) $grade = 'A';
                    elseif ($percentage >= 60) $grade = 'A-';
                    elseif ($percentage >= 50) $grade = 'B';
                    elseif ($percentage >= 40) $grade = 'C';
                    elseif ($percentage >= 33) $grade = 'D';
                    else $grade = 'F';
                    
                    echo "<p>Processing Student $student_id: CQ=$cq_marks, MCQ=$mcq_marks, Total=$total_marks, Grade=$grade</p>";
                    
                    $save_stmt = $pdo->prepare("
                        INSERT INTO results 
                        (student_id, exam_id, subject_id, session, group_name, exam_type, marks_obtained, 
                         cq_marks, mcq_marks, practical_marks, assignment_marks, attendance_marks, grade)
                        VALUES (?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ON DUPLICATE KEY UPDATE
                        marks_obtained = VALUES(marks_obtained),
                        cq_marks = VALUES(cq_marks),
                        mcq_marks = VALUES(mcq_marks),
                        practical_marks = VALUES(practical_marks),
                        assignment_marks = VALUES(assignment_marks),
                        attendance_marks = VALUES(attendance_marks),
                        grade = VALUES(grade),
                        updated_at = CURRENT_TIMESTAMP
                    ");
                    
                    $save_result = $save_stmt->execute([
                        $student_id, $subject_id, $session, '', $exam_type, $total_marks,
                        $cq_marks, $mcq_marks, $practical_marks, $assignment_marks, $attendance_marks, $grade
                    ]);
                    
                    if ($save_result) {
                        echo "<p>✅ Marks saved for student $student_id</p>";
                    } else {
                        echo "<p>❌ Failed to save marks for student $student_id</p>";
                    }
                }
                
                $pdo->commit();
                
                echo "<div style='background: #d4edda; padding: 15px; border-radius: 5px;'>";
                echo "<p>✅ <strong>MARKS SAVE TEST SUCCESSFUL!</strong></p>";
                echo "</div>";
                
                // Verify in database
                $verify_stmt = $pdo->prepare("SELECT * FROM results WHERE subject_id = ? AND session = ? AND exam_type = ? ORDER BY student_id");
                $verify_stmt->execute([$subject_id, $session, $exam_type]);
                $saved_results = $verify_stmt->fetchAll();
                
                if (!empty($saved_results)) {
                    echo "<h3>5. Database Verification</h3>";
                    echo "<table border='1' style='border-collapse: collapse;'>";
                    echo "<tr><th>Student ID</th><th>CQ</th><th>MCQ</th><th>Total</th><th>Grade</th></tr>";
                    foreach ($saved_results as $result) {
                        echo "<tr>";
                        echo "<td>{$result['student_id']}</td>";
                        echo "<td>{$result['cq_marks']}</td>";
                        echo "<td>{$result['mcq_marks']}</td>";
                        echo "<td>{$result['marks_obtained']}</td>";
                        echo "<td>{$result['grade']}</td>";
                        echo "</tr>";
                    }
                    echo "</table>";
                } else {
                    echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
                    echo "<p>❌ No results found in database after save!</p>";
                    echo "</div>";
                }
                
            } catch (Exception $e) {
                $pdo->rollBack();
                echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
                echo "<p>❌ Marks save error: " . $e->getMessage() . "</p>";
                echo "</div>";
            }
        }
    } else {
        echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
        echo "<p>❌ Failed to create distribution</p>";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
    echo "<p>❌ Auto-creation error: " . $e->getMessage() . "</p>";
    echo "</div>";
}

echo "<p><a href='marks/entry.php'>← Back to Marks Entry</a></p>";
?>