<?php


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

function adminClientsColumnExists(mysqli $con, string $column): bool
{
    $stmt = $con->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'clientdetails' 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 adminClientsOptionalColumn(mysqli $con, string $column, string $alias): string
{
    return adminClientsColumnExists($con, $column)
        ? "MAX(cd.`{$column}`) AS `{$alias}`"
        : "NULL AS `{$alias}`";
}

$addressSelect = implode(",\n    ", [
    adminClientsOptionalColumn($con, 'address1', 'address1'),
    adminClientsOptionalColumn($con, 'address2', 'address2'),
    adminClientsOptionalColumn($con, 'town', 'town'),
    adminClientsOptionalColumn($con, 'county', 'county'),
    adminClientsOptionalColumn($con, 'postcode', 'postcode')
]);

/* Show all live clients with counts of overdue and pending items */
$sql = "
  SELECT
    cd.clientnumber,
    cd.clientname,
    $addressSelect,
    COUNT(i.itemnumber) AS total_items,
    SUM(CASE WHEN i.duedate < UNIX_TIMESTAMP(NOW()) THEN 1 ELSE 0 END) AS overdue,
    SUM(CASE WHEN i.duedate >= UNIX_TIMESTAMP(NOW())
              AND i.duedate <= UNIX_TIMESTAMP(NOW() + INTERVAL 30 DAY) THEN 1 ELSE 0 END) AS pending
  FROM clientdetails cd
  LEFT JOIN itemdetails i
    ON i.clientnumber = cd.clientnumber
   AND i.statuslive = 1
   AND i.duedate IS NOT NULL
   AND i.duedate > 0
  WHERE cd.statuslive = 1
  GROUP BY cd.clientnumber, cd.clientname
";

/* If you only want clients with any expected inspections, add:
   HAVING (overdue + pending) > 0
*/

$result = $con->query($sql);
$clients = [];

while ($row = $result->fetch_assoc()) {
    $expected = (int)$row['overdue'] + (int)$row['pending'];
    $addressBits = array_filter([
        $row['address1'] ?? '',
        $row['address2'] ?? '',
        $row['town'] ?? '',
        $row['county'] ?? '',
        $row['postcode'] ?? ''
    ], fn($value) => trim((string)$value) !== '');
    $clients[] = [
        'clientnumber' => (int)$row['clientnumber'],
        'clientname' => $row['clientname'],
        'expected_inspections' => $expected,
        'map_query' => implode(', ', $addressBits)
    ];
}

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

$con->close();
