<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/output_devices_lib.php';
require_once __DIR__ . '/subscriber_contracts_lib.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

$conn = $GLOBALS['conn'] ?? ensure_db(true);
if (!($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['ok'=>false, 'error'=>'database_unavailable']);
    exit;
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !ua_csrf_verify()) {
    http_response_code(403);
    echo json_encode(['ok'=>false, 'error'=>'invalid_request']);
    exit;
}

$input = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($input)) $input = [];
$actor = ua_output_authorized_scope($conn, (string)($input['scope_key'] ?? ''));
if (empty($actor['authorized'])) {
    http_response_code(401);
    echo json_encode(['ok'=>false, 'error'=>'AUTH_REQUIRED']);
    exit;
}

$contractId = max(0, (int)($input['contract_id'] ?? 0));
$stmt = $conn->prepare(
    'SELECT c.id,c.subscriber_id,c.created_by,s.created_by_type,s.created_by_id
       FROM subscriber_contracts c
       JOIN subscribers s ON s.id=c.subscriber_id
      WHERE c.id=? LIMIT 1'
);
$stmt->bind_param('i', $contractId);
$stmt->execute();
$contract = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$contract) {
    http_response_code(404);
    echo json_encode(['ok'=>false, 'error'=>'contract_not_found']);
    exit;
}

if ((string)$actor['type'] === 'agent') {
    $agentId = (int)$actor['id'];
    $ownsSubscriber = strtolower(trim((string)$contract['created_by_type'])) === 'agent'
        && (int)$contract['created_by_id'] === $agentId;
    $agentResult = @$conn->query("SELECT full_name,name FROM agents WHERE id={$agentId} LIMIT 1");
    $agent = $agentResult ? ($agentResult->fetch_assoc() ?: []) : [];
    $agentName = trim((string)($agent['full_name'] ?? $agent['name'] ?? ''));
    $generatedByAgent = $agentName !== ''
        && hash_equals('AGENT: ' . $agentName, trim((string)$contract['created_by']));
    if (!$ownsSubscriber && !$generatedByAgent) {
        http_response_code(403);
        echo json_encode(['ok'=>false, 'error'=>'contract_scope_denied']);
        exit;
    }
}

$ok = sc_mark_printed($conn, $contractId);
echo json_encode(['ok'=>$ok], JSON_UNESCAPED_UNICODE);
