<?php
declare(strict_types=1);

const ADMIN_DB_HOST = 'localhost';
const ADMIN_DB_USER = 'enrepco_stmadmacc';
const ADMIN_DB_PASS = 'gCV^Aj@ky}19';
const ADMIN_DB_NAME = 'enrepco_sysmanager';
const TENANT_HOME = '/home/enrepco';
const DOMAIN_SUFFIX = 'enrep.co.uk';
const LOG_FILE = TENANT_HOME . '/maintPoolWorker.log';
const LOCK_FILE = TENANT_HOME . '/maintPoolWorker.lock';

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit("CLI only\n");
}

function pool_log(string $message): void
{
    $line = '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL;
    @file_put_contents(LOG_FILE, $line, FILE_APPEND | LOCK_EX);
    echo $line;
}

set_exception_handler(function (Throwable $e): void {
    pool_log('FATAL: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    exit(1);
});

$lock = fopen(LOCK_FILE, 'c');
if ($lock === false) {
    throw new RuntimeException('Unable to open worker lock file');
}
if (!flock($lock, LOCK_EX | LOCK_NB)) {
    pool_log('Another maintenance pool run is already active; exiting');
    fclose($lock);
    exit(0);
}

pool_log('Maintenance pool started');

$admin = new mysqli(ADMIN_DB_HOST, ADMIN_DB_USER, ADMIN_DB_PASS, ADMIN_DB_NAME);
if ($admin->connect_errno) {
    throw new RuntimeException('Admin DB connect failed: ' . $admin->connect_error);
}
$admin->set_charset('utf8mb4');

$result = $admin->query("
    SELECT client_id, company_name, subdomain_prefix
    FROM client_subscriptions
    WHERE status = 'active'
      AND deployed = 1
    ORDER BY client_id ASC
");
if ($result === false) {
    throw new RuntimeException('Active client query failed: ' . $admin->error);
}

$total = 0;
$completed = 0;
$failed = 0;
$skipped = 0;

while ($client = $result->fetch_assoc()) {
    $total++;
    $clientId = (int)$client['client_id'];
    $company = trim((string)$client['company_name']);
    $prefix = strtolower(trim((string)$client['subdomain_prefix']));

    if (!preg_match('/^[a-z0-9][a-z0-9-]*$/', $prefix)) {
        $skipped++;
        pool_log("SKIP client={$clientId} company={$company}: invalid subdomain prefix");
        continue;
    }

    $maintPath = TENANT_HOME . '/' . $prefix . '.' . DOMAIN_SUFFIX . '/maint.php';
    if (!is_file($maintPath)) {
        $skipped++;
        pool_log("SKIP client={$clientId} company={$company}: missing {$maintPath}");
        continue;
    }

    pool_log("RUN client={$clientId} company={$company} tenant={$prefix}");

    $output = [];
    $returnCode = 0;
    $command = escapeshellarg(PHP_BINARY) . ' -q ' . escapeshellarg($maintPath)
        . ' >> ' . escapeshellarg(LOG_FILE) . ' 2>&1';
    exec($command, $output, $returnCode);

    if ($returnCode === 0) {
        $completed++;
        pool_log("OK client={$clientId} tenant={$prefix}");
    } else {
        $failed++;
        pool_log("FAIL client={$clientId} tenant={$prefix} exit_code={$returnCode}");
    }
}

$result->free();
$admin->close();

pool_log("Maintenance pool finished total={$total} completed={$completed} failed={$failed} skipped={$skipped}");
flock($lock, LOCK_UN);
fclose($lock);

exit($failed > 0 ? 1 : 0);
