<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/database.php';

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    if (!$conn) {
        throw new Exception("Keine Datenbankverbindung möglich");
    }
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['autohaus_id'])) {
        throw new Exception('Autohaus ID ist erforderlich');
    }
    
    $autohaus_id = intval($input['autohaus_id']);
    $search_term = isset($input['search']) ? trim($input['search']) : '';
    $limit = isset($input['limit']) ? intval($input['limit']) : 10;
    
    // Build query based on search term
    if (!empty($search_term)) {
        $stmt = $conn->prepare("
            SELECT 
                brand_model,
                eu_label,
                size_pattern,
                usage_count,
                last_used
            FROM tire_suggestions 
            WHERE autohaus_id = ? 
            AND (brand_model LIKE ? OR size_pattern LIKE ?)
            ORDER BY usage_count DESC, last_used DESC
            LIMIT ?
        ");
        
        $searchPattern = '%' . $search_term . '%';
        $stmt->execute([$autohaus_id, $searchPattern, $searchPattern, $limit]);
    } else {
        $stmt = $conn->prepare("
            SELECT 
                brand_model,
                eu_label,
                size_pattern,
                usage_count,
                last_used
            FROM tire_suggestions 
            WHERE autohaus_id = ? 
            ORDER BY usage_count DESC, last_used DESC
            LIMIT ?
        ");
        
        $stmt->execute([$autohaus_id, $limit]);
    }
    
    $suggestions = $stmt->fetchAll();
    
    $formattedSuggestions = [];
    foreach ($suggestions as $row) {
        $formattedSuggestions[] = [
            'brand_model' => $row['brand_model'],
            'eu_label' => $row['eu_label'],
            'size_pattern' => $row['size_pattern'],
            'usage_count' => intval($row['usage_count']),
            'last_used' => $row['last_used']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'suggestions' => $formattedSuggestions,
        'count' => count($formattedSuggestions)
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
