<?php
require_once('../../../'.$_REQUEST['tenant'].'/config.php');

function adminSurveyorColumnExists(mysqli $con, string $column): bool
{
    $stmt = $con->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'surveyor' AND COLUMN_NAME = ? LIMIT 1");
    if (!$stmt) return false;
    $stmt->bind_param('s', $column);
    $stmt->execute();
    $stmt->store_result();
    $exists = $stmt->num_rows > 0;
    $stmt->close();
    return $exists;
}

// Fetch active surveyors
$dayStartSelect = adminSurveyorColumnExists($con, 'day_start_time') ? "day_start_time" : "NULL AS day_start_time";
$sql = "SELECT id, forename, surname, address1, address2, address3, postcode, $dayStartSelect FROM surveyor WHERE statuslive = 1";
$result = $con->query($sql);
$surveyors = [];

while ($row = $result->fetch_assoc()) {
    $addressBits = [];
    foreach (['address1', 'address2', 'address3', 'postcode'] as $key) {
        if (!empty($row[$key])) $addressBits[] = $row[$key];
    }
    $row['home_map_query'] = implode(', ', $addressBits);
    $surveyors[] = $row;
}

echo json_encode(['surveyors' => $surveyors]);
?>
