<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
require_once '../config/database.php';

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

try {
    $searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';
    
    if (empty($searchTerm)) {
        echo json_encode([
            'success' => false,
            'message' => 'Search term is required',
            'students' => []
        ]);
        exit;
    }
    
    // Prepare SQL query to search across multiple fields without LIMIT
    $sql = "SELECT * FROM students WHERE 
            full_name LIKE :search OR
            student_id LIKE :search OR
            program LIKE :search OR
            grade LIKE :search OR
            certificate_id LIKE :search OR
            department LIKE :search OR
            email LIKE :search OR
            phone LIKE :search
            ORDER BY full_name ASC";
    
    $stmt = $db->prepare($sql);
    $searchPattern = "%{$searchTerm}%";
    $stmt->bindParam(':search', $searchPattern, PDO::PARAM_STR);
    $stmt->execute();
    
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process photo paths if needed
    foreach ($students as &$student) {
        if (!empty($student['photo_path'])) {
            // Handle base64 or file path
            if (strpos($student['photo_path'], 'data:image') === 0) {
                // It's already a base64 data URL
                continue;
            } elseif (file_exists($student['photo_path'])) {
                // Convert file to base64
                $imageData = file_get_contents($student['photo_path']);
                $mimeType = mime_content_type($student['photo_path']);
                $student['photo_path'] = 'data:' . $mimeType . ';base64,' . $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';
        }
    }
    
    echo json_encode([
        'success' => true,
        'students' => $students,
        'count' => count($students)
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage(),
        'students' => []
    ]);
}
?>