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

function convert_to_utf8($string) {
    // Simplified version for testing
    return $string;
}

function get_class_id_by_name($pdo, $class_name) {
    $stmt = $pdo->prepare("SELECT id FROM classes WHERE name = ?");
    $stmt->execute([$class_name]);
    $result = $stmt->fetchColumn();
    return $result;
}

function get_subject_ids_by_codes($pdo, $subject_codes_str) {
    error_log("DEBUG: Processing subject codes string: " . $subject_codes_str);
    
    if (empty($subject_codes_str)) return [];
    
    // Split by comma to get individual code segments
    $segments = array_map('trim', explode(',', $subject_codes_str));
    error_log("DEBUG: Segments after comma split: " . json_encode($segments));
    
    // Process each segment to handle both individual codes and ranges
    $all_codes = [];
    foreach ($segments as $segment) {
        error_log("DEBUG: Processing segment: " . $segment);
        if (strpos($segment, '_') !== false) {
            error_log("DEBUG: Found underscore, treating as range");
            // Handle range notation (e.g., "101_102" or "253_254")
            $parts = explode('_', $segment);
            error_log("DEBUG: Parts after underscore split: " . json_encode($parts));
            if (count($parts) == 2) {
                $start = (int)$parts[0];
                $end = (int)$parts[1];
                error_log("DEBUG: Range from $start to $end");
                // Add all codes in the range
                for ($i = $start; $i <= $end; $i++) {
                    $all_codes[] = (string)$i;
                    error_log("DEBUG: Adding code to all_codes: " . (string)$i);
                }
            } else {
                // If not a proper range, treat as individual code
                error_log("DEBUG: Not a proper range, treating as individual code");
                $all_codes[] = $segment;
            }
        } else {
            error_log("DEBUG: No underscore, treating as individual code");
            // Individual code
            $all_codes[] = $segment;
        }
    }
    
    // Remove duplicates
    $all_codes = array_unique($all_codes);
    error_log("DEBUG: All codes after deduplication: " . json_encode($all_codes));
    
    if (empty($all_codes)) return [];
    
    $placeholders = rtrim(str_repeat('?,', count($all_codes)), ',');
    
    $stmt = $pdo->prepare("SELECT id FROM subjects WHERE code IN ({$placeholders})");
    $stmt->execute($all_codes);
    $results = $stmt->fetchAll(PDO::FETCH_COLUMN);
    error_log("DEBUG: Subject lookup results: " . json_encode($results));
    return $results;
}

// Simulate processing the CSV data
echo "=== Simulating Upload Process ===\n\n";

// Sample data from CSV
$student_data = [
    'first_name' => 'Multi',
    'last_name' => 'Range',
    'father_name' => 'Test',
    'mother_name' => 'Parent',
    'email' => 'multi@test.com',
    'phone' => '1234567890',
    'address' => 'Test Address',
    'date_of_birth' => '2010-01-15',
    'gender' => 'male',
    'class_name' => 'Eight',
    'session' => '2025',
    'group_name' => 'Science',
    'roll_number' => '777',
    'admission_date' => '2025-01-10',
    'guardian_name' => 'Guardian',
    'guardian_phone' => '1234567890',
    'guardian_email' => 'guardian@test.com',
    'guardian_address' => 'Test Guardian',
    'subject_codes' => '101_102,107_108'
];

echo "Processing student: {$student_data['first_name']} {$student_data['last_name']}\n";
echo "Subject codes: {$student_data['subject_codes']}\n\n";

// Validate required fields
if (empty($student_data['first_name']) || empty($student_data['class_name']) || empty($student_data['session']) || empty($student_data['roll_number'])) {
    echo "ERROR: Required fields missing\n";
    exit(1);
}

// Get Class ID
$class_id = get_class_id_by_name($pdo, $student_data['class_name']);
if (!$class_id) {
    echo "ERROR: Class '{$student_data['class_name']}' not found\n";
    exit(1);
}
echo "Class ID: $class_id\n";

// Check for duplicate roll number (simulated)
$stmt_check = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id = ? AND session = ? AND COALESCE(group_name, '') = ? AND roll_number = ? AND status = 'active'");
$stmt_check->execute([$class_id, $student_data['session'], $student_data['group_name'] ?: '', $student_data['roll_number']]);
if ($stmt_check->fetchColumn() > 0) {
    echo "ERROR: Duplicate roll number\n";
    exit(1);
}

// Generate student ID
$student_id_generated = 'SIM' . time();
echo "Generated student ID: $student_id_generated\n";

// Process subjects
echo "\n--- Processing Subjects ---\n";
$subject_ids = get_subject_ids_by_codes($pdo, $student_data['subject_codes']);

echo "Found " . count($subject_ids) . " subject IDs: " . json_encode($subject_ids) . "\n";

if (!empty($subject_ids)) {
    echo "\nInserting subjects for student:\n";
    foreach ($subject_ids as $subject_id) {
        echo "  Subject ID: $subject_id\n";
    }
} else {
    echo "No subjects found for the given codes\n";
}

echo "\nSimulation completed successfully!\n";
?>