<?php
$initialDir = getcwd();
chdir(__DIR__ . '/../');

require_once __DIR__ . '/../vendor/autoload.php';

use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use GuzzleHttp\Client;

// -- Configuration --
$customAttributeKey = 'passwordAntenaCliente';

// -- Initialization --
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$token = $config['apitoken'] ?? '';

if (empty($token)) {
    fwrite(STDERR, "Error: API Token is missing in plugin configuration.\n");
    exit(1);
}

// Initialize UCRM Client
$client = new Client([
    'base_uri' => $apiUrl,
    'verify' => false,
    'headers' => [
        'X-Auth-App-Key' => $token,
        'Content-Type' => 'application/json',
    ],
]);
$ucrmApi = new UcrmApi($client, $token);

function fetchAllClients($client)
{
    $allClients = [];
    $page = 1;
    $limit = 500;

    do {
        try {
            $response = $client->get('clients', [
                'query' => [
                    'limit' => $limit,
                    'offset' => ($page - 1) * $limit,
                    'isArchived' => 0,
                ]
            ]);

            $data = json_decode($response->getBody()->getContents(), true);

            if (empty($data)) break;
            $allClients = array_merge($allClients, $data);
            if (count($data) < $limit) break;
            $page++;
        } catch (\Exception $e) {
            fwrite(STDERR, "Error fetching page $page: " . $e->getMessage() . "\n");
            break;
        }
    } while (true);

    return $allClients;
}

// 0. Resolve Attribute ID
$customAttributeId = null;
try {
    $attributes = $ucrmApi->get('custom-attributes', ['attributeType' => 'client']);
    foreach ($attributes as $attr) {
        if ($attr['key'] === $customAttributeKey) {
            $customAttributeId = $attr['id'];
            break;
        }
    }
} catch (\Exception $e) {
    fwrite(STDERR, "Error fetching attributes: " . $e->getMessage() . "\n");
    exit(1);
}

if (!$customAttributeId) {
    fwrite(STDERR, "Error: Custom attribute '$customAttributeKey' not found.\n");
    exit(1);
}

// 1. Fetch all clients
fwrite(STDERR, "Fetching clients...\n");
$clients = fetchAllClients($client);
fwrite(STDERR, "Total active clients fetched: " . count($clients) . "\n");

// 2. Identify Invalid
$results = [];

foreach ($clients as $clientData) {
    $password = null;
    $attributes = $clientData['attributes'] ?? [];

    foreach ($attributes as $attr) {
        if ($attr['key'] === $customAttributeKey) {
            $password = $attr['value'];
            break;
        }
    }

    // Detect explicit error states that should be retried (e.g. "⚠️ Error Regenerating...")
    $isError = (stripos((string)$password, 'Error') !== false);

    // Detect managed states (valid non-passwords like "⚠️ Sin sitio", "Servicio Finalizado", etc.)
    $isManaged = (strpos((string)$password, 'Servicio') !== false || strpos((string)$password, '⚠️') !== false);

    $isValid = true;
    if (empty($password)) {
        $isValid = false;
    } elseif ($isError) {
        $isValid = false;
    } elseif (!$isManaged) {
        $len = strlen($password);
        if ($len < 8 || $len > 20) {
            $isValid = false;
        } elseif (strpos($password, ' ') !== false) {
            $isValid = false;
        }
    }

    if (!$isValid) {
        $results[] = [
            'id' => $clientData['id'],
            'name' => ($clientData['firstName'] ?? '') . ' ' . ($clientData['lastName'] ?? '')
        ];
    }
}

// 3. Output CSV

// 3. Output CSV

$outputFile = null;
foreach ($argv as $arg) {
    if (strpos($arg, '--output=') === 0) {
        $outputFile = substr($arg, 9);
    }
}

if ($outputFile) {
    // Resolve relative path to initial execution directory
    if ($outputFile[0] !== '/') {
        global $initialDir;
        $outputFile = $initialDir . '/' . $outputFile;
    }
    $outputHandle = fopen($outputFile, 'w');
    fwrite(STDERR, "Writing to file: $outputFile\n");
} else {
    $outputHandle = STDOUT;
}

foreach ($results as $row) {
    fwrite($outputHandle, $row['id'] . "\n");
}

if ($outputFile) {
    fclose($outputHandle);
    fwrite(STDERR, "Found " . count($results) . " invalid clients written to $outputFile.\n");
} else {
    fwrite(STDERR, "Found " . count($results) . " invalid clients.\n");
}
