<?php
// delete_client_site.php
// Soft-deletes a client site (Deleted_At). Never hard-deletes: a past
// certificate may still reference this SiteID via tbl_jobs.Site_ID, and
// removing the site here must not erase what those certificates show.
require_once 'includes/auth.php';
require_role(['admin', 'inspector'], true);
require_once 'db.php';

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

$siteId = $_POST['site_id'] ?? null;
if (!$siteId || !ctype_digit((string) $siteId)) {
    echo json_encode(['status' => 'error', 'message' => 'A valid Site is required.']);
    exit;
}

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

try {
    $stmt = $pdo->prepare('UPDATE tbl_client_sites SET Deleted_At = NOW(), Updated_By = ? WHERE SiteID = ? AND Deleted_At IS NULL');
    $stmt->execute([$userId, $siteId]);

    if ($stmt->rowCount() === 0) {
        echo json_encode(['status' => 'error', 'message' => 'Site not found or already removed.']);
        exit;
    }

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