<?php
header('Content-Type: application/json');
require_once '../config/database.php';

$database = Database::getInstance();
$db = $database->getConn();

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['error' => 'Invalid student ID']);
    exit;
}

$studentId = intval($_GET['id']);

try {
    // Fetch student data with all columns from the students table
    $stmt = $db->prepare("
        SELECT 
            id,
            student_id,
            app_num,
            full_name,
            surname,
            firstname,
            othername,
            program,
            department,
            grade,
            cgpa,
            session_name,
            level_name,
            semester,
            phone,
            email,
            amount_paid,
            receipt_no,
            payment_date,
            graduation_date,
            photo_path,
            certificate_id,
            created_at,
            last_updated,
            data_source,
            upload_batch,
            merged_from_students_data,
            merged_from_certificate_data
        FROM students 
        WHERE id = ?
    ");
    $stmt->execute([$studentId]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($student) {
        // Check if photo_path is base64 encoded
        $photoUrl = 'https://via.placeholder.com/120x120/1a237e/ffffff?text=Photo';
        
        if (!empty($student['photo_path'])) {
            // Check if it's a base64 string
            if (strpos($student['photo_path'], 'data:image') === 0) {
                // It's a base64 image, use it directly
                $photoUrl = $student['photo_path'];
            } else if (strpos($student['photo_path'], 'http') === 0) {
                // It's a URL
                $photoUrl = $student['photo_path'];
            } else if (file_exists($student['photo_path'])) {
                // It's a local file path, convert to base64
                $imageData = file_get_contents($student['photo_path']);
                if ($imageData !== false) {
                    $mimeType = mime_content_type($student['photo_path']);
                    $photoUrl = 'data:' . $mimeType . ';base64,' . base64_encode($imageData);
                }
            }
        }
        
        // Format the response to match what index.php expects
        $formattedStudent = [
            'id' => $student['id'],
            'student_id' => $student['student_id'],
            'full_name' => $student['full_name'],
            'program' => $student['program'],
            'department' => $student['department'],
            'grade' => $student['grade'],
            'cgpa' => $student['cgpa'],
            'graduation_date' => $student['graduation_date'],
            'photo_path' => $photoUrl, // This now contains base64 or URL
            'photo_base64' => strpos($photoUrl, 'data:image') === 0 ? $photoUrl : null,
            'certificate_id' => $student['certificate_id'],
            'phone' => $student['phone'],
            'email' => $student['email'],
            'session_name' => $student['session_name'],
            'level_name' => $student['level_name'],
            'semester' => $student['semester'],
            
            // For backward compatibility with existing code
            'certificate_type' => $student['certificate_id'] ? 
                (strpos($student['certificate_id'], 'HND') !== false ? 'Higher National Diploma' : 'National Diploma') : 
                'National Diploma',
            'qr_code_path' => null // This will be generated separately
        ];
        
        echo json_encode($formattedStudent);
    } else {
        echo json_encode(['error' => 'Student not found']);
    }
} catch (PDOException $e) {
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>