<?php
/**
 * API Handler - Services List
 * Aegean Dominance - İzmir Tenteci V2
 */

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../../config/config.php';

try {
    $db = Database::getInstance();
    
    // Get query params
    $category = $_GET['category'] ?? null;
    $limit = min((int)($_GET['limit'] ?? 100), 100);
    $featured = isset($_GET['featured']);
    
    // Build query - using actual columns from schema
    $sql = "SELECT id, name, slug, category, short_description, icon, is_featured, display_order 
            FROM services WHERE is_active = 1";
    $params = [];
    
    if ($category) {
        $sql .= " AND category = ?";
        $params[] = $category;
    }
    
    if ($featured) {
        $sql .= " AND is_featured = 1";
    }
    
    $sql .= " ORDER BY display_order ASC, name ASC LIMIT " . $limit;
    
    $services = $db->fetchAll($sql, $params);
    
    // Add URLs
    foreach ($services as &$service) {
        $service['url'] = Router::serviceUrl($service['slug']);
        // Get image from service_images table or use placeholder
        $image = $db->fetchColumn(
            "SELECT image_path FROM service_images WHERE service_id = ? AND is_featured = 1 LIMIT 1",
            [$service['id']]
        );
        $service['image_url'] = $image 
            ? Router::url('/urunler/' . $image)
            : Router::url('/assets/images/placeholder.webp');
    }
    
    echo json_encode([
        'success' => true,
        'count' => count($services),
        'data' => $services
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    error_log("API Services Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Servisler yüklenemedi.']);
}
