#!/usr/bin/php
<?php
/**
 * DNS Challenge Verification Script
 *
 * Runs via cron every minute to check and verify pending DNS-01 challenges
 * for wildcard SSL certificates. Challenges in 'created' status that were
 * requested more than 60 seconds ago are verified.
 *
 * Usage: php /root/whp/scripts/verify-dns-challenges.php
 */

// Change to web directory for includes
chdir('/docker/whp/web');

require_once('/docker/whp/web/configs/config.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/ssl_manager.php');

$timestamp = date('Y-m-d H:i:s');

try {
    $MySQLMgmt = new mysqlmgmt();
    $db = $MySQLMgmt->getMySQLConnection();

    if (!$db) {
        echo "[{$timestamp}] ERROR: Database connection failed\n";
        exit(1);
    }

    // Find challenges in 'created' status that were requested more than 60 seconds ago
    $stmt = $db->prepare("
        SELECT id, site_id, domain_name, challenge_fqdn, status
        FROM whp.dns_challenges
        WHERE status = 'created'
        AND requested_at < DATE_SUB(NOW(), INTERVAL 60 SECOND)
        ORDER BY requested_at ASC
        LIMIT 10
    ");
    $stmt->execute();
    $challenges = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($challenges)) {
        // No pending challenges - silent exit
        exit(0);
    }

    echo "[{$timestamp}] Found " . count($challenges) . " pending DNS challenge(s) to verify\n";

    $ssl_manager = new ssl_manager();

    foreach ($challenges as $challenge) {
        echo "[{$timestamp}] Verifying challenge #{$challenge['id']} for {$challenge['domain_name']}...\n";

        $result = $ssl_manager->verify_dns_challenge($challenge['id']);

        if ($result['success']) {
            echo "[{$timestamp}] SUCCESS: Challenge #{$challenge['id']} completed - {$result['message']}\n";
        } else {
            echo "[{$timestamp}] PENDING: Challenge #{$challenge['id']} - {$result['error']}\n";
        }
    }

    // Clean up old failed/completed challenges (older than 7 days)
    $stmt = $db->prepare("
        DELETE FROM whp.dns_challenges
        WHERE status IN ('completed', 'failed')
        AND requested_at < DATE_SUB(NOW(), INTERVAL 7 DAY)
    ");
    $stmt->execute();
    $cleaned = $stmt->rowCount();
    if ($cleaned > 0) {
        echo "[{$timestamp}] Cleaned up {$cleaned} old challenge record(s)\n";
    }

} catch (Exception $e) {
    echo "[{$timestamp}] ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
