<?php
// POST /api/projects/create.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireRole([1, 2]);
$db   = getDB();

$name = trim(post('name', ''));
if (!$name) apiError('Project name required.', 422);

$db->prepare("
    INSERT INTO projects (client_id, name, description, project_type, status, priority, start_date, target_date, budget, project_manager, created_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
")->execute([
    post('client_id') ?: null,
    $name,
    post('description'),
    post('project_type', 'software'),
    post('status', 'planning'),
    post('priority', 'medium'),
    post('start_date') ?: null,
    post('target_date') ?: null,
    post('budget') ?: null,
    post('project_manager') ?: $user['id'],
    $user['id']
]);

$projectId = (int)$db->lastInsertId();

// Auto-add creator as manager
$db->prepare("INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, 'manager')")
   ->execute([$projectId, $user['id']]);

// Log activity
$db->prepare("INSERT INTO project_activity (project_id, user_id, action, entity_type, entity_id, details) VALUES (?, ?, 'created', 'project', ?, ?)")
   ->execute([$projectId, $user['id'], $projectId, json_encode(['name' => $name])]);

apiSuccess(['id' => $projectId], 'Project created.', 201);
