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

$start = trim((string)($_GET['start'] ?? ''));
$end = trim((string)($_GET['end'] ?? ''));
$where = [];
$params = [];

if ($start !== '') {
    $where[] = "(p.end_date_planned IS NULL OR p.end_date_planned >= :start_date)";
    $params[':start_date'] = substr($start, 0, 10);
}
if ($end !== '') {
    $where[] = "(p.start_date IS NULL OR p.start_date <= :end_date)";
    $params[':end_date'] = substr($end, 0, 10);
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$sql = "
    SELECT p.id, p.code, p.title, p.status, p.start_date, p.end_date_planned, c.name AS customer_name
    FROM projects p
    LEFT JOIN customers c ON c.id = p.customer_id
    $whereSql
    ORDER BY p.start_date ASC, p.id DESC
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

$events = [];
foreach ($rows as $r) {
    $startDate = $r['start_date'] ?: date('Y-m-d');
    $endDate = $r['end_date_planned'] ?: $startDate;
    $endExclusive = date('Y-m-d', strtotime($endDate . ' +1 day'));

    $events[] = [
        'id' => (string)$r['id'],
        'title' => $r['title'] ?: $r['code'],
        'start' => $startDate,
        'end' => $endExclusive,
        'allDay' => true,
        'extendedProps' => [
            'status' => $r['status'],
            'customer_name' => $r['customer_name'],
        ],
    ];
}

echo json_encode($events, JSON_UNESCAPED_UNICODE);
