<?php
/**
 * Search API
 * Unified search across studies, researchers, publications, institutions
 */

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $db = getDB();
    
    $query = isset($_GET['q']) ? sanitize($_GET['q']) : '';
    $type = isset($_GET['type']) ? sanitize($_GET['type']) : 'all'; // all, studies, researchers, publications, institutions
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
    
    if (empty($query)) {
        echo json_encode(['success' => false, 'message' => 'Search query required']);
        exit;
    }
    
    $results = [];
    $searchTerm = "%$query%";
    
    // Search Studies
    if ($type === 'all' || $type === 'studies') {
        $stmt = $db->prepare("
            SELECT 'study' as type, id, title, description, status, created_at
            FROM studies
            WHERE (title LIKE ? OR description LIKE ? OR keywords LIKE ?)
            AND status = 'active'
            ORDER BY created_at DESC
            LIMIT ?
        ");
        $stmt->execute([$searchTerm, $searchTerm, $searchTerm, $limit]);
        $results['studies'] = $stmt->fetchAll();
    }
    
    // Search Researchers
    if ($type === 'all' || $type === 'researchers') {
        $stmt = $db->prepare("
            SELECT 'researcher' as type, u.id, u.first_name, u.last_name, 
                   rp.specialization, rp.bio, i.name as institution_name
            FROM users u
            LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
            LEFT JOIN institutions i ON rp.institution_id = i.id
            WHERE (u.first_name LIKE ? OR u.last_name LIKE ? OR rp.bio LIKE ? OR rp.specialization LIKE ?)
            AND u.status = 'active'
            AND u.role_id = ?
            ORDER BY u.created_at DESC
            LIMIT ?
        ");
        $stmt->execute([$searchTerm, $searchTerm, $searchTerm, $searchTerm, ROLE_RESEARCHER, $limit]);
        $results['researchers'] = $stmt->fetchAll();
    }
    
    // Search Publications
    if ($type === 'all' || $type === 'publications') {
        $stmt = $db->prepare("
            SELECT 'publication' as type, id, title, abstract, journal, publication_date, doi
            FROM publications
            WHERE (title LIKE ? OR abstract LIKE ? OR journal LIKE ? OR keywords LIKE ?)
            AND status = 'published'
            ORDER BY publication_date DESC
            LIMIT ?
        ");
        $stmt->execute([$searchTerm, $searchTerm, $searchTerm, $searchTerm, $limit]);
        $results['publications'] = $stmt->fetchAll();
    }
    
    // Search Institutions
    if ($type === 'all' || $type === 'institutions') {
        $stmt = $db->prepare("
            SELECT 'institution' as type, id, name, type, country, city, description
            FROM institutions
            WHERE (name LIKE ? OR description LIKE ? OR city LIKE ? OR country LIKE ?)
            AND status = 'active'
            ORDER BY name ASC
            LIMIT ?
        ");
        $stmt->execute([$searchTerm, $searchTerm, $searchTerm, $searchTerm, $limit]);
        $results['institutions'] = $stmt->fetchAll();
    }
    
    // Calculate total results
    $totalResults = 0;
    foreach ($results as $category) {
        $totalResults += count($category);
    }
    
    echo json_encode([
        'success' => true,
        'query' => $query,
        'type' => $type,
        'results' => $results,
        'total' => $totalResults
    ]);
    
} catch (Exception $e) {
    error_log("Search API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
