<?php
/**
 * Projects API Endpoint
 */

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

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

try {
    $pdo = getDBConnection();
    
    $filter = $_GET['filter'] ?? 'all';
    $query = "SELECT id, title, description, location, service_type, image_url, created_at
               FROM projects
               WHERE status = 'published'";
    
    if ($filter !== 'all') {
        $query .= " AND service_type = :filter";
    }
    
    $query .= " ORDER BY created_at DESC";
    
    $stmt = $pdo->prepare($query);
    if ($filter !== 'all') {
        $stmt->execute([':filter' => $filter]);
    } else {
        $stmt->execute();
    }
    
    $projects = [];
    while ($row = $stmt->fetch()) {
        // Format image URL if it exists
        $imageUrl = null;
        if (!empty($row['image_url'])) {
            // If it's already a full URL, use it; otherwise prepend the uploads path
            if (strpos($row['image_url'], 'http') === 0) {
                $imageUrl = $row['image_url'];
            } else {
                $imageUrl = '/backend/uploads/projects/' . $row['image_url'];
            }
        }
        
        $projects[] = [
            'id' => $row['id'],
            'title' => $row['title'],
            'description' => $row['description'] ?: '',
            'location' => $row['location'] ?: '',
            'service_type' => $row['service_type'] ?: '',
            'image_url' => $imageUrl,
            'created_at' => $row['created_at']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'projects' => $projects
    ]);
    
} catch (Exception $e) {
    error_log("Projects API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'projects' => []
    ]);
}

