<?php
/**
 * Domain Synchronization Script for WHP
 * Syncs domains between WHP database and mail server
 */

require_once '/docker/whp/web/libs/emailmgmt.php';
require_once '/docker/whp/web/libs/mysqlmgmt.php';

echo "=== Domain Synchronization with Mail Server ===\n\n";

$EmailMgmt = new emailmgmt();
$MySQLMgmt = new mysqlmgmt();
$db = $MySQLMgmt->getMySQLConnection();

if (!$db) {
    echo "✗ Database connection failed\n";
    exit(1);
}

// Test mail server connection
echo "1. Testing mail server connection...\n";
$connection_result = $EmailMgmt->testMailServerConnection();
if ($connection_result['status'] === 'success') {
    echo "   ✓ Mail server connection successful\n";
} else {
    echo "   ✗ Mail server connection failed: " . $connection_result['message'] . "\n";
    echo "   Continuing with database operations only...\n\n";
}

// Get domains from WHP database
echo "2. Getting domains from WHP database...\n";
$stmt = $db->prepare("
    SELECT domain_name, username, active, created_at 
    FROM whp.domains 
    WHERE active = 1 
    ORDER BY domain_name
");
$stmt->execute();
$whp_domains = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "   ✓ Found " . count($whp_domains) . " active domains in WHP\n";

// Get domains from mail server
echo "3. Getting domains from mail server...\n";
$mail_domains_result = $EmailMgmt->listMailServerDomains();
if ($mail_domains_result['status'] === '0') {
    $mail_domains = $mail_domains_result['domains'];
    echo "   ✓ Found " . count($mail_domains) . " domains on mail server\n";
} else {
    echo "   ✗ Failed to get domains from mail server: " . $mail_domains_result['msg'] . "\n";
    $mail_domains = [];
}

// Extract domain names from mail server response
$mail_domain_names = [];
if (!empty($mail_domains)) {
    foreach ($mail_domains as $domain) {
        if (isset($domain['name'])) {
            $mail_domain_names[] = $domain['name'];
        }
    }
}

// Find domains that exist in WHP but not on mail server
echo "4. Analyzing domain synchronization...\n";
$whp_domain_names = array_column($whp_domains, 'domain_name');
$missing_on_mail = array_diff($whp_domain_names, $mail_domain_names);
$missing_in_whp = array_diff($mail_domain_names, $whp_domain_names);

if (empty($missing_on_mail) && empty($missing_in_whp)) {
    echo "   ✓ All domains are synchronized between WHP and mail server\n";
} else {
    if (!empty($missing_on_mail)) {
        echo "   ⚠ Domains in WHP but missing on mail server (" . count($missing_on_mail) . "):\n";
        foreach ($missing_on_mail as $domain) {
            echo "     - $domain\n";
        }
    }
    
    if (!empty($missing_in_whp)) {
        echo "   ⚠ Domains on mail server but missing in WHP (" . count($missing_in_whp) . "):\n";
        foreach ($missing_in_whp as $domain) {
            echo "     - $domain\n";
        }
    }
}

// Interactive mode for domain management
echo "\n5. Domain Management Options:\n";
echo "   [1] Create missing domains on mail server\n";
echo "   [2] Delete domains from mail server\n";
echo "   [3] Show detailed domain information\n";
echo "   [4] Exit\n";

echo "\nEnter your choice (1-4): ";
$handle = fopen("php://stdin", "r");
$choice = trim(fgets($handle));
fclose($handle);

switch ($choice) {
    case '1':
        if (!empty($missing_on_mail)) {
            echo "\nCreating missing domains on mail server...\n";
            foreach ($missing_on_mail as $domain) {
                echo "Creating domain: $domain\n";
                $result = $EmailMgmt->createMailServerDomain($domain);
                if ($result['status'] === '0') {
                    echo "   ✓ Created successfully\n";
                } else {
                    echo "   ✗ Failed: " . $result['msg'] . "\n";
                }
            }
        } else {
            echo "No domains to create on mail server.\n";
        }
        break;
        
    case '2':
        if (!empty($mail_domain_names)) {
            echo "\nDomains on mail server:\n";
            foreach ($mail_domain_names as $index => $domain) {
                echo "   [" . ($index + 1) . "] $domain\n";
            }
            echo "\nEnter domain number to delete (or 'all' for all domains): ";
            $handle = fopen("php://stdin", "r");
            $delete_choice = trim(fgets($handle));
            fclose($handle);
            
            if ($delete_choice === 'all') {
                echo "\nDeleting all domains from mail server...\n";
                foreach ($mail_domain_names as $domain) {
                    echo "Deleting domain: $domain\n";
                    $result = $EmailMgmt->deleteMailServerDomain($domain);
                    if ($result['status'] === '0') {
                        echo "   ✓ Deleted successfully\n";
                    } else {
                        echo "   ✗ Failed: " . $result['msg'] . "\n";
                    }
                }
            } elseif (is_numeric($delete_choice) && $delete_choice > 0 && $delete_choice <= count($mail_domain_names)) {
                $domain_to_delete = $mail_domain_names[$delete_choice - 1];
                echo "\nDeleting domain: $domain_to_delete\n";
                $result = $EmailMgmt->deleteMailServerDomain($domain_to_delete);
                if ($result['status'] === '0') {
                    echo "   ✓ Deleted successfully\n";
                } else {
                    echo "   ✗ Failed: " . $result['msg'] . "\n";
                }
            } else {
                echo "Invalid choice.\n";
            }
        } else {
            echo "No domains on mail server to delete.\n";
        }
        break;
        
    case '3':
        echo "\nDetailed domain information:\n";
        echo "\nWHP Domains:\n";
        foreach ($whp_domains as $domain) {
            echo "   Domain: " . $domain['domain_name'] . "\n";
            echo "   User: " . $domain['username'] . "\n";
            echo "   Created: " . $domain['created_at'] . "\n";
            echo "   Status: " . ($domain['active'] ? 'Active' : 'Inactive') . "\n";
            
            // Check if domain exists on mail server
            $mail_result = $EmailMgmt->getMailServerDomain($domain['domain_name']);
            if ($mail_result['status'] === '0') {
                echo "   Mail Server: ✓ Exists\n";
                $mail_domain = $mail_result['domain'];
                echo "   Mail Server Created: " . $mail_domain['created'] . "\n";
                echo "   Mail Server Disabled: " . ($mail_domain['disabled'] ? 'Yes' : 'No') . "\n";
            } else {
                echo "   Mail Server: ✗ Not found\n";
            }
            echo "\n";
        }
        break;
        
    case '4':
        echo "Exiting...\n";
        break;
        
    default:
        echo "Invalid choice.\n";
        break;
}

echo "\n=== Domain Synchronization Complete ===\n";
?> 