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

function surveyorAdminAssignmentsColumnExists(mysqli $con, string $column): bool
{
    $stmt = $con->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'admin_assignments' 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;
}

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

function surveyorOptionalColumnSelect(mysqli $con, string $table, string $alias, string $column, string $selectAlias): string
{
    return surveyorTableColumnExists($con, $table, $column)
        ? "{$alias}.`{$column}` AS `{$selectAlias}`"
        : "NULL AS `{$selectAlias}`";
}

$surveyor_id = (int)$_SESSION['userid'];
$hasDiaryColumns = surveyorAdminAssignmentsColumnExists($con, 'start_time')
    && surveyorAdminAssignmentsColumnExists($con, 'end_time')
    && surveyorAdminAssignmentsColumnExists($con, 'notes')
    && surveyorAdminAssignmentsColumnExists($con, 'location_id')
    && surveyorAdminAssignmentsColumnExists($con, 'asset_id');

$diarySelect = $hasDiaryColumns
    ? "aa.start_time, aa.end_time, aa.notes, aa.location_id, aa.asset_id,"
    : "NULL AS start_time, NULL AS end_time, NULL AS notes, NULL AS location_id, NULL AS asset_id,";

$locationAddressSelect = implode(",\n        ", [
    surveyorOptionalColumnSelect($con, 'locations', 'l', 'locaddress1', 'locaddress1'),
    surveyorOptionalColumnSelect($con, 'locations', 'l', 'locaddress2', 'locaddress2'),
    surveyorOptionalColumnSelect($con, 'locations', 'l', 'locaddress3', 'locaddress3'),
    surveyorOptionalColumnSelect($con, 'locations', 'l', 'locaddress4', 'locaddress4')
]);
$clientAddressSelect = implode(",\n        ", [
    surveyorOptionalColumnSelect($con, 'clientdetails', 'cd', 'address1', 'client_address1'),
    surveyorOptionalColumnSelect($con, 'clientdetails', 'cd', 'address2', 'client_address2'),
    surveyorOptionalColumnSelect($con, 'clientdetails', 'cd', 'town', 'client_town'),
    surveyorOptionalColumnSelect($con, 'clientdetails', 'cd', 'county', 'client_county')
]);

$today_start = strtotime('today midnight');
$today_end = strtotime('tomorrow midnight') - 1;
$this_week_start = strtotime('monday this week');
$this_week_end = strtotime('sunday this week 23:59:59');
$this_month_start = strtotime('first day of this month');
$this_month_end = strtotime('last day of this month 23:59:59');
$sql = "
    SELECT
        aa.id,
        cd.clientname,
        cd.clientnumber,
        aa.appointment_date,
        $diarySelect
        l.locname,
        $locationAddressSelect,
        l.postcode AS location_postcode,
        $clientAddressSelect,
        cd.postcode AS client_postcode,
        aa.status,
        COUNT(DISTINCT i.itemnumber) AS total_items,
        SUM(CASE WHEN i.duedate < $today_start AND i.statuslive = 1 THEN 1 ELSE 0 END) AS overdue,
        SUM(CASE WHEN i.duedate BETWEEN $today_start AND $today_end AND i.statuslive = 1 THEN 1 ELSE 0 END) AS due_today,
        SUM(CASE WHEN i.duedate BETWEEN $this_week_start AND $this_week_end AND i.statuslive = 1 THEN 1 ELSE 0 END) AS due_this_week,
        SUM(CASE WHEN i.duedate BETWEEN $this_month_start AND $this_month_end AND i.statuslive = 1 THEN 1 ELSE 0 END) AS due_this_month,
        SUM(CASE WHEN i.duedate <= $today_end AND i.statuslive = 1 THEN COALESCE(dp.units, 0) ELSE 0 END) AS ui_units_due,
        SUM(CASE WHEN i.duedate <= $today_end AND i.statuslive = 1 AND dp.units IS NULL THEN 1 ELSE 0 END) AS ui_missing_due
    FROM admin_assignments aa
    LEFT JOIN clientdetails cd ON aa.client_id = cd.clientnumber
    LEFT JOIN locations l ON " . ($hasDiaryColumns ? "aa.location_id = l.locnumber" : "1 = 0") . "
    LEFT JOIN itemdetails i ON aa.client_id = i.clientnumber
        AND i.statuslive = 1
        AND i.duedate IS NOT NULL
        AND i.duedate > 0
        AND (" . ($hasDiaryColumns ? "aa.location_id IS NULL OR aa.location_id = 0 OR i.locnumber = aa.location_id" : "1 = 1") . ")
        AND (" . ($hasDiaryColumns ? "aa.asset_id IS NULL OR aa.asset_id = 0 OR i.itemnumber = aa.asset_id" : "1 = 1") . ")
    LEFT JOIN dd_plant dp ON i.code = dp.code
    WHERE aa.surveyor_id = ?
      AND aa.status IN (0, 1)
    GROUP BY aa.id
    ORDER BY COALESCE(" . ($hasDiaryColumns ? "aa.start_time" : "NULL") . ", aa.appointment_date) ASC, cd.clientname ASC
";

$stmt = $con->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['assignments' => [], 'error' => $con->error]);
    exit;
}
$stmt->bind_param('i', $surveyor_id);
$stmt->execute();
$result = $stmt->get_result();

$assignments = [];
while ($row = $result->fetch_assoc()) {
    $addressBits = [];
    $siteAddressBits = [];
    foreach (['locaddress1', 'locaddress2', 'locaddress3', 'locaddress4', 'location_postcode'] as $key) {
        if (!empty($row[$key])) $siteAddressBits[] = $row[$key];
    }
    foreach (['locname', 'locaddress1', 'locaddress2', 'locaddress3', 'locaddress4', 'location_postcode'] as $key) {
        if (!empty($row[$key])) $addressBits[] = $row[$key];
    }
    if (empty(array_filter($addressBits, fn($value) => trim((string)$value) !== ''))) {
        foreach (['clientname', 'client_address1', 'client_address2', 'client_town', 'client_county', 'client_postcode'] as $key) {
            if (!empty($row[$key])) $addressBits[] = $row[$key];
        }
        $siteAddressBits = $addressBits;
    }

    $assignments[] = [
        'id' => (int)$row['id'],
        'clientname' => $row['clientname'],
        'clientnumber' => (int)$row['clientnumber'],
        'appointment_date' => (int)$row['appointment_date'],
        'start_time' => $row['start_time'] !== null ? (int)$row['start_time'] : null,
        'end_time' => $row['end_time'] !== null ? (int)$row['end_time'] : null,
        'notes' => $row['notes'],
        'location_id' => $row['location_id'] !== null ? (int)$row['location_id'] : null,
        'asset_id' => $row['asset_id'] !== null ? (int)$row['asset_id'] : null,
        'locname' => $row['locname'],
        'site_address' => implode(', ', $siteAddressBits),
        'map_query' => implode(', ', $addressBits),
        'status' => $row['status'] == 0 ? 'Not Started' : ($row['status'] == 1 ? 'In Progress' : 'Completed'),
        'total_items' => (int)$row['total_items'],
        'overdue' => (int)$row['overdue'],
        'due_today' => (int)$row['due_today'],
        'due_this_week' => (int)$row['due_this_week'],
        'due_this_month' => (int)$row['due_this_month'],
        'ui_units_due' => (float)$row['ui_units_due'],
        'ui_missing_due' => (int)$row['ui_missing_due']
    ];
}

echo json_encode(['assignments' => $assignments]);

$stmt->close();
$con->close();
?>
