<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();
header('Content-Type: application/json; charset=utf-8');

$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
    exit;
}

$id = (int)($input['id'] ?? 0);
$start = trim((string)($input['start'] ?? ''));
$end = trim((string)($input['end'] ?? ''));

if ($id <= 0 || $start === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Missing id or start date']);
    exit;
}

$startDate = substr($start, 0, 10);
$endDate = $end !== '' ? substr($end, 0, 10) : $startDate;
$endDate = date('Y-m-d', strtotime($endDate . ' -1 day'));
if ($endDate < $startDate) $endDate = $startDate;

$stmt = $pdo->prepare("
    UPDATE projects
    SET start_date = :start_date,
        end_date_planned = :end_date
    WHERE id = :id
");
$stmt->execute([
    ':start_date' => $startDate,
    ':end_date' => $endDate,
    ':id' => $id,
]);

echo json_encode(['ok' => true]);
