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

$user = requireAuth();
$db   = getDB();
$id   = (int)post('id', 0);
if (!$id) apiError('Todo ID required.', 422);

$stmt = $db->prepare("SELECT * FROM project_todos WHERE id = ?");
$stmt->execute([$id]);
$todo = $stmt->fetch();
if (!$todo) apiError('Task not found.', 404);

$newStatus = post('status', $todo['status']);
$completedAt = ($newStatus === 'done' && $todo['status'] !== 'done') ? date('Y-m-d H:i:s') : ($todo['completed_at'] ?: null);

$db->prepare("
    UPDATE project_todos SET
        title           = ?,
        description     = ?,
        status          = ?,
        priority        = ?,
        assigned_to     = ?,
        estimated_hours = ?,
        actual_hours    = ?,
        due_date        = ?,
        completed_at    = ?
    WHERE id = ?
")->execute([
    post('title', $todo['title']),
    post('description', $todo['description']),
    $newStatus,
    post('priority', $todo['priority']),
    post('assigned_to') ?: $todo['assigned_to'],
    post('estimated_hours') ?: $todo['estimated_hours'],
    post('actual_hours') ?: $todo['actual_hours'],
    post('due_date') ?: $todo['due_date'],
    $completedAt,
    $id
]);

if ($newStatus !== $todo['status']) {
    $db->prepare("INSERT INTO project_activity (project_id, user_id, action, entity_type, entity_id, details) VALUES (?, ?, 'todo_status_changed', 'todo', ?, ?)")
       ->execute([$todo['project_id'], $user['id'], $id, json_encode(['from' => $todo['status'], 'to' => $newStatus, 'title' => $todo['title']])]);
}

apiSuccess([], 'Task updated.');
