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

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

try {
    // Get search term if provided
    $searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
    
    if ($searchTerm) {
        // Search across multiple fields - NO LIMIT for search results
        $searchQuery = "%" . $searchTerm . "%";
        $stmt = $db->prepare("
            SELECT 
                id,
                student_id,
                full_name,
                program,
                department,
                grade,
                graduation_date,
                photo_path,
                certificate_id,
                phone,
                email,
                level_name,
                session_name,
                cgpa
            FROM students 
            WHERE 
                full_name LIKE ? OR
                student_id LIKE ? OR
                program LIKE ? OR
                grade LIKE ? OR
                certificate_id LIKE ? OR
                department LIKE ? OR
                email LIKE ? OR
                phone LIKE ?
            ORDER BY full_name
        ");
        $stmt->execute([
            $searchQuery, $searchQuery, $searchQuery, $searchQuery,
            $searchQuery, $searchQuery, $searchQuery, $searchQuery
        ]);
    } else {
        // Get all students (limited to 50 for performance - initial load only)
        $stmt = $db->prepare("
            SELECT 
                id,
                student_id,
                full_name,
                program,
                department,
                grade,
                graduation_date,
                photo_path,
                certificate_id,
                phone,
                email,
                level_name,
                session_name,
                cgpa
            FROM students 
            ORDER BY id DESC 
            LIMIT 50
        ");
        $stmt->execute();
    }
    
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format photo paths and handle base64
    foreach ($students as &$student) {
        if (!empty($student['photo_path'])) {
            // Check if it's a base64 string
            if (strpos($student['photo_path'], 'data:image') === 0) {
                // It's already base64, use it directly for the list (small version)
                // For list view, we might want to use a smaller version or keep as is
                $student['photo_path'] = $student['photo_path'];
            } else if (strpos($student['photo_path'], 'http') === 0) {
                // It's a URL, keep it
                $student['photo_path'] = $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']);
                    $student['photo_path'] = 'data:' . $mimeType . ';base64,' . base64_encode($imageData);
                } else {
                    $student['photo_path'] = 'https://via.placeholder.com/50x50/1a237e/ffffff?text=Photo';
                }
            } else {
                $student['photo_path'] = 'https://via.placeholder.com/50x50/1a237e/ffffff?text=Photo';
            }
        } else {
            $student['photo_path'] = 'https://via.placeholder.com/50x50/1a237e/ffffff?text=Photo';
        }
    }
    
    echo json_encode([
        'success' => true,
        'count' => count($students),
        'students' => $students
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'error' => 'Database error: ' . $e->getMessage(),
        'success' => false
    ]);
}
?>