<?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 = '0000-00-00' 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 = '0000-00-00' 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, p.city, p.budget, 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 = [];
$palette = [
    '#3b82f6', // Bright Blue
    '#f43f5e', // Vibrant Rose
    '#10b981', // Emerald
    '#f59e0b', // Amber
    '#8b5cf6', // Violet
    '#0ea5e9', // Sky Blue
    '#ec4899', // Pink
    '#f97316', // Orange
    '#6366f1', // Indigo
    '#14b8a6', // Teal
];

// ── WEATHER CONFIG ──
$weatherApiKey = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'weather_api_key'")->fetchColumn();
$cityWeatherCache = [];

foreach ($rows as $r) {
    if (empty($r['start_date']) || $r['start_date'] === '0000-00-00') {
        continue; // Skip unscheduled projects
    }
    $startDate = $r['start_date'];
    $endDate = (!empty($r['end_date_planned']) && $r['end_date_planned'] !== '0000-00-00') ? $r['end_date_planned'] : $startDate;
    $endExclusive = date('Y-m-d', strtotime($endDate . ' +1 day'));

    $weather = [
        'temp' => null,
        'icon' => null,
        'description' => null
    ];

    if (!empty($r['city'])) {
        $weather = gp_get_weather_forecast($pdo, $r['city'], $startDate);
    }

    // Determine event color dynamically based on completed and paid status
    $eventColor = $palette[(int)$r['id'] % count($palette)];
    if ($r['status'] === 'completed') {
        $budget = (float)($r['budget'] ?? 0);
        $stmtPay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) FROM project_payments WHERE project_id = ? AND payment_type IN ('deposit', 'payment')");
        $stmtPay->execute([$r['id']]);
        $totalPaid = (float)$stmtPay->fetchColumn();

        if ($totalPaid >= $budget) {
            $eventColor = '#cbd5e1'; // Faint grey / Slate 300
        } else {
            $eventColor = '#ef4444'; // Red for completed but unpaid/underpaid
        }
    }

    $events[] = [
        'id' => (string)$r['id'],
        'title' => $r['title'] ?: $r['code'],
        'start' => $startDate,
        'end' => $endExclusive,
        'allDay' => true,
        'color' => $eventColor,
        'extendedProps' => [
            'status' => $r['status'],
            'customer_name' => $r['customer_name'],
            'city' => $r['city'],
            'weather' => (is_array($weather) && isset($weather['temp'])) ? $weather : null
        ],
    ];
}

// ── ADDITIONAL VISITS ──
$sqlVisits = "
    SELECT v.*, p.code, p.title AS project_title
    FROM project_visits v
    JOIN projects p ON p.id = v.project_id
    WHERE (v.start_date >= :start_date AND v.start_date <= :end_date)
       OR (v.end_date >= :start_date AND v.end_date <= :end_date)
";
$stmtV = $pdo->prepare($sqlVisits);
$stmtV->execute([':start_date' => substr($start, 0, 10), ':end_date' => substr($end, 0, 10)]);
$visitRows = $stmtV->fetchAll();

foreach ($visitRows as $v) {
    $endExclusive = date('Y-m-d', strtotime($v['end_date'] . ' +1 day'));
    $events[] = [
        'id' => 'visit_' . $v['id'],
        'title' => $v['project_title'] . ' - ' . $v['title'],
        'start' => $v['start_date'],
        'end' => $endExclusive,
        'allDay' => true,
        'color' => '#64748b', // Unique slate color for visits
        'extendedProps' => [
            'type' => 'visit',
            'project_id' => $v['project_id'],
        ],
    ];
}

echo json_encode($events, JSON_UNESCAPED_UNICODE);
