<?php
session_start();
require_once 'config/database.php';

echo "<h1>🔍 Debug Marks Save Issue</h1>";

// Check recent results
echo "<h2>1. Recent Results in Database</h2>";
try {
    $stmt = $pdo->query("SELECT * FROM results ORDER BY created_at DESC LIMIT 10");
    $recent_results = $stmt->fetchAll();
    
    if (empty($recent_results)) {
        echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
        echo "<p>❌ No results found in database!</p>";
        echo "</div>";
    } else {
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr style='background: #f8f9fa;'>";
        echo "<th>ID</th><th>Student ID</th><th>Subject ID</th><th>Session</th><th>Exam Type</th>";
        echo "<th>Total Marks</th><th>Grade</th><th>Created At</th>";
        echo "</tr>";
        
        foreach ($recent_results as $result) {
            echo "<tr>";
            echo "<td>{$result['id']}</td>";
            echo "<td>{$result['student_id']}</td>";
            echo "<td>{$result['subject_id']}</td>";
            echo "<td>{$result['session']}</td>";
            echo "<td>{$result['exam_type']}</td>";
            echo "<td>{$result['marks_obtained']}</td>";
            echo "<td>{$result['grade']}</td>";
            echo "<td>{$result['created_at']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
} catch (Exception $e) {
    echo "<p>Error: " . $e->getMessage() . "</p>";
}

// Test insert
echo "<h2>2. Test Direct Insert</h2>";
try {
    // Get a valid student ID
    $stmt = $pdo->query("SELECT id FROM students LIMIT 1");
    $student = $stmt->fetch();
    
    if ($student) {
        $test_student_id = $student['id'];
        
        echo "<p>Testing with Student ID: $test_student_id</p>";
        
        $test_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, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $result = $test_stmt->execute([
            $test_student_id, 1, '2024', '', 'test', 45.5, 20.0, 15.0, 10.5, 0.0, 0.0, 'B'
        ]);
        
        if ($result) {
            echo "<div style='background: #d4edda; padding: 15px; border-radius: 5px;'>";
            echo "<p>✅ Direct insert successful!</p>";
            echo "</div>";
            
            // Clean up
            $pdo->prepare("DELETE FROM results WHERE student_id = ? AND exam_type = 'test' AND marks_obtained = 45.5")->execute([$test_student_id]);
        } else {
            echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
            echo "<p>❌ Direct insert failed!</p>";
            echo "</div>";
        }
    } else {
        echo "<p>No students found in database!</p>";
    }
    
} catch (Exception $e) {
    echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
    echo "<p>❌ Test insert error: " . $e->getMessage() . "</p>";
    echo "</div>";
}

// Check error logs
echo "<h2>3. Recent Error Logs</h2>";
$error_log_path = "D:\\xampp\\apache\\logs\\error.log";
if (file_exists($error_log_path)) {
    $lines = file($error_log_path);
    $recent_lines = array_slice($lines, -20); // Last 20 lines
    
    echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px; max-height: 300px; overflow-y: scroll;'>";
    echo "<pre>";
    foreach ($recent_lines as $line) {
        if (strpos($line, 'marks') !== false || strpos($line, 'student') !== false || strpos($line, 'results') !== false) {
            echo htmlspecialchars($line);
        }
    }
    echo "</pre>";
    echo "</div>";
} else {
    echo "<p>Error log file not found at: $error_log_path</p>";
}

// Simulate marks submission
echo "<h2>4. Simulate Marks Submission</h2>";
echo "<form method='POST' action=''>";
echo "<input type='hidden' name='test_submission' value='1'>";
echo "<button type='submit' style='background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px;'>Test Marks Submission</button>";
echo "</form>";

if (isset($_POST['test_submission'])) {
    echo "<h3>Testing Marks Submission Process</h3>";
    
    // Get valid IDs
    $stmt = $pdo->query("SELECT id FROM students LIMIT 1");
    $student = $stmt->fetch();
    $stmt = $pdo->query("SELECT id FROM subjects LIMIT 1");
    $subject = $stmt->fetch();
    
    if ($student && $subject) {
        $student_id = $student['id'];
        $subject_id = $subject['id'];
        $session = '2024';
        $exam_type = 'test';
        $group_name = '';
        
        echo "<p>Using: Student ID: $student_id, Subject ID: $subject_id</p>";
        
        // Check/create mark distribution
        $stmt = $pdo->prepare("SELECT * FROM mark_distributions WHERE subject_id = ? AND class_id = 1 AND session = ? AND exam_type = ?");
        $stmt->execute([$subject_id, $session, $exam_type]);
        $mark_distribution = $stmt->fetch();
        
        if (!$mark_distribution) {
            echo "<p>Creating mark distribution...</p>";
            $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)
                VALUES (?, 1, ?, ?, 20, 15, 10, 5, 0, 50, 20)
            ");
            $create_stmt->execute([$subject_id, $session, $exam_type]);
            
            $stmt->execute([$subject_id, $session, $exam_type]);
            $mark_distribution = $stmt->fetch();
        }
        
        if ($mark_distribution) {
            echo "<p>Mark distribution found/created</p>";
            
            // Test marks save
            try {
                $pdo->beginTransaction();
                
                $cq_marks = 18.0;
                $mcq_marks = 12.0;
                $practical_marks = 8.0;
                $assignment_marks = 4.0;
                $attendance_marks = 0.0;
                $total_marks = (float)$cq_marks + (float)$mcq_marks + (float)$practical_marks + (float)$assignment_marks + (float)$attendance_marks;
                $grade = 'B';
                
                $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
                ");
                
                $result = $stmt->execute([
                    $student_id, $subject_id, $session, $group_name, $exam_type, $total_marks,
                    $cq_marks, $mcq_marks, $practical_marks, $assignment_marks, $attendance_marks, $grade
                ]);
                
                if ($result) {
                    $pdo->commit();
                    echo "<div style='background: #d4edda; padding: 15px; border-radius: 5px;'>";
                    echo "<p>✅ Test marks submission successful!</p>";
                    echo "<p>Total marks: $total_marks, Grade: $grade</p>";
                    echo "</div>";
                    
                    // Verify
                    $verify_stmt = $pdo->prepare("SELECT * FROM results WHERE student_id = ? AND subject_id = ? AND session = ? AND exam_type = ?");
                    $verify_stmt->execute([$student_id, $subject_id, $session, $exam_type]);
                    $saved_result = $verify_stmt->fetch();
                    
                    if ($saved_result) {
                        echo "<div style='background: #e7f3ff; padding: 15px; border-radius: 5px;'>";
                        echo "<p><strong>Verification:</strong> Data found in database</p>";
                        echo "<p>ID: {$saved_result['id']}, Marks: {$saved_result['marks_obtained']}, Grade: {$saved_result['grade']}</p>";
                        echo "</div>";
                    } else {
                        echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
                        echo "<p>❌ Verification failed: Data not found in database!</p>";
                        echo "</div>";
                    }
                } else {
                    $pdo->rollBack();
                    echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
                    echo "<p>❌ Test marks submission failed!</p>";
                    echo "</div>";
                }
                
            } catch (Exception $e) {
                $pdo->rollBack();
                echo "<div style='background: #f8d7da; padding: 15px; border-radius: 5px;'>";
                echo "<p>❌ Error during test submission: " . $e->getMessage() . "</p>";
                echo "</div>";
            }
        } else {
            echo "<p>❌ Could not create mark distribution</p>";
        }
    } else {
        echo "<p>❌ No valid student or subject found</p>";
    }
}

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