<?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);

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

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

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

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