<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

$data = json_decode(file_get_contents('php://input'), true);

// Validation
if (empty($data['title'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Le titre est requis']);
    exit;
}

// Generate slug
$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $data['title']), '-'));

// Check if slug exists
$stmt = getDB()->prepare("SELECT id FROM services WHERE slug = ?");
$stmt->execute([$slug]);
if ($stmt->fetch()) {
    $slug .= '-' . time();
}

try {
    $stmt = getDB()->prepare("INSERT INTO services (title, slug, description, full_content, icon, featured, order_position, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $data['title'],
        $slug,
        $data['description'] ?? '',
        $data['full_content'] ?? '',
        $data['icon'] ?? 'fa-cog',
        $data['featured'] ? 1 : 0,
        $data['order_position'] ?? 0,
        $data['status'] ?? 'active'
    ]);
    
    $id = getDB()->lastInsertId();
    
    echo json_encode([
        'success' => true,
        'message' => 'Service créé avec succès',
        'id' => $id
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
