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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

echo "<h1>🔍 Debug Marksheet Form Issues</h1>";

// Get parameters
$student_id = $_GET['student_id'] ?? '';
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? '';

echo "<div style='background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px;'>";
echo "<h3>📋 Current Parameters:</h3>";
echo "<p><strong>Student ID:</strong> " . ($student_id ?: 'Not set') . "</p>";
echo "<p><strong>Session:</strong> " . ($session ?: 'Not set') . "</p>";
echo "<p><strong>Exam Type:</strong> " . ($exam_type ?: 'Not set') . "</p>";
echo "</div>";

// Test 1: Check if we have students with results
echo "<h2>🧪 Test 1: Students with Results</h2>";
$stmt = $pdo->query("
    SELECT DISTINCT s.id, s.student_id, s.first_name, s.last_name, 
           c.name as class_name, s.group_name,
           COUNT(r.id) as result_count
    FROM students s
    JOIN classes c ON s.class_id = c.id
    LEFT JOIN results r ON s.id = r.student_id AND r.session = '2024' AND r.exam_type = 'midterm'
    WHERE s.status = 'active'
    GROUP BY s.id
    HAVING result_count > 0
    ORDER BY s.id
    LIMIT 10
");
$students_with_results = $stmt->fetchAll();

echo "<p><strong>Found:</strong> " . count($students_with_results) . " students with 2024 midterm results</p>";

if (!empty($students_with_results)) {
    echo "<table border='1' style='border-collapse: collapse; width: 100%; margin-bottom: 20px;'>";
    echo "<tr style='background: #f8f9fa;'>";
    echo "<th>DB ID</th><th>Student ID</th><th>Name</th><th>Class</th><th>Group</th><th>Results</th><th>Test Links</th>";
    echo "</tr>";
    
    foreach ($students_with_results as $student) {
        echo "<tr>";
        echo "<td><strong>{$student['id']}</strong></td>";
        echo "<td>{$student['student_id']}</td>";
        echo "<td>{$student['first_name']} {$student['last_name']}</td>";
        echo "<td>{$student['class_name']}</td>";
        echo "<td>{$student['group_name']}</td>";
        echo "<td>{$student['result_count']}</td>";
        echo "<td>";
        echo "<a href='reports/marksheet.php?student_id={$student['id']}&session=2024&exam_type=midterm&debug=1' style='background: #28a745; color: white; padding: 2px 6px; text-decoration: none; border-radius: 3px; font-size: 11px; margin: 1px;'>Debug</a> ";
        echo "<a href='reports/marksheet.php?student_id={$student['id']}&session=2024&exam_type=midterm' style='background: #007bff; color: white; padding: 2px 6px; text-decoration: none; border-radius: 3px; font-size: 11px; margin: 1px;'>View</a>";
        echo "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "<div style='background: #f8d7da; padding: 15px; border: 1px solid #dc3545; border-radius: 5px;'>";
    echo "<p>❌ No students found with 2024 midterm results!</p>";
    echo "</div>";
}

// Test 2: Check specific student if provided
if ($student_id) {
    echo "<hr>";
    echo "<h2>🧪 Test 2: Specific Student Check (ID: $student_id)</h2>";
    
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name 
        FROM students s 
        LEFT JOIN classes c ON s.class_id = c.id 
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if ($student) {
        echo "<div style='background: #d1edff; padding: 15px; border: 1px solid #0d6efd; border-radius: 5px; margin-bottom: 15px;'>";
        echo "<h4>✅ Student Found:</h4>";
        echo "<p><strong>Name:</strong> {$student['first_name']} {$student['last_name']}</p>";
        echo "<p><strong>Class:</strong> {$student['class_name']}</p>";
        echo "<p><strong>Group:</strong> {$student['group_name']}</p>";
        echo "<p><strong>Status:</strong> {$student['status']}</p>";
        echo "</div>";
        
        // Check results for this student
        $stmt = $pdo->prepare("
            SELECT r.*, sub.name as subject_name 
            FROM results r 
            JOIN subjects sub ON r.subject_id = sub.id 
            WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
            ORDER BY sub.name
        ");
        $stmt->execute([$student_id, $session, $exam_type]);
        $results = $stmt->fetchAll();
        
        echo "<h4>📊 Results for {$session} {$exam_type}: " . count($results) . " subjects</h4>";
        
        if (!empty($results)) {
            echo "<table border='1' style='border-collapse: collapse; width: 100%; margin-bottom: 20px;'>";
            echo "<tr style='background: #f8f9fa;'>";
            echo "<th>Subject</th><th>CQ</th><th>MCQ</th><th>Practical</th><th>Total</th><th>Grade</th>";
            echo "</tr>";
            
            $bangla_found = false;
            $duplicate_subjects = [];
            $subject_counts = [];
            
            foreach ($results as $result) {
                $subject_name = $result['subject_name'];
                
                // Check for Bangla
                if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'bangla') !== false) {
                    $bangla_found = true;
                }
                
                // Check for duplicates
                if (!isset($subject_counts[$subject_name])) {
                    $subject_counts[$subject_name] = 0;
                }
                $subject_counts[$subject_name]++;
                
                if ($subject_counts[$subject_name] > 1) {
                    $duplicate_subjects[] = $subject_name;
                }
                
                $row_style = '';
                if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'bangla') !== false) {
                    $row_style = 'style="background: #fff3cd;"'; // Highlight Bangla
                } elseif ($subject_counts[$subject_name] > 1) {
                    $row_style = 'style="background: #ffeeee;"'; // Highlight duplicates
                }
                
                echo "<tr $row_style>";
                echo "<td>{$subject_name}</td>";
                echo "<td>{$result['cq_marks']}</td>";
                echo "<td>{$result['mcq_marks']}</td>";
                echo "<td>{$result['practical_marks']}</td>";
                echo "<td>{$result['marks_obtained']}</td>";
                echo "<td>{$result['grade']}</td>";
                echo "</tr>";
            }
            echo "</table>";
            
            // Analysis
            echo "<div style='margin-bottom: 20px;'>";
            if ($bangla_found) {
                echo "<div style='background: #d1edff; padding: 10px; border: 1px solid #0d6efd; border-radius: 5px; margin-bottom: 10px;'>";
                echo "✅ <strong>বাংলা বিষয় পাওয়া গেছে!</strong>";
                echo "</div>";
            } else {
                echo "<div style='background: #f8d7da; padding: 10px; border: 1px solid #dc3545; border-radius: 5px; margin-bottom: 10px;'>";
                echo "❌ <strong>বাংলা বিষয় পাওয়া যায়নি!</strong>";
                echo "</div>";
            }
            
            if (!empty($duplicate_subjects)) {
                echo "<div style='background: #fff3cd; padding: 10px; border: 1px solid #ffc107; border-radius: 5px; margin-bottom: 10px;'>";
                echo "⚠️ <strong>Duplicate বিষয়:</strong> " . implode(', ', array_unique($duplicate_subjects));
                echo "</div>";
            } else {
                echo "<div style='background: #d1edff; padding: 10px; border: 1px solid #0d6efd; border-radius: 5px; margin-bottom: 10px;'>";
                echo "✅ <strong>কোন duplicate বিষয় নেই!</strong>";
                echo "</div>";
            }
            echo "</div>";
            
        } else {
            echo "<div style='background: #f8d7da; padding: 15px; border: 1px solid #dc3545; border-radius: 5px;'>";
            echo "<p>❌ No results found for this student in {$session} {$exam_type}!</p>";
            echo "</div>";
        }
        
    } else {
        echo "<div style='background: #f8d7da; padding: 15px; border: 1px solid #dc3545; border-radius: 5px;'>";
        echo "<p>❌ Student not found with ID: $student_id</p>";
        echo "</div>";
    }
}

// Test 3: Check marksheet query logic
if ($student_id && $session && $exam_type) {
    echo "<hr>";
    echo "<h2>🧪 Test 3: Marksheet Query Logic Test</h2>";
    
    // Test the exact query from marksheet.php
    $stmt = $pdo->prepare("
        SELECT r.*, sub.name as subject_name, sub.code as subject_code
        FROM results r
        JOIN subjects sub ON r.subject_id = sub.id
        WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
    ");
    $stmt->execute([$student_id, $session, $exam_type]);
    $all_results = $stmt->fetchAll();
    
    echo "<p><strong>Raw query results:</strong> " . count($all_results) . "</p>";
    
    // Matrix approach (like in marksheet.php)
    $results_matrix = [];
    foreach ($all_results as $result) {
        $results_matrix[$result['subject_id']] = $result;
    }
    
    $unique_results = array_values($results_matrix);
    usort($unique_results, function($a, $b) {
        return strcmp($a['subject_name'], $b['subject_name']);
    });
    
    echo "<p><strong>After matrix deduplication:</strong> " . count($unique_results) . "</p>";
    
    echo "<h4>Final Results (as shown in marksheet):</h4>";
    echo "<table border='1' style='border-collapse: collapse; width: 100%; margin-bottom: 20px;'>";
    echo "<tr style='background: #f8f9fa;'>";
    echo "<th>Subject ID</th><th>Subject Name</th><th>Total</th><th>Grade</th>";
    echo "</tr>";
    
    $final_bangla_found = false;
    foreach ($unique_results as $result) {
        if (stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'bangla') !== false) {
            $final_bangla_found = true;
            $row_style = 'style="background: #fff3cd;"';
        } else {
            $row_style = '';
        }
        
        echo "<tr $row_style>";
        echo "<td>{$result['subject_id']}</td>";
        echo "<td>{$result['subject_name']}</td>";
        echo "<td>{$result['marks_obtained']}</td>";
        echo "<td>{$result['grade']}</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    if ($final_bangla_found) {
        echo "<div style='background: #d1edff; padding: 10px; border: 1px solid #0d6efd; border-radius: 5px;'>";
        echo "✅ <strong>বাংলা বিষয় final marksheet এ আছে!</strong>";
        echo "</div>";
    } else {
        echo "<div style='background: #f8d7da; padding: 10px; border: 1px solid #dc3545; border-radius: 5px;'>";
        echo "❌ <strong>বাংলা বিষয় final marksheet এ নেই!</strong>";
        echo "</div>";
    }
}

// Quick test form
echo "<hr>";
echo "<h2>🧪 Quick Test Form</h2>";
echo "<form method='GET' style='background: #f8f9fa; padding: 20px; border-radius: 5px;'>";
echo "<div style='display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 15px; align-items: end;'>";
echo "<div>";
echo "<label>Student ID:</label>";
echo "<input type='number' name='student_id' value='$student_id' class='form-control' placeholder='e.g., 123'>";
echo "</div>";
echo "<div>";
echo "<label>Session:</label>";
echo "<input type='text' name='session' value='$session' class='form-control' placeholder='e.g., 2024'>";
echo "</div>";
echo "<div>";
echo "<label>Exam Type:</label>";
echo "<input type='text' name='exam_type' value='$exam_type' class='form-control' placeholder='e.g., midterm'>";
echo "</div>";
echo "<div>";
echo "<button type='submit' class='btn btn-primary'>🧪 Test</button>";
echo "</div>";
echo "</div>";
echo "</form>";

echo "<div style='text-align: center; margin: 30px 0;'>";
echo "<a href='reports/marksheet.php' style='background: #6f42c1; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin: 5px;'>📄 Go to Marksheet</a>";
echo "<a href='quick_student_check.php' style='background: #17a2b8; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin: 5px;'>🔍 Student Check</a>";
echo "</div>";

echo "<p><a href='reports/marksheet.php'>← Back to Marksheet</a></p>";
?>