<?php
require_once '../connect.php';

header('Content-Type: application/json');

try {

    if (isset($_GET['search'])) {
        $search = $_GET['search'];
        
        $query = "SELECT authorid, firstname, lastname 
        FROM author 
        WHERE firstname ILIKE :search 
        OR lastname ILIKE :search
        ORDER BY firstname, lastname 
        LIMIT 10";

        $stmt = $conn->prepare($query);
        $stmt->execute([':search' => "$search%"]);  
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        
        echo json_encode($results);
        
    } else if (isset($_GET['id'])) {
        
        $authorId = $_GET['id'];
        
        $query = "SELECT * FROM author WHERE authorid = :authorId";
        $stmt = $conn->prepare($query);
        $stmt->execute([':authorId' => $authorId]);
        
        $author = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$author) {
            throw new Exception('Author not found');
        }
        
        echo json_encode($author);
        
    } else {
        throw new Exception('Either search term or author ID is required');
    }
    
} catch(Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
} catch(PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}
?>