<?php ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once('../../../' . $_REQUEST['tenant'] . '/config.php');

function adminAssignedJobsColumnExists(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 adminTableColumnExists(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 adminOptionalColumnSelect(mysqli $con, string $table, string $alias, string $column, string $selectAlias): string
{
    return adminTableColumnExists($con, $table, $column)
        ? "{$alias}.`{$column}` AS `{$selectAlias}`"
        : "NULL AS `{$selectAlias}`";
}

$hasDiaryColumns = adminAssignedJobsColumnExists($con, 'start_time')
    && adminAssignedJobsColumnExists($con, 'end_time')
    && adminAssignedJobsColumnExists($con, 'notes')
    && adminAssignedJobsColumnExists($con, 'location_id')
    && adminAssignedJobsColumnExists($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        ", [
    adminOptionalColumnSelect($con, 'locations', 'l', 'locaddress1', 'locaddress1'),
    adminOptionalColumnSelect($con, 'locations', 'l', 'locaddress2', 'locaddress2'),
    adminOptionalColumnSelect($con, 'locations', 'l', 'locaddress3', 'locaddress3'),
    adminOptionalColumnSelect($con, 'locations', 'l', 'locaddress4', 'locaddress4')
]);
$clientAddressSelect = implode(",\n        ", [
    adminOptionalColumnSelect($con, 'clientdetails', 'cd', 'address1', 'client_address1'),
    adminOptionalColumnSelect($con, 'clientdetails', 'cd', 'address2', 'client_address2'),
    adminOptionalColumnSelect($con, 'clientdetails', 'cd', 'town', 'client_town'),
    adminOptionalColumnSelect($con, 'clientdetails', 'cd', 'county', 'client_county')
]);

// Define date ranges for overdue, today, this week, and this month
$currentDate = time();
$todayStart = strtotime('today midnight');
$todayEnd = strtotime('tomorrow midnight') - 1;
$weekStart = strtotime('monday this week');
$weekEnd = strtotime('sunday this week 23:59:59');
$monthStart = strtotime('first day of this month');
$monthEnd = strtotime('last day of this month 23:59:59');
$sql = "
     SELECT 
        aa.id, 
        aa.appointment_date,
        $diarySelect
        cd.clientname, 
        cd.clientnumber,
        $clientAddressSelect,
        cd.postcode AS client_postcode,
        l.locname,
        $locationAddressSelect,
        l.postcode AS location_postcode,
        s.id AS surveyor_id,  -- Select the surveyor ID here
        CONCAT(s.forename, ' ', s.surname) AS surveyor, 
        COUNT(DISTINCT i.itemnumber) AS total_inspections,
        SUM(CASE WHEN i.duedate < $todayStart AND i.statuslive = 1 THEN 1 ELSE 0 END) AS overdue,
        SUM(CASE WHEN i.duedate BETWEEN $todayStart AND $todayEnd AND i.statuslive = 1 THEN 1 ELSE 0 END) AS due_today,
        SUM(CASE WHEN i.duedate BETWEEN $weekStart AND $weekEnd AND i.statuslive = 1 THEN 1 ELSE 0 END) AS due_this_week,
        SUM(CASE WHEN i.duedate BETWEEN $monthStart AND $monthEnd AND i.statuslive = 1 THEN 1 ELSE 0 END) AS due_this_month,
        SUM(CASE WHEN i.duedate <= $todayEnd AND i.statuslive = 1 THEN COALESCE(dp.units, 0) ELSE 0 END) AS ui_units_due,
        SUM(CASE WHEN i.duedate <= $todayEnd AND i.statuslive = 1 AND dp.units IS NULL THEN 1 ELSE 0 END) AS ui_missing_due,
        CASE aa.status 
            WHEN 0 THEN 'Not Started' 
            WHEN 1 THEN 'In Progress' 
            WHEN 2 THEN 'Completed' 
        END AS status
    FROM admin_assignments aa
    LEFT JOIN clientdetails cd ON aa.client_id = cd.clientnumber
    LEFT JOIN surveyor s ON aa.surveyor_id = s.id
    LEFT JOIN locations l ON " . ($hasDiaryColumns ? "aa.location_id = l.locnumber" : "1 = 0") . "
    LEFT JOIN itemdetails i ON i.clientnumber = cd.clientnumber
        AND i.statuslive = 1
        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
    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(['jobs' => [], 'error' => $con->error]);
    exit;
}
$stmt->execute();
$result = $stmt->get_result();
$jobs = [];

while ($row = $result->fetch_assoc()) {
    $addressBits = [];
    foreach (['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 (['client_address1', 'client_address2', 'client_town', 'client_county', 'client_postcode'] as $key) {
            if (!empty($row[$key])) $addressBits[] = $row[$key];
        }
    }
    $row['map_query'] = implode(', ', $addressBits);
    $jobs[] = $row;
}

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

$stmt->close();
