<?php
// get_client_sites.php
// JSON lookup of a client's active (non-deleted) sites. Used by clients.php's
// site-management panel and available for any other View form that needs a
// Site Name dropdown for a given client.
require_once 'includes/auth.php';
require_role(['admin', 'inspector', 'coordinator'], true);
require_once 'db.php';

header('Content-Type: application/json');

$clientId = $_GET['client_id'] ?? null;
if (!$clientId || !ctype_digit((string) $clientId)) {
    echo json_encode(['status' => 'error', 'message' => 'A valid Client is required.']);
    exit;
}

try {
    $stmt = $pdo->prepare('SELECT SiteID, Site_Name FROM tbl_client_sites WHERE ClientID = ? AND Deleted_At IS NULL ORDER BY Site_Name ASC');
    $stmt->execute([$clientId]);
    $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['status' => 'success', 'sites' => $sites]);
} catch (\PDOException $e) {
    error_log('get_client_sites.php error: ' . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'A database error occurred while fetching sites.']);
}
