<?php
// ============================================================
// suggest.php  —  PHP 8 compatible
// Run on a cron to regenerate /suggester/suggest.js
// Changes from original:
//   - "HI" output removed (caused headers-already-sent issues)
//   - $url now set correctly for every field in the loop, not
//     just inside the address block (was undefined for other
//     fields, causing stale URL reuse)
//   - StreetName used as string not array (StreetName[0] -> StreetName)
//   - lakename and school_district_number no longer overwritten
//     with empty arrays after being populated from the API
//   - cURL timeouts added (CONNECTTIMEOUT 5, TIMEOUT 15)
//   - File write wrapped in error check
//   - Empty address strings skipped to keep the JS array clean
//   - debug ini_set calls removed (not appropriate for cron output)
// ============================================================

$field_array = ['address', 'POSTALCODE_T', 'CITY_T', 'NEIGHBORHOOD_T', 'SCHOOLDISTRICTNUMBER_T', 'WaterBodyName_T'];

$query = "StandardStatus%3AActive%20";
$res   = '';

foreach ($field_array as $field) {

    // Build the correct API URL for each field type
    if ($field === 'address') {
        $fl  = 'ListingId,StreetDirPrefix,StreetNumber,StreetName,StreetSuffix,StreetDirSuffix,City,StateOrProvince';
        $url = "https://data.msllcdata.com/bonstlistingsnew2/select?fl={$fl}&q={$query}&rows=1000000";
    } else {
        $url = "https://data.msllcdata.com/bonstlistingsnew2/select?fl={$field}&q={$query}&rows=1000000";
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $result_tmp = curl_exec($ch);
    $httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200 || !$result_tmp) {
        continue;
    }

    $response      = json_decode($result_tmp, true);
    $total_records = $response['response']['numFound'] ?? 0;

    if ($total_records <= 0) {
        continue;
    }

    $results     = $response['response']['docs'];
    $commonArray = [];

    foreach ($results as $value) {
        if ($field === 'address') {
            if (!isset($value['ListingId'])) continue;
            $address = '(' . str_replace('NST', '', $value['ListingId']) . ') ';
            if (!empty($value['StreetDirPrefix']))  $address .= $value['StreetDirPrefix'] . ' ';
            if (!empty($value['StreetNumber']))     $address .= $value['StreetNumber'] . ' ';
            if (!empty($value['StreetName']))       $address .= $value['StreetName'] . ' ';
            if (!empty($value['StreetSuffix']))     $address .= $value['StreetSuffix'] . ' ';
            if (!empty($value['StreetDirSuffix']))  $address .= $value['StreetDirSuffix'];
            if (!empty($value['City']))             $address .= ', ' . $value['City'];
            if (!empty($value['StateOrProvince']))  $address .= ', ' . $value['StateOrProvince'];
            $address = trim($address);
            if ($address !== '') {
                $commonArray[] = $address;
            }

        } elseif ($field === 'NEIGHBORHOOD_T') {
            if (!empty($value[$field][0])) $commonArray[] = $value[$field][0];

        } elseif ($field === 'SCHOOLDISTRICTNUMBER_T') {
            if (!empty($value[$field])) $commonArray[] = $value[$field];

        } else {
            if (!empty($value[$field])) $commonArray[] = $value[$field];
        }
    }

    $commonArray = array_values(array_unique($commonArray));

    // Map API field names to JS variable names
    $jsVarName = match($field) {
        'CITY_T'                 => 'sale_city',
        'POSTALCODE_T'           => 'sale_postalcode',
        'address'                => 'sale_address',
        'NEIGHBORHOOD_T'         => 'sale_neighborhood',
        'SCHOOLDISTRICTNUMBER_T' => 'school_district_number',
        'WaterBodyName_T'        => 'lakename',
        default                  => $field,
    };

    $res .= "var {$jsVarName} = " . json_encode($commonArray) . ";\n";
}

// Append empty placeholder arrays for variables referenced in footer.php
// (rental, multi-family, land, farm, commercial — not populated here)
$emptyVars = [
    'sale_stateorprovince', 'sale_county', 'sale_waterfrontname',
    'rent_city', 'rent_county', 'rent_neighborhood', 'rent_postalcode',
    'rent_address', 'rent_waterfrontname', 'rent_stateorprovince',
    'mul_city', 'mul_county', 'mul_neighborhood', 'mul_postalcode',
    'mul_address', 'mul_waterfrontname', 'mul_stateorprovince',
    'lnd_city', 'lnd_county', 'lnd_neighborhood', 'lnd_postalcode',
    'lnd_address', 'lnd_waterfrontname', 'lnd_stateorprovince',
    'frm_city', 'frm_county', 'frm_neighborhood', 'frm_postalcode',
    'frm_address', 'frm_waterfrontname', 'frm_stateorprovince',
    'com_city', 'com_county', 'com_neighborhood', 'com_postalcode',
    'com_address', 'com_waterfrontname', 'com_stateorprovince',
];
foreach ($emptyVars as $varName) {
    $res .= "var {$varName} = [];\n";
}

// Write the generated JS file
$fileUrl = $_SERVER['DOCUMENT_ROOT'] . '/suggester/suggest.js';
$fh = fopen($fileUrl, 'w');
if ($fh === false) {
    error_log("suggest.php: failed to open {$fileUrl} for writing");
    exit(1);
}
fwrite($fh, $res);
fclose($fh);