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

// Simulate the actual marksheet generation process for a specific student
$class_id = 10;
$session = '2025';
$exam_type = 'final';

// Get a specific student (Roll 1)
$stmt = $pdo->prepare("
    SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
    FROM students s
    WHERE s.class_id = ? AND s.status = 'active' AND s.roll_number = 1
");
$stmt->execute([$class_id]);
$student = $stmt->fetch();

if (!$student) {
    die("Student not found");
}

echo "<h2>Actual Marksheet Debug for Student: " . $student['first_name'] . " " . $student['last_name'] . " (Roll: " . $student['roll_number'] . ")</h2>";

// Get all subjects selected by the student
$stmt = $pdo->prepare("
    SELECT ss.subject_id, ss.is_fourth_subject, s.name as subject_name, s.code as subject_code 
    FROM student_subjects ss 
    JOIN subjects s ON ss.subject_id = s.id 
    WHERE ss.student_id = ? AND s.status = 'active' 
    ORDER BY s.name
");
$stmt->execute([$student['id']]);
$all_student_subjects = $stmt->fetchAll();

echo "<h3>All Student Subjects (" . count($all_student_subjects) . " found)</h3>";
echo "<ul>";
foreach ($all_student_subjects as $subject) {
    $is_fourth = ($subject['is_fourth_subject'] ?? false) ? " (4th)" : "";
    echo "<li>" . $subject['subject_name'] . " (" . $subject['subject_code'] . ") (ID: " . $subject['subject_id'] . ")" . $is_fourth . "</li>";
}

// Get results for the student
$stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name, sub.code as subject_code FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND session = ? AND exam_type = ? GROUP BY subject_id) ORDER BY sub.name");
$stmt->execute([$student['id'], $session, $exam_type, $student['id'], $session, $exam_type]);
$results_with_marks = $stmt->fetchAll();

echo "<h3>Results with Marks (" . count($results_with_marks) . " found)</h3>";
echo "<ul>";
foreach ($results_with_marks as $result) {
    echo "<li>" . $result['subject_name'] . " (" . $result['subject_code'] . ") - Grade: " . ($result['grade'] ?? 'N/A') . "</li>";
}
echo "</ul>";

// Create a map of results by subject_id for easy lookup
$results_map = [];
foreach ($results_with_marks as $result) {
    $results_map[$result['subject_id']] = $result;
}

// Create combined results array with all subjects
$results = [];
$has_missing_marks = false; // Track if any subject is missing marks

foreach ($all_student_subjects as $subject) {
    $subject_id = $subject['subject_id'];
    
    // If student has marks for this subject, use the result data
    if (isset($results_map[$subject_id])) {
        // Ensure cq_marks_array and mcq_marks_array are initialized for all subjects
        $result_data = $results_map[$subject_id];
        if (!isset($result_data['cq_marks_array'])) {
            $result_data['cq_marks_array'] = [$result_data['cq_marks']];
        }
        if (!isset($result_data['mcq_marks_array'])) {
            $result_data['mcq_marks_array'] = [$result_data['mcq_marks']];
        }
        // Add the is_fourth_subject flag from the subject data
        $result_data['is_fourth_subject'] = $subject['is_fourth_subject'] ?? false;
        
        $results[] = $result_data;
    } else {
        // If student doesn't have marks, create a placeholder result with 'F' grade
        $placeholder_result = [
            'subject_id' => $subject_id,
            'subject_name' => $subject['subject_name'],
            'subject_code' => $subject['subject_code'],
            'cq_marks' => 0,
            'cq_marks_array' => [0],
            'mcq_marks' => 0,
            'mcq_marks_array' => [0],
            'practical_marks' => 0,
            'assignment_marks' => 0,
            'attendance_marks' => 0,
            'marks_obtained' => 0,
            'full_marks' => 100,
            'pass_marks' => 33,
            'grade' => 'F', // Mark as failed if no marks
            'grade_point' => 0.00,
            'class_max_marks' => 0,
            'is_fourth_subject' => $subject['is_fourth_subject'] ?? false
        ];
        
        $results[] = $placeholder_result;
        $has_missing_marks = true; // Mark that we have missing marks
    }
}

echo "<h3>Final Results Array (" . count($results) . " items)</h3>";
echo "<ul>";
foreach ($results as $result) {
    $is_fourth = ($result['is_fourth_subject'] ?? false) ? " (4th)" : "";
    echo "<li>" . $result['subject_name'] . " (" . $result['subject_code'] . ")" . $is_fourth . " - Grade: " . ($result['grade'] ?? 'N/A') . "</li>";
}
echo "</ul>";

// Process combined subjects
$processed_results = [];
$original_bangla_results = [];
$original_english_results = [];
$other_results = [];
$combined_subject_ids = [];

// First, collect original Bangla and English results
foreach ($results as $result) {
    // Check if this is a Bangla subject
    if ((stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) && strpos($result['subject_name'], 'একত্রে') === false) {
        $original_bangla_results[] = $result;
    }
    // Check if this is an English subject
    elseif ((stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) && strpos($result['subject_name'], 'একত্রে') === false) {
        $original_english_results[] = $result;
    } else {
        $other_results[] = $result;
    }
}

echo "<h3>Separated Results:</h3>";
echo "<p>Bangla subjects: " . count($original_bangla_results) . "</p>";
echo "<p>English subjects: " . count($original_english_results) . "</p>";
echo "<p>Other subjects: " . count($other_results) . "</p>";

// Process Bangla subjects as a combined subject
$combined_bangla = null;
if (!empty($original_bangla_results)) {
    // Combine Bangla subjects into one subject
    $combined_bangla = [
        'subject_name' => 'বাংলা(একত্রে)',
        'subject_code' => 'CBAN',
        'subject_id' => 'combined_bangla',
        'cq_marks' => 0,
        'cq_marks_array' => [],
        'mcq_marks' => 0,
        'mcq_marks_array' => [],
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Consider only first 2 Bangla papers for CQ/MCQ averaging
    $considered_results = array_slice($original_bangla_results, 0, 2);

    // Sum up other marks from all Bangla subjects
    foreach ($original_bangla_results as $result) {
        $combined_bangla['practical_marks'] += $result['practical_marks'];
        $combined_bangla['assignment_marks'] += $result['assignment_marks'];
        $combined_bangla['attendance_marks'] += $result['attendance_marks'];
        $combined_bangla['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined_bangla['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // Average CQ and MCQ based on first 2 papers
    $cq_total = 0;
    $mcq_total = 0;
    foreach ($considered_results as $result) {
        $cq_total += $result['cq_marks'];
        $combined_bangla['cq_marks_array'][] = $result['cq_marks'];
        $mcq_total += $result['mcq_marks'];
        $combined_bangla['mcq_marks_array'][] = $result['mcq_marks'];
    }
    
    $count = count($considered_results);
    if ($count > 0) {
        $combined_bangla['cq_marks'] = $cq_total / $count;
        $combined_bangla['mcq_marks'] = $mcq_total / $count;
    }
    
    // Calculate obtained marks as sum of averaged CQ and MCQ
    $combined_bangla['marks_obtained'] = $combined_bangla['cq_marks'] + $combined_bangla['mcq_marks'];
    
    // Average full and pass marks over total Bangla results
    $total_count = count($original_bangla_results);
    if ($total_count > 0) {
        $combined_bangla['full_marks'] = $combined_bangla['full_marks'] / $total_count;
        $combined_bangla['pass_marks'] = $combined_bangla['pass_marks'] / $total_count;
    }
    
    // Check if any of the original Bangla subjects is a fourth subject
    $is_fourth_subject = false;
    foreach ($original_bangla_results as $bangla_result) {
        if ($bangla_result['is_fourth_subject'] ?? false) {
            $is_fourth_subject = true;
            break;
        }
    }
    $combined_bangla['is_fourth_subject'] = $is_fourth_subject;
    
    $processed_results[] = $combined_bangla;
}

// Process English subjects as a combined subject
$combined_english = null;
if (!empty($original_english_results)) {
    // Combine English subjects into one subject
    $combined_english = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        'subject_code' => 'CENG',
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [],
        'mcq_marks' => 0,
        'mcq_marks_array' => [],
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Sum up the marks from all English subjects
    foreach ($original_english_results as $result) {
        $combined_english['cq_marks'] += $result['cq_marks'];
        $combined_english['cq_marks_array'][] = $result['cq_marks'];
        $combined_english['mcq_marks'] += $result['mcq_marks'];
        $combined_english['mcq_marks_array'][] = $result['mcq_marks'];
        $combined_english['practical_marks'] += $result['practical_marks'];
        $combined_english['assignment_marks'] += $result['assignment_marks'];
        $combined_english['attendance_marks'] += $result['attendance_marks'];
        $combined_english['marks_obtained'] += $result['marks_obtained'];
        $combined_english['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined_english['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // Average the marks for proper grading
    $count = count($original_english_results);
    if ($count > 0) {
        $combined_english['cq_marks'] = $combined_english['cq_marks'] / $count;
        $combined_english['mcq_marks'] = $combined_english['mcq_marks'] / $count;
        // For English: obtained marks = CQ average + MCQ average
        $combined_english['marks_obtained'] = $combined_english['cq_marks'] + $combined_english['mcq_marks'];
        $combined_english['full_marks'] = $combined_english['full_marks'] / $count;
        $combined_english['pass_marks'] = $combined_english['pass_marks'] / $count;
    }
    
    // Check if any of the original English subjects is a fourth subject
    $is_fourth_subject = false;
    foreach ($original_english_results as $english_result) {
        if ($english_result['is_fourth_subject'] ?? false) {
            $is_fourth_subject = true;
            break;
        }
    }
    $combined_english['is_fourth_subject'] = $is_fourth_subject;
    
    $processed_results[] = $combined_english;
}

// Collect subject IDs that have been combined to avoid duplicates
foreach ($original_bangla_results as $bangla_result) {
    $combined_subject_ids[] = $bangla_result['subject_id'];
}
foreach ($original_english_results as $english_result) {
    $combined_subject_ids[] = $english_result['subject_id'];
}

// Process other subjects (exclude combined subjects)
foreach ($other_results as $result) {
    // Skip subjects that have been combined
    if (in_array($result['subject_id'], $combined_subject_ids)) {
        continue;
    }
    $processed_results[] = $result;
}

echo "<h3>Processed Results (" . count($processed_results) . " items)</h3>";
echo "<ul>";
foreach ($processed_results as $result) {
    $is_fourth = ($result['is_fourth_subject'] ?? false) ? " (4th)" : "";
    echo "<li>" . $result['subject_name'] . " (" . ($result['subject_code'] ?? 'N/A') . ")" . $is_fourth . " - Grade: " . ($result['grade'] ?? 'N/A') . "</li>";
}
echo "</ul>";

// Separate fourth subjects from regular subjects
$regular_subjects = array_filter($processed_results, function($result) {
    // Check if is_fourth_subject is set and is true
    $isFourth = $result['is_fourth_subject'] ?? false;
    return !($isFourth === true || $isFourth === 1 || $isFourth === '1' || $isFourth === 'true');
});

$fourth_subjects_only = array_filter($processed_results, function($result) {
    // Check if is_fourth_subject is set and is true
    $isFourth = $result['is_fourth_subject'] ?? false;
    return ($isFourth === true || $isFourth === 1 || $isFourth === '1' || $isFourth === 'true');
});

echo "<h3>Final Separation:</h3>";
echo "<p>Regular subjects: " . count($regular_subjects) . "</p>";
echo "<p>Fourth subjects: " . count($fourth_subjects_only) . "</p>";

// Total subjects that would be displayed
$total_displayed_subjects = count($regular_subjects) + count($fourth_subjects_only);
echo "<h3>Total Displayed Subjects: " . $total_displayed_subjects . "</h3>";

?>