<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $seller_id = Auth::check();
    
    $data = json_decode(file_get_contents("php://input"));
    
    if (!isset($data->title) || !isset($data->price)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing title or price']);
        exit;
    }

    $title = trim($data->title);
    $description = isset($data->description) ? trim($data->description) : '';
    $price = (int)$data->price;
    $category = isset($data->category) ? $data->category : 'general';
    $image_url = isset($data->image_url) ? $data->image_url : null;

    if ($price < 0) {
        throw new Exception("Price cannot be negative");
    }

    $sql = "INSERT INTO services (seller_id, title, description, price, category, image_url) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$seller_id, $title, $description, $price, $category, $image_url]);
    
    echo json_encode([
        'status' => 'success',
        'service_id' => $pdo->lastInsertId(),
        'message' => 'Service created successfully'
    ]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
