#!/usr/bin/env php
<?php
/**
 * Check status of backups in the system
 */

require_once(__DIR__ . '/../web-files/configs/config.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');

$mysql = new mysqlmgmt();
$db = $mysql->getMySQLConnection();
$db->exec("USE whp");

echo "\n=== BACKUP STATUS CHECK ===\n\n";

// Check backups by status
$statuses = ['pending', 'running', 'completed', 'failed'];
foreach ($statuses as $status) {
    $stmt = $db->prepare("SELECT COUNT(*) FROM backup_history WHERE status = ?");
    $stmt->execute([$status]);
    $count = $stmt->fetchColumn();
    echo "Status '$status': $count backups\n";
}

echo "\n=== RECENT BACKUPS ===\n\n";

// Show recent backups
$stmt = $db->query("
    SELECT id, user, backup_type, backup_name, status,
           started_at, completed_at, error_message
    FROM backup_history
    ORDER BY started_at DESC
    LIMIT 10
");

$backups = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($backups)) {
    echo "No backups found.\n";
} else {
    foreach ($backups as $backup) {
        echo "ID: {$backup['id']}\n";
        echo "  User: {$backup['user']}\n";
        echo "  Type: {$backup['backup_type']}\n";
        echo "  Name: {$backup['backup_name']}\n";
        echo "  Status: {$backup['status']}\n";
        echo "  Started: {$backup['started_at']}\n";
        echo "  Completed: " . ($backup['completed_at'] ?? 'N/A') . "\n";
        if ($backup['error_message']) {
            echo "  Error: {$backup['error_message']}\n";
        }
        echo "\n";
    }
}

// Check for stuck backups (running for more than 30 minutes)
echo "=== STUCK BACKUPS (running > 30 min) ===\n\n";

$stmt = $db->query("
    SELECT id, user, backup_name, started_at,
           TIMESTAMPDIFF(MINUTE, started_at, NOW()) as minutes_running
    FROM backup_history
    WHERE status = 'running'
    AND started_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE)
");

$stuckBackups = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($stuckBackups)) {
    echo "No stuck backups found.\n";
} else {
    foreach ($stuckBackups as $backup) {
        echo "ID {$backup['id']}: {$backup['backup_name']} - running for {$backup['minutes_running']} minutes\n";
        echo "  Started: {$backup['started_at']}\n";
        echo "  User: {$backup['user']}\n\n";
    }

    echo "To reset stuck backups to 'failed', run:\n";
    echo "  php " . __FILE__ . " --reset-stuck\n";
}

// Handle reset option
if (in_array('--reset-stuck', $argv)) {
    echo "\n=== RESETTING STUCK BACKUPS ===\n";

    $stmt = $db->prepare("
        UPDATE backup_history
        SET status = 'failed',
            error_message = 'Backup stuck in running state - reset by admin',
            completed_at = NOW()
        WHERE status = 'running'
        AND started_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE)
    ");

    $stmt->execute();
    $affected = $stmt->rowCount();

    echo "Reset $affected stuck backup(s) to 'failed' status.\n";
}

echo "\n";