<?php
/**
 * Subject Helper Functions
 * Common functions for categorizing and sorting subjects in marksheets and tabulation sheets
 */

/**
 * Group and sort subjects by category:
 * 1. General subjects (Bangla and English first)
 * 2. Group-based subjects
 * 3. 4th subjects
 * 
 * @param array $raw_subjects Array of subjects with id, name, code, group_name, is_general, is_fourth_subject
 * @param PDO $pdo Database connection (optional, for checking 4th subjects if not provided)
 * @param int $class_id Class ID (optional, for checking 4th subjects)
 * @param string $session Session (optional, for checking 4th subjects)
 * @param string $group_name Group name (optional, for checking 4th subjects)
 * @return array Sorted array of subjects
 */
function groupSubjectsWithCategory($raw_subjects, $pdo = null, $class_id = null, $session = null, $group_name = null) {
    $bangla_subjects = [];
    $english_subjects = [];
    $general_subjects = [];
    $group_subjects = [];
    $fourth_subjects = [];
    
    // If 4th subject info is not provided, check for it
    if ($pdo && $class_id && $session) {
        foreach ($raw_subjects as &$subject) {
            if (!isset($subject['is_fourth_subject'])) {
                $stmt_check = $pdo->prepare("
                    SELECT COUNT(*) as count
                    FROM student_subjects ss
                    JOIN students st ON ss.student_id = st.id
                    WHERE ss.subject_id = ? AND ss.is_fourth_subject = 1 
                    AND st.class_id = ? AND st.session = ?
                    " . ($group_name ? "AND LOWER(TRIM(st.group_name)) = LOWER(TRIM(?))" : "") . "
                    LIMIT 1
                ");
                $check_params = [$subject['id'], $class_id, $session];
                if ($group_name) $check_params[] = $group_name;
                $stmt_check->execute($check_params);
                $fourth_check = $stmt_check->fetch();
                $subject['is_fourth_subject'] = ($fourth_check && $fourth_check['count'] > 0) ? 1 : 0;
            }
        }
        unset($subject);
    }
    
    foreach ($raw_subjects as $subject) {
        // Check if this is a 4th subject
        $is_fourth = isset($subject['is_fourth_subject']) && $subject['is_fourth_subject'] == 1;
        
        // Check if this is a general subject (group_name is NULL or empty)
        $is_general = isset($subject['is_general']) && $subject['is_general'] == 1;
        
        // Check if this is a Bangla subject (more precise detection to avoid false positives)
        $is_bangla = false;
        if (stripos($subject['name'], 'বাংলা') !== false) {
            $is_bangla = true;
        } else if (stripos($subject['name'], 'Bangla') !== false && stripos($subject['name'], 'Bangladesh') === false) {
            $is_bangla = true;
        }
        
        // Check if this is an English subject (English or English Grammar)
        $is_english = false;
        if (stripos($subject['name'], 'ইংরেজি') !== false || stripos($subject['name'], 'English') !== false) {
            $is_english = true;
        }
        
        // Categorize subjects
        if ($is_fourth) {
            // 4th subjects go to separate array
            if ($is_bangla) {
                $bangla_subjects[] = $subject;
            } else if ($is_english) {
                $english_subjects[] = $subject;
            } else {
                $fourth_subjects[] = $subject;
            }
        } else if ($is_bangla) {
            $bangla_subjects[] = $subject;
        } else if ($is_english) {
            $english_subjects[] = $subject;
        } else if ($is_general) {
            $general_subjects[] = $subject;
        } else {
            $group_subjects[] = $subject;
        }
    }
    
    // Prepare final subject list in order: General (Bangla/English first) -> Group-based -> 4th subjects
    $grouped_subjects = [];
    
    // 1. Add combined Bangla subject (general subjects first)
    if (count($bangla_subjects) > 1) {
        $grouped_subjects[] = [
            'id' => 'combined_bangla',
            'name' => 'বাংলা(একত্রে)',
            'code' => 'CBAN',
            'is_general' => 1,
            'is_fourth_subject' => 0
        ];
    } else if (count($bangla_subjects) == 1) {
        $grouped_subjects[] = $bangla_subjects[0];
    }
    
    // 2. Add combined English subject (general subjects first)
    if (count($english_subjects) > 1) {
        $grouped_subjects[] = [
            'id' => 'combined_english',
            'name' => 'ইংরেজি(একত্রে)',
            'code' => 'CENG',
            'is_general' => 1,
            'is_fourth_subject' => 0
        ];
    } else if (count($english_subjects) == 1) {
        $grouped_subjects[] = $english_subjects[0];
    }
    
    // 3. Add other general subjects in Jessore Board SSC order
    $ordered_general_subjects = [];

    // Define Jessore Board SSC subject priority order
    $subject_priority = [
        // Core subjects after Bangla/English
        'Math' => 1,
        'Mathematics' => 1,
        'গণিত' => 1,
        'Science' => 2,
        'বিজ্ঞান' => 2,
        'Physics' => 3,
        'পদার্থবিদ্যা' => 3,
        'Chemistry' => 4,
        'রসায়ন' => 4,
        'Biology' => 5,
        'জীববিদ্যা' => 5,
        'Higher Math' => 6,
        'উচ্চতর গণিত' => 6,
        'ICT' => 7,
        'আইসিটি' => 7,
        'Economics' => 8,
        'অর্থনীতি' => 8,
        'Geography' => 9,
        'ভূগোল' => 9,
        'History of Bangladesh' => 10,
        'বাংলাদেশের ইতিহাস' => 10,
        'Bangladesh and World Introduction' => 11,
        'বাংলাদেশ ও বিশ্ব পরিচিতি' => 11,
        'Islam' => 12,
        'ইসলাম' => 12,
        'Physical Edu' => 13,
        'শারীরিক শিক্ষা' => 13,
        'Career Edu' => 14,
        'ক্যারিয়ার শিক্ষা' => 14
    ];

    // Sort general subjects by priority, then by name
    usort($general_subjects, function($a, $b) use ($subject_priority) {
        $a_priority = $subject_priority[$a['name']] ?? 99;
        $b_priority = $subject_priority[$b['name']] ?? 99;

        if ($a_priority != $b_priority) {
            return $a_priority - $b_priority;
        }

        return strcmp($a['name'], $b['name']);
    });

    $grouped_subjects = array_merge($grouped_subjects, $general_subjects);
    
    // 4. Add group-based subjects (sorted by name)
    usort($group_subjects, function($a, $b) {
        return strcmp($a['name'], $b['name']);
    });
    $grouped_subjects = array_merge($grouped_subjects, $group_subjects);
    
    // 5. Add 4th subjects at the end (sorted by name)
    usort($fourth_subjects, function($a, $b) {
        return strcmp($a['name'], $b['name']);
    });
    $grouped_subjects = array_merge($grouped_subjects, $fourth_subjects);
    
    return $grouped_subjects;
}

/**
 * Legacy function for backward compatibility
 * @deprecated Use groupSubjectsWithCategory instead
 */
function groupSubjects($raw_subjects, $pdo = null, $class_id = null, $session = null, $group_name = null) {
    return groupSubjectsWithCategory($raw_subjects, $pdo, $class_id, $session, $group_name);
}

