<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../models/Product.php';

$database = new Database();
$db = $database->getConnection();
$product = new Product($db);

$method = $_SERVER['REQUEST_METHOD'];
$id = isset($_GET['id']) ? $_GET['id'] : null;

if (!$id) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Product ID is required'
    ]);
    exit();
}

switch($method) {
    case 'GET':
        // Get related products
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 8;
        
        try {
            $relatedProducts = $product->getRelatedProducts($id, $limit);
            
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'products' => $relatedProducts
            ]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Internal server error: ' . $e->getMessage()
            ]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode([
            'success' => false,
            'message' => 'Method not allowed'
        ]);
        break;
}
?>