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

$user = requireAuth();
$db   = getDB();

$sectionId = (int)post('section_id', 0);
$projectId = (int)post('project_id', 0);
$title     = trim(post('title', ''));

if (!$sectionId) apiError('Section ID required.', 422);
if (!$projectId) apiError('Project ID required.', 422);
if (!$title)     apiError('Title required.', 422);

$db->prepare("
    INSERT INTO project_todos (section_id, project_id, title, description, status, priority, assigned_to, estimated_hours, due_date, created_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
")->execute([
    $sectionId, $projectId, $title,
    post('description'),
    post('status', 'todo'),
    post('priority', 'medium'),
    post('assigned_to') ?: null,
    post('estimated_hours') ?: null,
    post('due_date') ?: null,
    $user['id']
]);

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

$db->prepare("INSERT INTO project_activity (project_id, user_id, action, entity_type, entity_id, details) VALUES (?, ?, 'todo_created', 'todo', ?, ?)")
   ->execute([$projectId, $user['id'], $todoId, json_encode(['title' => $title])]);

apiSuccess(['id' => $todoId], 'Task created.', 201);
