<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit(1);
}

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/crm.php';

$options = getopt('', ['deal-id::']);
$dealId = trim((string) ($options['deal-id'] ?? ''));
if ($dealId === '') {
    $dealId = '999' . getmypid();
}
$lockPath = dirname((string) config('STATE_FILE')) . '/locks/qualification_workflow_' . $dealId . '.lock';
$handle = null;
$ok = false;
$error = '';

try {
    $handle = acquireQualificationWorkflowLock($dealId);
    $ok = is_resource($handle) && is_file($lockPath);
} catch (Throwable $exception) {
    $error = $exception->getMessage();
} finally {
    if (is_resource($handle)) {
        releaseQualificationWorkflowLock($handle);
    }
}

$permissions = is_file($lockPath) ? substr(sprintf('%o', fileperms($lockPath)), -4) : '';
if (is_file($lockPath)) {
    @unlink($lockPath);
}

echo json_encode([
    'ok' => $ok,
    'permissions' => $permissions,
    'error' => $error,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;

exit($ok ? 0 : 1);
