<?php
// POST /api/calendar/events.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user  = requireAuth();
$db    = getDB();
$uid   = (int)$user['id'];
$role  = (int)$user['role_id'];

$year  = (int)post('year',  date('Y'));
$month = (int)post('month', date('n'));

$from = sprintf('%04d-%02d-01', $year, $month);
$to   = date('Y-m-t', strtotime($from));

$events = [];
$errors = [];

// ── 1. Job Cards ─────────────────────────────────────────
try {
    if ($role == 1 || $role == 2) {
        $stmt = $db->prepare("
            SELECT jc.id, jc.job_number, jc.title,
                   jc.scheduled_date AS event_date,
                   jc.scheduled_time AS event_time,
                   jc.priority, jc.status,
                   jc.site_name, jc.site_address
            FROM job_cards jc
            WHERE jc.scheduled_date BETWEEN ? AND ?
              AND jc.status NOT IN ('completed','invoiced')
            ORDER BY jc.scheduled_date, jc.scheduled_time
        ");
        $stmt->execute([$from, $to]);
    } else {
        $stmt = $db->prepare("
            SELECT jc.id, jc.job_number, jc.title,
                   jc.scheduled_date AS event_date,
                   jc.scheduled_time AS event_time,
                   jc.priority, jc.status,
                   jc.site_name, jc.site_address
            FROM job_cards jc
            JOIN job_card_technicians jct ON jct.job_card_id = jc.id AND jct.user_id = ?
            WHERE jc.scheduled_date BETWEEN ? AND ?
              AND jc.status NOT IN ('completed','invoiced')
            ORDER BY jc.scheduled_date, jc.scheduled_time
        ");
        $stmt->execute([$uid, $from, $to]);
    }
    foreach ($stmt->fetchAll() as $r) {
        $events[] = [
            'id'       => 'jc-' . $r['id'],
            'type'     => 'jobcard',
            'label'    => ($r['job_number'] ?? '') . ' — ' . $r['title'],
            'sub'      => $r['site_name'] ?? $r['site_address'] ?? null,
            'date'     => $r['event_date'],
            'time'     => !empty($r['event_time']) ? substr($r['event_time'], 0, 5) : null,
            'priority' => $r['priority'],
            'status'   => $r['status'],
            'link'     => ['page' => 'jobcards', 'id' => (int)$r['id']],
            'color'    => 'blue',
        ];
    }
} catch (Exception $e) { $errors[] = 'jobcards: ' . $e->getMessage(); }

// ── 2. Project Todos ──────────────────────────────────────
try {
    if ($role != 4) {
        if ($role == 1 || $role == 5) {
            $stmt = $db->prepare("
                SELECT t.id, t.title, t.due_date AS event_date, t.priority, t.status,
                       p.name AS project_name, p.id AS project_id
                FROM project_todos t
                JOIN project_sections s ON s.id = t.section_id
                JOIN projects p ON p.id = s.project_id
                WHERE t.due_date BETWEEN ? AND ? AND t.status != 'done'
                ORDER BY t.due_date
            ");
            $stmt->execute([$from, $to]);
        } else {
            $stmt = $db->prepare("
                SELECT t.id, t.title, t.due_date AS event_date, t.priority, t.status,
                       p.name AS project_name, p.id AS project_id
                FROM project_todos t
                JOIN project_sections s ON s.id = t.section_id
                JOIN projects p ON p.id = s.project_id
                WHERE t.due_date BETWEEN ? AND ? AND t.status != 'done' AND t.assigned_to = ?
                ORDER BY t.due_date
            ");
            $stmt->execute([$from, $to, $uid]);
        }
        foreach ($stmt->fetchAll() as $r) {
            $events[] = [
                'id'       => 'todo-' . $r['id'],
                'type'     => 'todo',
                'label'    => $r['title'],
                'sub'      => $r['project_name'],
                'date'     => $r['event_date'],
                'time'     => null,
                'priority' => $r['priority'],
                'status'   => $r['status'],
                'link'     => ['page' => 'projects', 'id' => (int)$r['project_id']],
                'color'    => 'purple',
            ];
        }
    }
} catch (Exception $e) { $errors[] = 'todos: ' . $e->getMessage(); }

// ── 3. Leave ─────────────────────────────────────────────
try {
    if ($role == 1 || $role == 5) {
        $stmt = $db->prepare("
            SELECT l.id, l.leave_type, l.start_date, l.end_date, l.days,
                   CONCAT(e.first_name,' ',e.last_name) AS emp_name
            FROM employee_leave l
            JOIN employees e ON e.id = l.employee_id
            WHERE l.status = 'approved' AND l.start_date <= ? AND l.end_date >= ?
        ");
        $stmt->execute([$to, $from]);
    } else {
        $stmt = $db->prepare("
            SELECT l.id, l.leave_type, l.start_date, l.end_date, l.days,
                   CONCAT(e.first_name,' ',e.last_name) AS emp_name
            FROM employee_leave l
            JOIN employees e ON e.id = l.employee_id
            WHERE l.status = 'approved' AND l.start_date <= ? AND l.end_date >= ?
              AND e.user_id = ?
        ");
        $stmt->execute([$to, $from, $uid]);
    }
    foreach ($stmt->fetchAll() as $r) {
        $start = max($r['start_date'], $from);
        $end   = min($r['end_date'],   $to);
        $cur   = strtotime($start);
        $endTs = strtotime($end);
        while ($cur <= $endTs) {
            $events[] = [
                'id'    => 'leave-' . $r['id'] . '-' . date('Ymd', $cur),
                'type'  => 'leave',
                'label' => ucfirst($r['leave_type']) . ' Leave — ' . $r['emp_name'],
                'sub'   => $r['days'] . ' day(s)',
                'date'  => date('Y-m-d', $cur),
                'time'  => null,
                'color' => 'orange',
                'link'  => null,
            ];
            $cur = strtotime('+1 day', $cur);
        }
    }
} catch (Exception $e) { $errors[] = 'leave: ' . $e->getMessage(); }

// ── 4. Project Target Dates ───────────────────────────────
try {
    if ($role == 1 || $role == 2) {
        $stmt = $db->prepare("
            SELECT p.id, p.name, p.target_date AS event_date, p.status, p.priority
            FROM projects p
            WHERE p.target_date BETWEEN ? AND ?
              AND p.status NOT IN ('completed','cancelled')
        ");
        $stmt->execute([$from, $to]);
        foreach ($stmt->fetchAll() as $r) {
            $events[] = [
                'id'    => 'proj-' . $r['id'],
                'type'  => 'project',
                'label' => '🎯 ' . $r['name'],
                'sub'   => 'Target date',
                'date'  => $r['event_date'],
                'time'  => null,
                'link'  => ['page' => 'projects', 'id' => (int)$r['id']],
                'color' => 'green',
            ];
        }
    }
} catch (Exception $e) { $errors[] = 'projects: ' . $e->getMessage(); }

// ── 5. Custom Events ──────────────────────────────────────
try {
    $stmt = $db->prepare("
        SELECT id, title, description, event_date, event_time,
               event_type, color, all_day, created_by, is_shared,
               COALESCE(is_complete, 0) AS is_complete
        FROM calendar_events
        WHERE event_date BETWEEN ? AND ?
          AND (created_by = ? OR is_shared = 1)
          AND COALESCE(is_complete, 0) = 0
        ORDER BY event_date, event_time
    ");
    $stmt->execute([$from, $to, $uid]);
    foreach ($stmt->fetchAll() as $r) {
        $events[] = [
            'id'       => 'evt-' . $r['id'],
            'type'     => $r['event_type'] ?: 'event',
            'label'    => $r['title'],
            'sub'      => $r['description'],
            'date'     => $r['event_date'],
            'time'     => (!empty($r['event_time']) && !$r['all_day']) ? substr($r['event_time'], 0, 5) : null,
            'color'    => $r['color'] ?: 'teal',
            'link'     => null,
            'editable' => (int)$r['created_by'] === $uid,
            'raw_id'   => (int)$r['id'],
        ];
    }
} catch (Exception $e) { $errors[] = 'calendar_events: ' . $e->getMessage(); }

// ── 6. Checklist Instances ────────────────────────────────
try {
    $clWhere = $role == 1 || $role == 2
        ? "ci.due_date BETWEEN ? AND ? AND ci.status NOT IN ('completed','missed')"
        : "ci.due_date BETWEEN ? AND ? AND ci.status NOT IN ('completed','missed') AND (ct.assigned_to = ? OR ct.assigned_to IS NULL)";
    $clParams = $role == 1 || $role == 2 ? [$from, $to] : [$from, $to, $uid];
    $clStmt = $db->prepare("
        SELECT ci.id, ci.due_date, ci.status, ci.title AS instance_title,
               ct.name AS template_name, ct.linked_type
        FROM checklist_instances ci
        JOIN checklist_templates ct ON ct.id = ci.template_id
        WHERE $clWhere
        ORDER BY ci.due_date
    ");
    $clStmt->execute($clParams);
    $statusIcons = ['pending' => '🕐', 'in_progress' => '🔄', 'completed' => '✅', 'missed' => '❌'];
    foreach ($clStmt->fetchAll() as $r) {
        $icon = $statusIcons[$r['status']] ?? '📋';
        $events[] = [
            'id'       => 'cl-' . $r['id'],
            'type'     => 'checklist',
            'label'    => $icon . ' ' . ($r['instance_title'] ?: $r['template_name']),
            'sub'      => ucfirst(str_replace('_', ' ', $r['status'])),
            'date'     => $r['due_date'],
            'time'     => null,
            'status'   => $r['status'],
            'link'     => ['page' => 'checklists', 'instance_id' => (int)$r['id']],
            'color'    => 'teal',
        ];
    }
} catch (Exception $e) { $errors[] = 'checklists: ' . $e->getMessage(); }

// Sort
usort($events, function($a, $b) {
    return strcmp($a['date'] . ($a['time'] ?? '00:00'), $b['date'] . ($b['time'] ?? '00:00'));
});

apiSuccess([
    'events'       => $events,
    'month'        => $month,
    'year'         => $year,
    'from'         => $from,
    'to'           => $to,
    'debug_errors' => $errors,
]);