<?php
/**
 * City Council API — Scrapes Cincinnati Legistar for meetings + agenda items
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$action = $_GET['action'] ?? 'meetings';

function fetchUrl($url, $timeout = 15) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; CFD Portal/1.0)',
        CURLOPT_ENCODING => '',
    ]);
    $html = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($code >= 200 && $code < 400) ? $html : false;
}

function parseCalendar() {
    $cacheFile = __DIR__ . '/../uploads/council_cache.json';
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 3600) {
        header('Content-Type: application/json');
        readfile($cacheFile);
        exit;
    }

    $html = fetchUrl('https://cincinnatioh.legistar.com/Calendar.aspx');
    if (!$html) {
        if (file_exists($cacheFile)) { header('Content-Type: application/json'); readfile($cacheFile); exit; }
        jsonResponse(['error' => 'Unable to fetch council calendar'], 502);
    }

    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $xpath = new DOMXPath($doc);

    $rows = $xpath->query("//table[contains(@class,'rgMasterTable')]//tr[contains(@class,'rgRow') or contains(@class,'rgAltRow')]");
    $meetings = [];
    $today = date('Y-m-d');

    foreach ($rows as $row) {
        $cells = $xpath->query('.//td', $row);
        if ($cells->length < 6) continue;

        $nameCell = $cells->item(0);
        $nameLink = $xpath->query('.//a', $nameCell);
        $name = trim($nameCell->textContent);

        $dateStr = trim($cells->item(1)->textContent);
        $time = trim($cells->item(3)->textContent);
        $location = trim($cells->item(4)->textContent);

        // Parse details link for ID and GUID
        $detailsLink = $xpath->query('.//a/@href', $cells->item(5));
        $detailsUrl = $detailsLink->length > 0 ? $detailsLink->item(0)->nodeValue : '';
        $meetingId = '';
        $meetingGuid = '';
        if (preg_match('/ID=(\d+)/', $detailsUrl, $m)) $meetingId = $m[1];
        if (preg_match('/GUID=([A-F0-9-]+)/i', $detailsUrl, $m)) $meetingGuid = $m[1];

        // Agenda link
        $agendaLink = $xpath->query('.//a/@href', $cells->item(6));
        $agendaUrl = ($agendaLink->length > 0 && stripos($cells->item(6)->textContent, 'Not available') === false)
            ? 'https://cincinnatioh.legistar.com/' . $agendaLink->item(0)->nodeValue
            : '';

        // Minutes link
        $minutesAvailable = ($cells->length > 8 && stripos($cells->item(8)->textContent, 'Not available') === false);

        // Video link
        $videoAvailable = ($cells->length > 9 && stripos($cells->item(9)->textContent, 'Not available') === false);

        // Determine status
        $parsedDate = date('Y-m-d', strtotime($dateStr));
        $status = ($parsedDate >= $today) ? 'Scheduled' : ($minutesAvailable ? 'Completed' : 'Past');

        // Committee color category
        $category = 'other';
        $nameLower = strtolower($name);
        if (strpos($nameLower, 'public safety') !== false) $category = 'public-safety';
        elseif (strpos($nameLower, 'city council') !== false && strpos($nameLower, 'committee') === false) $category = 'full-council';
        elseif (strpos($nameLower, 'budget') !== false || strpos($nameLower, 'finance') !== false) $category = 'budget';
        elseif (strpos($nameLower, 'housing') !== false) $category = 'housing';
        elseif (strpos($nameLower, 'climate') !== false || strpos($nameLower, 'infrastructure') !== false) $category = 'climate';

        $meetings[] = [
            'id' => $meetingId,
            'guid' => $meetingGuid,
            'name' => $name,
            'date' => $parsedDate,
            'dateDisplay' => $dateStr,
            'time' => $time,
            'location' => $location,
            'status' => $status,
            'category' => $category,
            'agendaUrl' => $agendaUrl,
            'hasMinutes' => $minutesAvailable,
            'hasVideo' => $videoAvailable,
            'detailsUrl' => $meetingId ? "https://cincinnatioh.legistar.com/MeetingDetail.aspx?ID={$meetingId}&GUID={$meetingGuid}&Options=info|&Search=" : '',
        ];
    }

    $result = ['meetings' => $meetings, 'cached_at' => date('c')];
    @file_put_contents($cacheFile, json_encode($result));
    jsonResponse($result);
}

function parseAgenda() {
    $id = $_GET['id'] ?? '';
    $guid = $_GET['guid'] ?? '';
    if (!$id || !$guid) jsonResponse(['error' => 'Missing id or guid'], 400);

    $cacheFile = __DIR__ . "/../uploads/council_agenda_{$id}.json";
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 7200) {
        header('Content-Type: application/json');
        readfile($cacheFile);
        exit;
    }

    $url = "https://cincinnatioh.legistar.com/MeetingDetail.aspx?ID={$id}&GUID={$guid}&Options=info|&Search=";
    $html = fetchUrl($url);
    if (!$html) {
        if (file_exists($cacheFile)) { header('Content-Type: application/json'); readfile($cacheFile); exit; }
        jsonResponse(['error' => 'Unable to fetch agenda'], 502);
    }

    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $xpath = new DOMXPath($doc);

    // Get meeting title from page
    $titleEl = $xpath->query("//span[contains(@id,'lblMeetingDetail')]");
    $meetingName = $titleEl->length > 0 ? trim($titleEl->item(0)->textContent) : '';

    $rows = $xpath->query("//table[contains(@id,'gridMain')]//tr[contains(@class,'rgRow') or contains(@class,'rgAltRow')]");
    $items = [];

    foreach ($rows as $row) {
        $cells = $xpath->query('.//td', $row);
        if ($cells->length < 5) continue;

        $fileNumber = trim($cells->item(0)->textContent);
        $itemNumber = trim($cells->item(2)->textContent);
        $type = trim($cells->item(3)->textContent);
        $description = trim(preg_replace('/\s+/', ' ', $cells->item(4)->textContent));

        // Check if fire-relevant
        $descLower = strtolower($description);
        $fireRelevant = (strpos($descLower, 'fire') !== false || strpos($descLower, 'cfd') !== false
            || strpos($descLower, 'ems') !== false || strpos($descLower, 'emergency medical') !== false
            || strpos($descLower, 'arson') !== false);

        $items[] = [
            'fileNumber' => $fileNumber,
            'itemNumber' => $itemNumber,
            'type' => $type,
            'description' => $description,
            'fireRelevant' => $fireRelevant,
        ];
    }

    $result = ['items' => $items, 'meeting_name' => $meetingName, 'meeting_id' => $id, 'cached_at' => date('c')];
    @file_put_contents($cacheFile, json_encode($result));
    jsonResponse($result);
}

if ($action === 'agenda') {
    parseAgenda();
} else {
    parseCalendar();
}
