<?php require_once "/var/www/html/config.database.php"; ?>
<?php
/**
 * =====================================================================
 * FX-HUNTER — COMPLETE SIGNAL FILE MANAGEMENT ENGINE (FINAL WORKING)
 *
 * ✅ Creates missing signal files for ALL licenses in fxh_licenses
 * ✅ Deletes orphan files that no longer exist in DB
 * ✅ NO dependency on `decrypted` column
 * ✅ NO dependency on `active` column
 * ✅ SAFE: does not delete valid files
 * ✅ Dashboard-trigger compatible
 * =====================================================================
 */

require_once __DIR__ . "/../portal/config.php";

$dir = __DIR__ . "/signals";
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}

$logFile = __DIR__ . "/debug_signal_file_manager.txt";
file_put_contents(
    $logFile,
    "\n---- RUN AT ".date("Y-m-d H:i:s")." ----\n",
    FILE_APPEND
);


/* =====================================================
   1) LOAD ALL LICENSE KEYS FROM fxh_licenses
===================================================== */

$dbLicenses = [];

$q = $conn->query("
    SELECT license_key
    FROM fxh_licenses
    WHERE license_key IS NOT NULL
      AND license_key != ''
");

while ($row = $q->fetch_assoc()) {

    $clean = preg_replace('/[^0-9A-Za-z_-]/', '', trim($row['license_key']));

    if ($clean !== '') {
        $dbLicenses[] = $clean;
    }
}

file_put_contents(
    $logFile,
    "DB LICENSE COUNT: " . count($dbLicenses) . "\n",
    FILE_APPEND
);


/* =====================================================
   2) SCAN SIGNAL FOLDER
===================================================== */

$folderFiles = glob($dir . "/latest_signal_*.txt") ?: [];
$folderLicenses = [];

foreach ($folderFiles as $file) {

    if (preg_match('/latest_signal_(.*)\.txt$/', basename($file), $m)) {
        $folderLicenses[] = $m[1];
    }
}


/* =====================================================
   3) CREATE MISSING FILES
===================================================== */

$created = 0;

foreach ($dbLicenses as $lic) {

    $path = $dir . "/latest_signal_" . $lic . ".txt";

    if (!file_exists($path)) {

        file_put_contents(
            $path,
            "WAITING|" . gmdate("Y-m-d H:i:s") . PHP_EOL
        );

        $created++;

        file_put_contents(
            $logFile,
            "CREATED FILE FOR LICENSE: $lic\n",
            FILE_APPEND
        );
    }
}


/* =====================================================
   4) DELETE ORPHAN FILES
===================================================== */

$deleted = 0;

foreach ($folderLicenses as $lic) {

    if (!in_array($lic, $dbLicenses, true)) {

        $path = $dir . "/latest_signal_" . $lic . ".txt";

        if (file_exists($path)) {

            unlink($path);
            $deleted++;

            file_put_contents(
                $logFile,
                "DELETED ORPHAN FILE: $lic\n",
                FILE_APPEND
            );
        }
    }
}


/* =====================================================
   5) FINAL REPORT
===================================================== */

$msg = "✅ SIGNAL MANAGER DONE | Created=$created | Deleted=$deleted";

file_put_contents($logFile, $msg . "\n", FILE_APPEND);

echo $msg;
