<?php
// save_client_site.php
// Adds a new Site Name for a client. Follows the exact pattern of
// save_client.php: PDO prepared statements, CSRF, role gate, audit columns.
require_once 'includes/auth.php';
require_role(['admin', 'inspector'], true);
require_once 'db.php';

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

$clientId = $_POST['client_id'] ?? null;
$siteName = trim($_POST['site_name'] ?? '');

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

$userId = current_user()['id'] ?? null;

try {
    // Confirm the client exists and is not soft-deleted before attaching a
    // site to it -- avoids creating orphaned/invalid site records.
    $clientCheck = $pdo->prepare('SELECT ClientID FROM tbl_clients WHERE ClientID = ? AND Deleted_At IS NULL LIMIT 1');
    $clientCheck->execute([$clientId]);
    if (!$clientCheck->fetchColumn()) {
        echo json_encode(['status' => 'error', 'message' => 'Client not found.']);
        exit;
    }

    $stmt = $pdo->prepare('INSERT INTO tbl_client_sites (ClientID, Site_Name, Created_By, Updated_By) VALUES (?, ?, ?, ?)');
    $stmt->execute([$clientId, $siteName, $userId, $userId]);

    echo json_encode([
        'status'    => 'success',
        'site_id'   => (int) $pdo->lastInsertId(),
        'site_name' => $siteName,
    ]);
} catch (\PDOException $e) {
    error_log('save_client_site.php error: ' . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'A database error occurred while saving the site.']);
}
