#!/usr/bin/env php
<?php
require '/etc/freepbx.conf';
$pdo = FreePBX::Database();
$row = $pdo->query("SELECT * FROM module_xml WHERE id='security'")
    ->fetch(PDO::FETCH_ASSOC);
$data = json_decode($row['data'] ?? '', true);

if (!is_array($data) || !array_key_exists('issue', $data) || $data['issue'] !== false) {
    exit("Cache does not contain the diagnosed value; nothing changed.\n");
}

umask(0077);
$backup = '/root/freepbx-security-cache-'.date('Ymd-His').'.json';
if (file_put_contents($backup, json_encode($row)) === false) {
    exit("Backup failed; nothing changed.\n");
}

$data['issue'] = [];
$stmt = $pdo->prepare("UPDATE module_xml SET data=? WHERE id='security'");
$stmt->execute([json_encode($data)]);
echo "Security cache repaired. Backup: $backup\n";

