#!/usr/bin/php
<?php
/**
 * Test script to verify auto-recreation functionality
 * Usage: php test-auto-recreate.php [image_name]
 */

// Include configuration file first to define MySQL constants
require_once(__DIR__ . '/../web-files/configs/config.php');

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

try {
    // Create direct PDO connection (use 127.0.0.1 for host-based script)
    $dsn = "mysql:host=127.0.0.1;port=3306;dbname=whp;charset=utf8mb4";
    $db = new PDO($dsn, 'root', trim(MYSQL_PASS), [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    
    $image_name = $argv[1] ?? null;
    
    // Query to check sites with auto_recreate_on_update enabled
    $query = "
        SELECT 
            s.id as site_id,
            s.site_name,
            s.username,
            s.auto_recreate_on_update,
            ct.name as container_type,
            ct.base_image,
            d.domain_name as primary_domain,
            COUNT(sc.id) as container_count
        FROM whp.sites s
        JOIN whp.container_types ct ON s.container_type_id = ct.id
        JOIN whp.domains d ON s.primary_domain_id = d.id
        LEFT JOIN whp.site_containers sc ON s.id = sc.site_id
        WHERE s.auto_recreate_on_update = 1
    ";
    
    if ($image_name) {
        $query .= " AND ct.base_image = ?";
    }
    
    $query .= " GROUP BY s.id ORDER BY s.site_name";
    
    $stmt = $db->prepare($query);
    if ($image_name) {
        $stmt->execute([$image_name]);
        echo "Sites with auto-recreate enabled for image: $image_name\n";
    } else {
        $stmt->execute();
        echo "All sites with auto-recreate enabled:\n";
    }
    
    echo str_repeat("=", 80) . "\n";
    
    $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($sites)) {
        echo "No sites found with auto_recreate_on_update enabled";
        if ($image_name) {
            echo " for image $image_name";
        }
        echo "\n";
    } else {
        printf("%-30s %-20s %-30s %s\n", "Site Name", "Username", "Container Type", "Containers");
        echo str_repeat("-", 80) . "\n";
        
        foreach ($sites as $site) {
            printf("%-30s %-20s %-30s %d\n", 
                $site['site_name'],
                $site['username'],
                $site['container_type'] . " (" . $site['base_image'] . ")",
                $site['container_count']
            );
        }
        
        echo "\nTotal sites: " . count($sites) . "\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}