<?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 {
    $user_id = Auth::check();
    $data = json_decode(file_get_contents('php://input'), true);

    if (empty($data['title']) || empty($data['price']) || empty($data['category'])) {
        throw new Exception("Title, price, and category are required.");
    }

    $title = htmlspecialchars($data['title']);
    $price = (int)$data['price'];
    $category = htmlspecialchars($data['category']);

    // Check if table exists, create if not (Ad-hoc migration for safety)
    $pdo->exec("CREATE TABLE IF NOT EXISTS mk_services (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        title VARCHAR(255) NOT NULL,
        price INT NOT NULL,
        category VARCHAR(50) DEFAULT 'General',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        rating FLOAT DEFAULT 0,
        FOREIGN KEY (user_id) REFERENCES users(id)
    )");

    $stmt = $pdo->prepare("INSERT INTO mk_services (user_id, title, price, category) VALUES (?, ?, ?, ?)");
    $stmt->execute([$user_id, $title, $price, $category]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Service created successfully',
        'service_id' => $pdo->lastInsertId()
    ]);

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