<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Cache-Control: max-age=300");

// Judge roster effective August 1, 2025
// Source: Milwaukee County First Judicial District Court Roster
$JUDGES = [
    1  => ["judge"=>"Judge Jack L. Davila",          "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4521"],
    2  => ["judge"=>"Judge Milton Lee Childs Sr.",   "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4498"],
    3  => ["judge"=>"Judge Katie Beth Kegel",        "division"=>"Felony/Gun/HIDTA",          "room"=>"CJF",    "phone"=>"(414) 278-4775"],
    4  => ["judge"=>"Judge Michael J. Hanrahan",     "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-5102"],
    5  => ["judge"=>"Judge Kristela L. Cervera",     "division"=>"Misdemeanor",               "room"=>"622 CH", "phone"=>"(414) 278-XXXX"],
    7  => ["judge"=>"Judge Thomas J. McAdams",       "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4523"],
    8  => ["judge"=>"Judge William Sosnay",          "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4514"],
    9  => ["judge"=>"Judge Paul R. Van Grunsven",    "division"=>"Probate",                   "room"=>"CH",     "phone"=>"(414) 278-4517"],
    10 => ["judge"=>"Judge Michelle Ackerman Havas", "division"=>"Felony/Homicide/Sex Assault","room"=>"CJF",   "phone"=>"(414) 278-4496"],
    11 => ["judge"=>"Judge David C. Swanson",        "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4772"],
    12 => ["judge"=>"Judge David L. Borowski",       "division"=>"Felony/Homicide",           "room"=>"502 SB", "phone"=>"(414) 278-4472"],
    13 => ["judge"=>"Judge Ana Maria Berrios-Schroeder","division"=>"Misdemeanor/DV",         "room"=>"504 CH", "phone"=>"(414) 278-5316"],
    14 => ["judge"=>"Judge Christopher R. Foley",    "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4582"],
    15 => ["judge"=>"Judge Jonathan D. Watts",       "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4484"],
    16 => ["judge"=>"Judge Brittany C. Grayson",     "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4504"],
    17 => ["judge"=>"Judge Carolina Stark",          "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4500"],
    18 => ["judge"=>"Judge Ronnie V. Murray II",     "division"=>"Children's Court",          "room"=>"VPJJC",  "phone"=>"(414) 257-7098"],
    19 => ["judge"=>"Judge Kori L. Ashley",          "division"=>"Felony/Gun",                "room"=>"316 SB", "phone"=>"(414) 278-5153"],
    20 => ["judge"=>"Judge Joseph R. Wall",          "division"=>"Felony/Drugs",              "room"=>"CJF",    "phone"=>"(414) 454-4220"],
    21 => ["judge"=>"Judge Cynthia M. Davis",        "division"=>"Probate (Presiding)",       "room"=>"CH",     "phone"=>"(414) 278-4474"],
    23 => ["judge"=>"Judge Jorge R. Fragoso",        "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-XXXX"],
    33 => ["judge"=>"Judge Carl Ashley",             "division"=>"Chief Judge",               "room"=>"609 CH", "phone"=>"(414) 278-4998"],
    35 => ["judge"=>"Judge Frederick C. Rosa",       "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4560"],
    36 => ["judge"=>"Judge Laura A. Crivello",       "division"=>"Felony (Presiding)",        "room"=>"CJF",    "phone"=>"(414) 278-4478"],
    37 => ["judge"=>"Judge T. Christopher Dee",      "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4551"],
    38 => ["judge"=>"Judge Jeffrey A. Wagner",       "division"=>"Felony/Homicide (Presiding)","room"=>"CJF",  "phone"=>"(414) 278-5393"],
    39 => ["judge"=>"Judge Jane Vinopal Carroll",    "division"=>"Children's Court (Deputy CJ)","room"=>"VPJJC","phone"=>"(414) 257-7150"],
    40 => ["judge"=>"Judge Danielle L. Shelton",     "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-4898"],
    41 => ["judge"=>"Judge Lena Carolyn Taylor",     "division"=>"Misdemeanor/DV",            "room"=>"CH",     "phone"=>"(414) 278-4901"],
    42 => ["judge"=>"Judge Reyna Ivonne Morales",    "division"=>"Family",                    "room"=>"CH",     "phone"=>"(414) 278-4519"],
    43 => ["judge"=>"Judge Marisabel Cabrera",       "division"=>"Misdemeanor",               "room"=>"623 CH", "phone"=>"(414) 278-4480"],
    44 => ["judge"=>"Judge Mark A. Sanders",         "division"=>"Felony/Mental Health",      "room"=>"CJF",    "phone"=>"(414) 278-XXXX"],
    45 => ["judge"=>"Judge Jean M. Kies",            "division"=>"Civil",                     "room"=>"CH",     "phone"=>"(414) 278-XXXX"],
    46 => ["judge"=>"Judge Raphael F.A. Ramos",      "division"=>"Felony/Drugs",              "room"=>"CJF",    "phone"=>"(414) 278-XXXX"],
    47 => ["judge"=>"Judge Jonathan D. Richards",    "division"=>"Felony",                    "room"=>"CJF",    "phone"=>"(414) 278-XXXX"],
];

// Division type info for PSN
$DIVISION_INFO = [
    "Felony"           => ["type"=>"Criminal","psnNote"=>"High-value coverage — major crimes, trials, sentencing"],
    "Felony/Homicide"  => ["type"=>"Criminal","psnNote"=>"PRIORITY — homicide cases, high-profile trials"],
    "Felony/Homicide (Presiding)"=>["type"=>"Criminal","psnNote"=>"PRIORITY — homicide calendar presiding"],
    "Felony/Homicide/Sex Assault"=>["type"=>"Criminal","psnNote"=>"PRIORITY — homicide and sexual assault cases"],
    "Felony/Gun"       => ["type"=>"Criminal","psnNote"=>"Gun crimes calendar"],
    "Felony/Gun/HIDTA" => ["type"=>"Criminal","psnNote"=>"Gun + drug trafficking calendar"],
    "Felony/Drugs"     => ["type"=>"Criminal","psnNote"=>"Drug felony calendar"],
    "Felony (Presiding)"=>["type"=>"Criminal","psnNote"=>"Presiding felony judge"],
    "Misdemeanor"      => ["type"=>"Criminal","psnNote"=>"Misdemeanor calendar"],
    "Misdemeanor/DV"   => ["type"=>"Criminal","psnNote"=>"Domestic violence calendar"],
    "Children's Court" => ["type"=>"Juvenile", "psnNote"=>"Juvenile cases — limited public access"],
    "Children's Court (Deputy CJ)"=>["type"=>"Juvenile","psnNote"=>"Juvenile presiding — limited public access"],
    "Probate"          => ["type"=>"Probate",  "psnNote"=>"Estates and guardianship"],
    "Probate (Presiding)"=>["type"=>"Probate", "psnNote"=>"Presiding probate judge"],
    "Civil"            => ["type"=>"Civil",    "psnNote"=>"Civil disputes"],
    "Family"           => ["type"=>"Family",   "psnNote"=>"Family law — divorce, custody"],
    "Chief Judge"      => ["type"=>"Admin",    "psnNote"=>"Administrative — not typically streamed"],
    "Felony/Mental Health"=>["type"=>"Criminal","psnNote"=>"Mental health court calendar"],
];

function fetchPage($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122 Safari/537.36");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

function checkDacastLive($url) {
    // Live detection done client-side to avoid server timeout
    if (!$url) return "unknown";
    return "offline";
}

function normalizeUrl($href) {
    if (!$href) return "";
    if (strpos($href, "http") === 0) return $href;
    return "https://www.wicourts.gov/" . ltrim($href, "/");
}

function slugify($str) {
    return preg_replace('/[^a-z0-9]+/', '-', strtolower(trim($str)));
}

function getBranchNumber($title) {
    if (preg_match('/Branch\s+(\d+)/i', $title, $m)) return (int)$m[1];
    return null;
}

$FALLBACK = ["Branch 1","Branch 2","Branch 3","Branch 4","Branch 5","Branch 6","Branch 7","Branch 8","Branch 9","Branch 10","Branch 11","Branch 12","Branch 13","Branch 14","Branch 15","Branch 16","Branch 17","Branch 18","Branch 19","Branch 20","Branch 21","Branch 22","Branch 23","Branch 24","Branch 25","Branch 26","Branch 27","Branch 28","Branch 29","Branch 30","Branch 31","Branch 32","Branch 33","Branch 34","Branch 35","Branch 36","Branch 37","Branch 38","Branch 39","Branch 40","Branch 41","Branch 42","Branch 43","Branch 44","Branch 45","Branch 46","Branch 47","Intake Court","Out of Custody Court","Preliminary Hearing Court","Probate Hearing Court","Probate Hearing Court 2","Reserve","Small Claims Court 1","Small Claims Court 2","Small Claims Court 3","Small Claims Court 4"];

function buildFeedEntry($id, $title, $url, $provider, $streamStatus, $checkedTime, $branchNum, $judges, $divisionInfo) {
    $judgeData = $branchNum && isset($judges[$branchNum]) ? $judges[$branchNum] : null;
    $divData = $judgeData && isset($divisionInfo[$judgeData["division"]]) ? $divisionInfo[$judgeData["division"]] : null;
    return [
        "id"           => $id,
        "title"        => $title,
        "url"          => $url,
        "provider"     => $provider,
        "county"       => "Milwaukee County",
        "isLive"       => $streamStatus === "live",
        "streamStatus" => $streamStatus,
        "lastChecked"  => $checkedTime,
        "judge"        => $judgeData ? $judgeData["judge"] : "",
        "division"     => $judgeData ? $judgeData["division"] : "",
        "room"         => $judgeData ? $judgeData["room"] : "",
        "phone"        => $judgeData ? $judgeData["phone"] : "",
        "psnNote"      => $divData ? $divData["psnNote"] : "",
        "caseType"     => $divData ? $divData["type"] : "",
        "notes"        => ""
    ];
}

try {
    $html = fetchPage("https://www.wicourts.gov/courts/livestream.htm");
    $feeds = [];
    $inMilwaukee = false;
    $checkedTime = date("g:i A");

    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML('<?xml encoding="utf-8" ?>' . $html);
    libxml_clear_errors();
    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query("//h4 | //a[@href]");

    foreach ($nodes as $node) {
        $tag = strtolower($node->tagName);
        $text = trim($node->textContent);
        if ($tag === "h4") { $inMilwaukee = stripos($text, "Milwaukee") !== false; continue; }
        if (!$inMilwaukee || $tag !== "a") continue;
        $href = normalizeUrl(trim($node->getAttribute("href")));
        if (!$href || !$text) continue;
        if (stripos($href, "wicourts.gov") !== false && stripos($href, "livestream") !== false) continue;

        $provider = "external";
        if (strpos($href, "dacast.com") !== false) $provider = "dacast";
        elseif (strpos($href, "youtube.com") !== false) $provider = "youtube";
        elseif (strpos($href, "zoom.us") !== false) $provider = "zoom";

        $branchNum = getBranchNumber($text);
        $streamStatus = checkDacastLive($href);

        $feeds[] = buildFeedEntry(
            "milwaukee-" . slugify($text),
            $text, $href, $provider, $streamStatus,
            $checkedTime, $branchNum, $JUDGES, $DIVISION_INFO
        );
    }

    if (empty($feeds)) {
        // Fallback with judge data attached
        $feeds = array_map(function($title, $i) use ($checkedTime, $JUDGES, $DIVISION_INFO) {
            $branchNum = null;
            if (preg_match('/Branch\s+(\d+)/i', $title, $m)) $branchNum = (int)$m[1];
            return buildFeedEntry("fallback-".($i+1), $title, "", "unknown", "unknown", $checkedTime, $branchNum, $JUDGES, $DIVISION_INFO);
        }, $FALLBACK, array_keys($FALLBACK));
    }

    echo json_encode($feeds);

} catch (Exception $e) {
    $feeds = array_map(function($title, $i) use ($e, $checkedTime, $JUDGES, $DIVISION_INFO) {
        $branchNum = null;
        if (preg_match('/Branch\s+(\d+)/i', $title, $m)) $branchNum = (int)$m[1];
        return buildFeedEntry("fallback-".($i+1), $title, "", "unknown", "unknown", $checkedTime, $branchNum, $JUDGES, $DIVISION_INFO);
    }, $FALLBACK, array_keys($FALLBACK));
    echo json_encode($feeds);
}