<?php
// Permission checking is now handled by the permission system in auto-prepend.php
// 
// NS Record Fix (2025): Domains now properly create 2 NS records instead of 1
// - Fixed addDefaultRecords() to add all NS records in single API call
// - PowerDNS API uses 'changetype' => 'REPLACE' which was overwriting previous NS records
// - Solution: Collect all nameservers and add them together via addMultipleRecords()

require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/pdns-integration.php');
require_once('/docker/whp/web/libs/emailmgmt.php');

$message = '';
$message_type = '';
$is_root = (defined('AUTH_USER') && AUTH_USER === 'root');

// Initialize database connection
$MySQLMgmt = new mysqlmgmt();
$db = $MySQLMgmt->getMySQLConnection();

if (!$db) {
    $message = 'Database connection failed';
    $message_type = 'danger';
    $pdns = null;
    $EmailMgmt = null;
} else {
    // Initialize PowerDNS integration
    try {
        $pdns = new PowerDNSIntegration($db);
    } catch (Exception $e) {
        $message = 'PowerDNS integration error: ' . $e->getMessage();
        $message_type = 'danger';
        $pdns = null;
    }
    
    // Initialize Email Management for mail server synchronization
    try {
        $EmailMgmt = new emailmgmt();
    } catch (Exception $e) {
        $EmailMgmt = null;
        // Don't show error for email integration as it's optional
    }
}

// Get server settings for default DNS records
$server_settings = [];
if (file_exists('/docker/whp/settings.json')) {
    $settings_content = file_get_contents('/docker/whp/settings.json');
    if ($settings_content) {
        $server_settings = json_decode($settings_content, true) ?: [];
    }
}

// Get nameservers from whp_nameservers configuration
if (isset($server_settings['whp_nameservers'])) {
    $nameservers = [
        $server_settings['whp_nameservers']['ns1'] ?? 'ns1.example.com',
        $server_settings['whp_nameservers']['ns2'] ?? 'ns2.example.com'
    ];
} else {
    $nameservers = $server_settings['nameservers'] ?? ['ns1.example.com', 'ns2.example.com'];
}
$mail_server = $server_settings['mail_server'] ?? 'mail.example.com';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_domain':
                if (!empty($_POST['domain_name']) && $pdns) {
                    try {
                        $domain_name = strtolower(trim($_POST['domain_name']));
                        
                        // Validate domain format
                        if (!filter_var('http://' . $domain_name, FILTER_VALIDATE_URL)) {
                            $message = 'Invalid domain format';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check if domain already exists in WHP
                        $stmt = $db->prepare("SELECT id FROM whp.domains WHERE domain_name = ?");
                        $stmt->execute([$domain_name]);
                        if ($stmt->fetch()) {
                            $message = 'Domain already exists in the system';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Get user ID
                        $owner_username = $is_root && !empty($_POST['owner_username']) ? $_POST['owner_username'] : AUTH_USER;
                        $stmt = $db->prepare("SELECT username FROM whp.client_allowances WHERE username = ?");
                        $stmt->execute([$owner_username]);
                        $user = $stmt->fetch();
                        
                        if (!$user) {
                            $message = 'Invalid user specified';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Create PowerDNS zone first
                        $zone_result = $pdns->createZoneForDomain($domain_name, $owner_username);
                        if (!$zone_result['success']) {
                            $message = 'Failed to create DNS zone: ' . $zone_result['error'];
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Insert domain into WHP database (no container type assigned - will be set when used in Sites)
                        $stmt = $db->prepare("
                            INSERT INTO whp.domains (domain_name, username, active) 
                            VALUES (?, ?, 1)
                        ");
                        $stmt->execute([$domain_name, $owner_username]);
                        
                        // Follow proper sequence: PowerDNS → Mail Server → DKIM Generation → DNS Record Creation
                        $mail_sync_success = true;
                        $mail_sync_message = '';
                        $dkim_success = true;
                        $dkim_message = '';
                        $dns_success = true;
                        $dns_message = '';
                        
                        if ($EmailMgmt) {
                            try {
                                // Step 1: PowerDNS zone already created above
                                
                                // Step 2: Add domain to mail server
                                $mail_result = $EmailMgmt->createMailServerDomain($domain_name, [
                                    'disabled' => false,
                                    'reference_id' => $owner_username
                                ]);
                                if ($mail_result['status'] !== '0') {
                                    $mail_sync_success = false;
                                    $mail_sync_message = $mail_result['msg'];
                                } else {
                                    // Step 2.5: Wait for mail server to process domain creation
                                    // This delay allows the mail server to fully process the domain before DKIM creation
                                    sleep(3);
                                    
                                    // Step 3: Generate DKIM records on mail server with retry logic
                                    try {
                                        $dkim_result = $EmailMgmt->createDkimRecordsWithRetry($domain_name, $owner_username, 3, 2);
                                        if ($dkim_result['status'] !== '0') {
                                            $dkim_success = false;
                                            $dkim_message = $dkim_result['msg'];
                                        } else {
                                            // Step 4: Add DKIM DNS record to PowerDNS
                                            $dns_result = $EmailMgmt->createDkimDnsRecord($domain_name, null, null, $owner_username);
                                            if ($dns_result['status'] !== '0') {
                                                $dns_success = false;
                                                $dns_message = $dns_result['msg'];
                                            }
                                        }
                                    } catch (Exception $e) {
                                        $dkim_success = false;
                                        $dkim_message = $e->getMessage();
                                    }
                                }
                            } catch (Exception $e) {
                                $mail_sync_success = false;
                                $mail_sync_message = $e->getMessage();
                            }
                        }
                        
                        // Determine success message based on all operations
                        if ($mail_sync_success && $dkim_success && $dns_success) {
                            $message = 'Domain added successfully: ' . $domain_name . ' (DNS zone, mail server, DKIM, and DNS records all configured)';
                            $message_type = 'success';
                        } else if ($mail_sync_success && $dkim_success && !$dns_success) {
                            $message = 'Domain added successfully: ' . $domain_name . '. Warning: DKIM DNS record creation failed: ' . $dns_message;
                            $message_type = 'warning';
                        } else if ($mail_sync_success && !$dkim_success) {
                            $message = 'Domain added successfully: ' . $domain_name . '. Warning: DKIM setup failed after retries: ' . $dkim_message;
                            $message_type = 'warning';
                        } else if (!$mail_sync_success) {
                            $message = 'Domain added successfully: ' . $domain_name . '. Warning: Mail server sync failed: ' . $mail_sync_message;
                            $message_type = 'warning';
                        }
                    } catch (PDOException $e) {
                        $message = 'Error adding domain: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'delete_domain':
                if (!empty($_POST['domain_id']) && $pdns) {
                    try {
                        $domain_id = intval($_POST['domain_id']);
                        
                        // Get domain info
                        $stmt = $db->prepare("
                            SELECT d.*, d.username 
                            FROM whp.domains d 
                            WHERE d.id = ?
                        ");
                        $stmt->execute([$domain_id]);
                        $domain = $stmt->fetch();
                        
                        if (!$domain) {
                            $message = 'Domain not found';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check ownership (users can delete their own domains, root can delete any)
                        if (!$is_root && $domain['username'] !== AUTH_USER) {
                            $message = 'You can only delete your own domains';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check if domain has active containers
                        $stmt = $db->prepare("SELECT COUNT(*) as count FROM whp.containers WHERE domain_id = ? AND status = 'running'");
                        $stmt->execute([$domain_id]);
                        $container_count = $stmt->fetch()['count'];
                        
                        if ($container_count > 0) {
                            $message = 'Cannot delete domain with active containers. Stop containers first.';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check site attachments. JOIN against whp.sites so we
                        // ignore orphan site_domains rows that somehow survived
                        // a site delete (cascade FK should catch this; the
                        // JOIN is defense-in-depth). Collect role info so we
                        // can decide between hard-block (primary attachment)
                        // and auto-detach (additional-only).
                        $stmt = $db->prepare("
                            SELECT s.id, s.site_name, s.active, sd.is_primary
                            FROM whp.site_domains sd
                            JOIN whp.sites s ON sd.site_id = s.id
                            WHERE sd.domain_id = ?
                            ORDER BY sd.is_primary DESC, s.id
                        ");
                        $stmt->execute([$domain_id]);
                        $linked_sites = $stmt->fetchAll(PDO::FETCH_ASSOC);

                        $primary_attachments = array_values(array_filter($linked_sites, fn($r) => (int)$r['is_primary'] === 1));
                        $additional_attachments = array_values(array_filter($linked_sites, fn($r) => (int)$r['is_primary'] !== 1));

                        if (!empty($primary_attachments)) {
                            // Primary attachment blocks the delete — removing
                            // the domain row would leave the site with no
                            // primary_domain_id reference. Operator has to
                            // change the primary or delete the site first.
                            $site_descs = array_map(function ($r) {
                                $status = $r['active'] ? '' : ' (inactive)';
                                return '#' . $r['id'] . ' ' . $r['site_name'] . $status;
                            }, array_slice($primary_attachments, 0, 5));
                            $message = 'Cannot delete domain — it is the primary domain for: '
                                     . implode('; ', $site_descs)
                                     . '. Either delete the site itself or change the site\'s primary domain first.';
                            $message_type = 'danger';
                            break;
                        }

                        // Additional-only attachment: safe to auto-detach
                        // because the domain is just an alias entry on the
                        // site, not the site's primary identity. Drop the
                        // site_domains rows BEFORE the domain delete so the
                        // FK doesn't bite. Audit-log so the operator can
                        // trace what was detached if they expected the alias
                        // to stick around.
                        if (!empty($additional_attachments)) {
                            $stmt = $db->prepare("DELETE FROM whp.site_domains WHERE domain_id = ?");
                            $stmt->execute([$domain_id]);
                            $detached = (int) $stmt->rowCount();
                            $site_ids = implode(',', array_column($additional_attachments, 'id'));
                            error_log("domains: detached domain_id=$domain_id from $detached additional-domain attachment(s) [sites=$site_ids] before delete (actor=" . AUTH_USER . ")");
                        }

                        // Also sweep any truly-orphaned site_domains rows
                        // referencing this domain_id (parent site missing).
                        // FK cascade should make this a no-op but historical
                        // drift on long-running installs could leave straggler
                        // rows. Removing here means the domain delete below
                        // succeeds cleanly.
                        $stmt = $db->prepare("
                            DELETE FROM whp.site_domains
                            WHERE domain_id = ?
                              AND site_id NOT IN (SELECT id FROM whp.sites)
                        ");
                        $stmt->execute([$domain_id]);
                        $cleaned = (int) $stmt->rowCount();
                        if ($cleaned > 0) {
                            error_log("domains: cleaned $cleaned orphan site_domains row(s) for domain_id=$domain_id before delete (actor=" . AUTH_USER . ")");
                        }
                        
                        // Delete PowerDNS zone first
                        $zone_result = $pdns->deleteZoneForDomain($domain['domain_name'], $domain['username']);
                        if (!$zone_result['success']) {
                            $message = 'Warning: Failed to delete DNS zone: ' . $zone_result['error'];
                            $message_type = 'warning';
                        }
                        
                        // Delete domain from mail server
                        $mail_sync_success = true;
                        $mail_sync_message = '';
                        if ($EmailMgmt) {
                            try {
                                $mail_result = $EmailMgmt->deleteMailServerDomain($domain['domain_name']);
                                if ($mail_result['status'] !== '0') {
                                    $mail_sync_success = false;
                                    $mail_sync_message = $mail_result['msg'];
                                }
                            } catch (Exception $e) {
                                $mail_sync_success = false;
                                $mail_sync_message = $e->getMessage();
                            }
                        }
                        
                        // Clean up email database entries for this domain
                        $email_cleanup_errors = [];
                        if ($EmailMgmt) {
                            $cleanup_result = $EmailMgmt->cleanupDomainEmailEntries($domain['domain_name']);
                            if ($cleanup_result['status'] !== '0') {
                                $email_cleanup_errors[] = $cleanup_result['msg'];
                            }
                        } else {
                            $email_cleanup_errors[] = "Email management system not available for cleanup";
                        }
                        
                        // Delete domain from WHP database
                        $stmt = $db->prepare("DELETE FROM whp.domains WHERE id = ?");
                        $stmt->execute([$domain_id]);
                        
                        if ($mail_sync_success && empty($email_cleanup_errors)) {
                            $message = 'Domain deleted successfully: ' . $domain['domain_name'] . ' (removed from mail server and email database entries cleaned up)';
                            $message_type = 'success';
                        } else {
                            $warnings = [];
                            if (!$mail_sync_success) {
                                $warnings[] = 'Mail server removal failed: ' . $mail_sync_message;
                            }
                            if (!empty($email_cleanup_errors)) {
                                $warnings[] = implode(', ', $email_cleanup_errors);
                            }
                            
                            $message = 'Domain deleted successfully: ' . $domain['domain_name'] . '. Warning: ' . implode('. ', $warnings);
                            $message_type = 'warning';
                        }
                    } catch (PDOException $e) {
                        $message = 'Error deleting domain: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'move_domain':
                if (!empty($_POST['domain_id']) && !empty($_POST['new_owner']) && $is_root) {
                    try {
                        $domain_id = intval($_POST['domain_id']);
                        $new_owner = trim($_POST['new_owner']);
                        
                        // Get domain info
                        $stmt = $db->prepare("SELECT domain_name, username FROM whp.domains WHERE id = ?");
                        $stmt->execute([$domain_id]);
                        $domain = $stmt->fetch();
                        
                        if (!$domain) {
                            $message = 'Domain not found';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check if new owner exists
                        $stmt = $db->prepare("SELECT username FROM whp.client_allowances WHERE username = ?");
                        $stmt->execute([$new_owner]);
                        $new_user = $stmt->fetch();
                        
                        if (!$new_user) {
                            $message = 'Invalid new owner specified';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check if domain is used by any active sites
                        $stmt = $db->prepare("SELECT COUNT(*) as count FROM whp.site_domains WHERE domain_id = ?");
                        $stmt->execute([$domain_id]);
                        $site_usage = $stmt->fetch()['count'];
                        
                        if ($site_usage > 0) {
                            $message = 'Cannot move domain that is used by active sites. Remove from sites first.';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Update domain owner
                        $stmt = $db->prepare("UPDATE whp.domains SET username = ? WHERE id = ?");
                        $stmt->execute([$new_owner, $domain_id]);
                        
                        $message = 'Domain moved successfully: ' . $domain['domain_name'] . ' → ' . $new_owner;
                        $message_type = 'success';
                    } catch (PDOException $e) {
                        $message = 'Error moving domain: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'add_dns_record':
                if (!empty($_POST['domain_name']) && !empty($_POST['record_name']) && !empty($_POST['record_type']) && !empty($_POST['record_content']) && $pdns) {
                    try {
                        $domain_name = trim($_POST['domain_name']);
                        $record_name = trim($_POST['record_name']);
                        $record_type = strtoupper(trim($_POST['record_type']));
                        $record_content = trim($_POST['record_content']);
                        $ttl = intval($_POST['ttl'] ?? 3600);
                        $priority = !empty($_POST['priority']) ? intval($_POST['priority']) : null;
                        
                        // Validate record type
                        $valid_types = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'PTR', 'SRV', 'CAA', 'SSHFP', 'TLSA', 'DS', 'DNSKEY', 'RRSIG', 'NSEC', 'NSEC3'];
                        if (!in_array($record_type, $valid_types)) {
                            $message = 'Invalid record type';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Auto-quote TXT records if not already quoted
                        if ($record_type === 'TXT') {
                            // Check if the content is not already quoted
                            if (!preg_match('/^".*"$/', $record_content)) {
                                // Add quotes around the content
                                $record_content = '"' . $record_content . '"';
                            }
                        }
                        
                        // Check domain ownership
                        $stmt = $db->prepare("SELECT username FROM whp.domains WHERE domain_name = ?");
                        $stmt->execute([$domain_name]);
                        $domain_owner = $stmt->fetch();
                        
                        if (!$domain_owner) {
                            $message = 'Domain not found';
                            $message_type = 'danger';
                            break;
                        }
                        
                        if (!$is_root && $domain_owner['username'] !== AUTH_USER) {
                            $message = 'You can only manage DNS records for your own domains';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Handle NS records specially to prevent overwriting
                        if ($record_type === 'NS') {
                            // Get existing NS records of the same name
                            $existing_records = $pdns->getRecords($domain_name);
                            $existing_ns_records = [];
                            
                            foreach ($existing_records as $existing) {
                                if ($existing['name'] === $record_name && $existing['type'] === 'NS') {
                                    $existing_ns_records[] = $existing['content'];
                                }
                            }
                            
                            // Add the new NS record to the existing ones
                            $existing_ns_records[] = $record_content;
                            
                            // Use addMultipleRecords to set all NS records at once
                            $result = $pdns->addMultipleRecords($domain_name, $record_name, $record_type, $ttl, $existing_ns_records);
                        } else {
                            // Add DNS record normally for other types
                            $result = $pdns->addRecord($domain_name, $record_name, $record_type, $record_content, $ttl, $priority);
                        }
                        
                        if ($result) {
                            $message = 'DNS record added successfully';
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to add DNS record';
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error adding DNS record: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'delete_dns_record':
                if (!empty($_POST['domain_name']) && !empty($_POST['record_name']) && !empty($_POST['record_type']) && $pdns) {
                    try {
                        $domain_name = trim($_POST['domain_name']);
                        $record_name = trim($_POST['record_name']);
                        $record_type = strtoupper(trim($_POST['record_type']));
                        
                        // Check domain ownership
                        $stmt = $db->prepare("SELECT username FROM whp.domains WHERE domain_name = ?");
                        $stmt->execute([$domain_name]);
                        $domain_owner = $stmt->fetch();
                        
                        if (!$domain_owner) {
                            $message = 'Domain not found';
                            $message_type = 'danger';
                            break;
                        }
                        
                        if (!$is_root && $domain_owner['username'] !== AUTH_USER) {
                            $message = 'You can only manage DNS records for your own domains';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Delete DNS record
                        $result = $pdns->deleteRecord($domain_name, $record_name, $record_type);
                        
                        if ($result) {
                            $message = 'DNS record deleted successfully';
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to delete DNS record';
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error deleting DNS record: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'edit_dns_record':
                if (!empty($_POST['domain_name']) && !empty($_POST['record_name']) && !empty($_POST['record_type']) && !empty($_POST['record_content']) && $pdns) {
                    try {
                        $domain_name = trim($_POST['domain_name']);
                        $record_name = trim($_POST['record_name']);
                        $record_type = strtoupper(trim($_POST['record_type']));
                        $record_content = trim($_POST['record_content']);
                        $ttl = intval($_POST['ttl'] ?? 3600);
                        $priority = !empty($_POST['priority']) ? intval($_POST['priority']) : null;
                        
                        // Validate record type
                        $valid_types = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'PTR', 'SRV', 'CAA', 'SSHFP', 'TLSA', 'DS', 'DNSKEY', 'RRSIG', 'NSEC', 'NSEC3'];
                        if (!in_array($record_type, $valid_types)) {
                            $message = 'Invalid record type';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Auto-quote TXT records if not already quoted
                        if ($record_type === 'TXT') {
                            // Check if the content is not already quoted
                            if (!preg_match('/^".*"$/', $record_content)) {
                                // Add quotes around the content
                                $record_content = '"' . $record_content . '"';
                            }
                        }
                        
                        // Check domain ownership
                        $stmt = $db->prepare("SELECT username FROM whp.domains WHERE domain_name = ?");
                        $stmt->execute([$domain_name]);
                        $domain_owner = $stmt->fetch();
                        
                        if (!$domain_owner) {
                            $message = 'Domain not found';
                            $message_type = 'danger';
                            break;
                        }
                        
                        if (!$is_root && $domain_owner['username'] !== AUTH_USER) {
                            $message = 'You can only manage DNS records for your own domains';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // For MX, SRV, and NS records, we need to handle multiple records properly
                        if (in_array($record_type, ['MX', 'SRV', 'NS'])) {
                            // Get existing records of this type to preserve others
                            $existing_records = $pdns->getRecords($domain_name);
                            $other_records = [];
                            $found_target = false;
                            
                            if ($record_type === 'NS') {
                                // For NS records, we can't edit individual records easily
                                // Direct users to use the multiple records interface for NS editing
                                $message = 'NS records must be edited using the multiple records interface. Please use "Add Multiple NS" to manage nameserver records.';
                                $message_type = 'warning';
                                break;
                            } else {
                                // For MX and SRV records with priorities
                                foreach ($existing_records as $existing) {
                                    if ($existing['name'] === $record_name && $existing['type'] === $record_type) {
                                        // Check if this is the record we're editing
                                        $existing_parts = explode(' ', $existing['content'], 2);
                                        if (count($existing_parts) === 2 && is_numeric($existing_parts[0])) {
                                            $existing_priority = intval($existing_parts[0]);
                                            if ($existing_priority === $priority) {
                                                // This is the record we're editing, skip it
                                                $found_target = true;
                                                continue;
                                            }
                                        }
                                        // Keep other records of the same type
                                        $other_records[] = $existing['content'];
                                    }
                                }
                                // Add the updated record to the list
                                $updated_content = $priority . ' ' . $record_content;
                                $other_records[] = $updated_content;
                            }
                            
                                                    // Update all records of this type
                        $result = $pdns->addMultipleRecords($domain_name, $record_name, $record_type, $ttl, $other_records);
                        } else {
                            // For non-MX/SRV records, use simple update
                            $result = $pdns->addRecord($domain_name, $record_name, $record_type, $record_content, $ttl, $priority);
                        }
                        
                        if ($result) {
                            $message = 'DNS record updated successfully';
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to update DNS record';
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error updating DNS record: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'add_multiple_records':
                if (!empty($_POST['domain_name']) && !empty($_POST['record_name']) && !empty($_POST['record_type']) && !empty($_POST['contents']) && $pdns) {
                    try {
                        $domain_name = trim($_POST['domain_name']);
                        $record_name = trim($_POST['record_name']);
                        $record_type = strtoupper(trim($_POST['record_type']));
                        $ttl = intval($_POST['ttl'] ?? 3600);
                        $priorities = $_POST['priorities'] ?? [];
                        $contents = $_POST['contents'];
                        
                        // Validate record type
                        if (!in_array($record_type, ['MX', 'SRV', 'NS'])) {
                            $message = 'Invalid record type for multiple records';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check domain ownership
                        $stmt = $db->prepare("SELECT username FROM whp.domains WHERE domain_name = ?");
                        $stmt->execute([$domain_name]);
                        $domain_owner = $stmt->fetch();
                        
                        if (!$domain_owner) {
                            $message = 'Domain not found';
                            $message_type = 'danger';
                            break;
                        }
                        
                        if (!$is_root && $domain_owner['username'] !== AUTH_USER) {
                            $message = 'You can only manage DNS records for your own domains';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Prepare record contents 
                        $record_contents = [];
                        if ($record_type === 'NS') {
                            // For NS records, no priorities needed
                            for ($i = 0; $i < count($contents); $i++) {
                                if (!empty($contents[$i])) {
                                    $content = trim($contents[$i]);
                                    $record_contents[] = $content;
                                }
                            }
                        } else {
                            // For MX/SRV records, include priorities
                            for ($i = 0; $i < count($priorities); $i++) {
                                if (!empty($priorities[$i]) && !empty($contents[$i])) {
                                    $priority = intval($priorities[$i]);
                                    $content = trim($contents[$i]);
                                    $record_contents[] = $priority . ' ' . $content;
                                }
                            }
                        }
                        
                        if (empty($record_contents)) {
                            $message = 'No valid records provided';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Add multiple records
                        $result = $pdns->addMultipleRecords($domain_name, $record_name, $record_type, $ttl, $record_contents);
                        
                        if ($result) {
                            $message = 'Multiple ' . $record_type . ' records added successfully';
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to add multiple records';
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error adding multiple records: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'edit_multiple_records':
                if (!empty($_POST['domain_name']) && !empty($_POST['record_name']) && !empty($_POST['record_type']) && !empty($_POST['contents']) && $pdns) {
                    try {
                        $domain_name = trim($_POST['domain_name']);
                        $record_name = trim($_POST['record_name']);
                        $record_type = strtoupper(trim($_POST['record_type']));
                        $ttl = intval($_POST['ttl'] ?? 3600);
                        $priorities = $_POST['priorities'] ?? [];
                        $contents = $_POST['contents'];
                        
                        // Validate record type
                        if (!in_array($record_type, ['MX', 'SRV', 'NS'])) {
                            $message = 'Invalid record type for multiple records';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Check domain ownership
                        $stmt = $db->prepare("SELECT username FROM whp.domains WHERE domain_name = ?");
                        $stmt->execute([$domain_name]);
                        $domain_owner = $stmt->fetch();
                        
                        if (!$domain_owner) {
                            $message = 'Domain not found';
                            $message_type = 'danger';
                            break;
                        }
                        
                        if (!$is_root && $domain_owner['username'] !== AUTH_USER) {
                            $message = 'You can only manage DNS records for your own domains';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Prepare record contents 
                        $record_contents = [];
                        if ($record_type === 'NS') {
                            // For NS records, no priorities needed
                            for ($i = 0; $i < count($contents); $i++) {
                                if (!empty($contents[$i])) {
                                    $content = trim($contents[$i]);
                                    $record_contents[] = $content;
                                }
                            }
                        } else {
                            // For MX/SRV records, include priorities
                            for ($i = 0; $i < count($priorities); $i++) {
                                if (!empty($priorities[$i]) && !empty($contents[$i])) {
                                    $priority = intval($priorities[$i]);
                                    $content = trim($contents[$i]);
                                    $record_contents[] = $priority . ' ' . $content;
                                }
                            }
                        }
                        
                        if (empty($record_contents)) {
                            $message = 'No valid records provided';
                            $message_type = 'danger';
                            break;
                        }
                        
                        // Update multiple records (this replaces all records of this type)
                        $result = $pdns->addMultipleRecords($domain_name, $record_name, $record_type, $ttl, $record_contents);
                        
                        if ($result) {
                            $message = 'Multiple ' . $record_type . ' records updated successfully';
                            $message_type = 'success';
                        } else {
                            $message = 'Failed to update multiple records';
                            $message_type = 'danger';
                        }
                    } catch (Exception $e) {
                        $message = 'Error updating multiple records: ' . $e->getMessage();
                        $message_type = 'danger';
                    }
                }
                break;
        }
    }
}

// Get user's domains
global $db;
try {
    if ($is_root) {
        // Root sees all domains
        $stmt = $db->query("
            SELECT 
                d.id,
                d.domain_name,
                d.active,
                d.created_at,
                d.username as owner,
                ct.name as container_type,
                c.status as container_status,
                c.container_id
            FROM whp.domains d
            LEFT JOIN whp.container_types ct ON d.container_type_id = ct.id
            LEFT JOIN whp.containers c ON d.id = c.domain_id
            ORDER BY d.domain_name ASC
        ");
    } else {
        // Regular users see only their domains
        $stmt = $db->prepare("
            SELECT 
                d.id,
                d.domain_name,
                d.active,
                d.created_at,
                d.username as owner,
                ct.name as container_type,
                c.status as container_status,
                c.container_id
            FROM whp.domains d
            LEFT JOIN whp.container_types ct ON d.container_type_id = ct.id
            LEFT JOIN whp.containers c ON d.id = c.domain_id
            WHERE d.username = ?
            ORDER BY d.domain_name ASC
        ");
        $stmt->execute([AUTH_USER]);
    }
    $domains = $stmt->fetchAll();
} catch (PDOException $e) {
    $domains = [];
    $message = 'Error loading domains: ' . $e->getMessage();
    $message_type = 'danger';
}

// Get available users for root
$available_users = [];
if ($is_root) {
    try {
        $stmt = $db->query("SELECT username FROM whp.client_allowances ORDER BY username ASC");
        $available_users = $stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch (PDOException $e) {
        $available_users = [];
    }
}

// Get DNS records for selected domain (if any)
$selected_domain = $_GET['domain'] ?? '';
$dns_records = [];
if ($selected_domain && $pdns) {
    try {
        $dns_records = $pdns->getRecords($selected_domain) ?: [];
    } catch (Exception $e) {
        $message = 'Error loading DNS records: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// PowerDNS supported record types
$record_types = [
    'A' => 'A (IPv4 Address)',
    'AAAA' => 'AAAA (IPv6 Address)',
    'CNAME' => 'CNAME (Canonical Name)',
    'MX' => 'MX (Mail Exchange)',
    'TXT' => 'TXT (Text)',
    'NS' => 'NS (Name Server)',
    'PTR' => 'PTR (Pointer)',
    'SRV' => 'SRV (Service)',
    'CAA' => 'CAA (Certification Authority Authorization)',
    'SSHFP' => 'SSHFP (SSH Fingerprint)',
    'TLSA' => 'TLSA (TLS Authentication)',
    'DS' => 'DS (Delegation Signer)',
    'DNSKEY' => 'DNSKEY (DNS Key)',
    'RRSIG' => 'RRSIG (Resource Record Signature)',
    'NSEC' => 'NSEC (Next Secure)',
    'NSEC3' => 'NSEC3 (Next Secure v3)'
];
?>

<div class="row">
    <div class="col-md-12">
        <?php if (!empty($message)): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            <i class="fa fa-<?php echo $message_type === 'success' ? 'check' : 'exclamation-triangle'; ?>"></i>
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="row">
    <div class="col-md-3">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    Your Domains
                    <?php if ($is_root): ?>
                    <small class="text-muted">(All domains)</small>
                    <?php endif; ?>
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($domains)): ?>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>No domains found</strong> - Add your first domain using the form below.
                </div>
                <?php else: ?>
                <div class="mb-3">
                    <label for="domain_select" class="form-label">Select Domain</label>
                    <select class="form-select" id="domain_select" onchange="window.location.href='?page=domains&domain=' + encodeURIComponent(this.value)">
                        <option value="">Choose a domain...</option>
                        <?php foreach ($domains as $domain): ?>
                        <option value="<?php echo htmlspecialchars($domain['domain_name']); ?>" 
                                <?php echo $selected_domain === $domain['domain_name'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($domain['domain_name']); ?>
                            <?php if ($is_root): ?>
                                (<?php echo htmlspecialchars($domain['owner']); ?>)
                            <?php endif; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Domain Management Actions -->
                <?php if ($selected_domain): ?>
                <div class="mb-3">
                    <h6>Domain Actions</h6>
                    <?php 
                    $current_domain = null;
                    foreach ($domains as $domain) {
                        if ($domain['domain_name'] === $selected_domain) {
                            $current_domain = $domain;
                            break;
                        }
                    }
                    ?>
                    <?php if ($current_domain): ?>
                    <div class="d-grid gap-2">
                        <!-- Delete Domain Button -->
                        <?php if ($is_root || $current_domain['owner'] === AUTH_USER): ?>
                        <form method="post" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this domain? This action cannot be undone.');">
                            <input type="hidden" name="action" value="delete_domain">
                            <input type="hidden" name="domain_id" value="<?php echo $current_domain['id']; ?>">
                            <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                            <button type="submit" class="btn btn-danger btn-sm">
                                <i class="fa fa-trash"></i> Delete Domain
                            </button>
                        </form>
                        <?php endif; ?>
                        
                        <!-- Move Domain Button (Root Only) -->
                        <?php if ($is_root): ?>
                        <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#moveDomainModal">
                            <i class="fa fa-exchange"></i> Move Domain
                        </button>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php endif; ?>
                
                <hr>
                
                <!-- Add Domain Form -->
                <h6>Add New Domain</h6>
                <form method="post">
                    <input type="hidden" name="action" value="add_domain">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="mb-3">
                        <label for="domain_name" class="form-label">Domain Name</label>
                        <input type="text" class="form-control" id="domain_name" name="domain_name" 
                               placeholder="example.com" required>
                    </div>
                    
                    <?php if ($is_root): ?>
                    <div class="mb-3">
                        <label for="owner_username" class="form-label">Owner</label>
                        <select class="form-select" id="owner_username" name="owner_username" required>
                            <option value="">Select user...</option>
                            <?php foreach ($available_users as $username): ?>
                            <option value="<?php echo htmlspecialchars($username); ?>">
                                <?php echo htmlspecialchars($username); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    
                    <button type="submit" class="btn btn-primary btn-sm">
                        <i class="fa fa-plus"></i> Add Domain
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-9">
        <?php if ($selected_domain): ?>
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    DNS Records for <?php echo htmlspecialchars($selected_domain); ?>
                    <div class="float-end">
                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addRecordModal">
                            <i class="fa fa-plus"></i> Add Record
                        </button>
                        <a href="?page=domains" class="btn btn-secondary btn-sm">
                            <i class="fa fa-times"></i> Close
                        </a>
                    </div>
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($dns_records)): ?>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>No DNS records found</strong> - Add your first DNS record using the button above.
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th style="width: 80px;">Type</th>
                                <th style="width: 200px;">Name</th>
                                <th style="width: 350px;">Content</th>
                                <th style="width: 80px;">TTL</th>
                                <th style="width: 120px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($dns_records as $record): ?>
                            <?php
                            // Parse priority for MX and SRV records
                            $priority = null;
                            $content_display = $record['content'];
                            if (in_array($record['type'], ['MX', 'SRV'])) {
                                $parts = explode(' ', $record['content'], 2);
                                if (count($parts) === 2 && is_numeric($parts[0])) {
                                    $priority = intval($parts[0]);
                                    $content_display = $parts[1];
                                }
                            }
                            ?>
                            <tr>
                                <td>
                                    <span class="badge bg-primary"><?php echo htmlspecialchars($record['type']); ?></span>
                                    <?php if ($priority !== null): ?>
                                        <br><small class="text-muted">Priority: <?php echo $priority; ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="word-wrap: break-word; word-break: break-all;">
                                        <?php echo htmlspecialchars($record['name']); ?>
                                    </div>
                                </td>
                                <td>
                                    <div style="max-width: 350px; word-wrap: break-word; word-break: break-all; font-family: monospace; font-size: 0.9em;">
                                        <code><?php echo htmlspecialchars($content_display); ?></code>
                                        <?php if ($record['disabled']): ?>
                                            <span class="badge bg-secondary">Disabled</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td><?php echo $record['ttl']; ?></td>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button type="button" class="btn btn-primary btn-sm" 
                                                onclick="editRecord('<?php echo htmlspecialchars($selected_domain); ?>', '<?php echo htmlspecialchars($record['name']); ?>', '<?php echo htmlspecialchars($record['type']); ?>', '<?php echo htmlspecialchars(addslashes($content_display)); ?>', <?php echo $record['ttl']; ?>, <?php echo $priority !== null ? $priority : 'null'; ?>)">
                                            <i class="fa fa-edit"></i>
                                        </button>
                                        <form method="post" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this DNS record?');">
                                            <input type="hidden" name="action" value="delete_dns_record">
                                            <input type="hidden" name="domain_name" value="<?php echo htmlspecialchars($selected_domain); ?>">
                                            <input type="hidden" name="record_name" value="<?php echo htmlspecialchars($record['name']); ?>">
                                            <input type="hidden" name="record_type" value="<?php echo htmlspecialchars($record['type']); ?>">
                                            <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                            <button type="submit" class="btn btn-danger btn-sm">
                                                <i class="fa fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">DNS Management</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>Select a domain</strong> from the dropdown on the left to manage its DNS records.
                </div>
                
                <h6>Default DNS Records</h6>
                <p>When you add a new domain, the following DNS records are automatically created:</p>
                <ul>
                    <li><strong>A Record</strong> for the apex domain pointing to the server's IP</li>
                    <li><strong>CNAME Record</strong> for www pointing to the apex domain</li>
                    <li><strong>NS Records</strong> using the configured nameservers</li>
                    <li><strong>MX Record</strong> pointing to the mail server</li>
                    <li><strong>TXT Record</strong> for SPF protection</li>
                </ul>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Move Domain Modal -->
<div class="modal fade" id="moveDomainModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Move Domain</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="move_domain">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="domain_id" value="<?php 
                        $current_domain = null;
                        foreach ($domains as $domain) {
                            if ($domain['domain_name'] === $selected_domain) {
                                $current_domain = $domain;
                                break;
                            }
                        }
                        echo $current_domain ? $current_domain['id'] : '';
                    ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">Domain</label>
                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($selected_domain); ?>" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label for="new_owner" class="form-label">New Owner</label>
                        <select class="form-select" id="new_owner" name="new_owner" required>
                            <option value="">Select new owner...</option>
                            <?php foreach ($available_users as $username): ?>
                            <option value="<?php echo htmlspecialchars($username); ?>">
                                <?php echo htmlspecialchars($username); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Warning:</strong> Moving a domain will transfer ownership to the new user. This action cannot be undone.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Move Domain</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add DNS Record Modal -->
<div class="modal fade" id="addRecordModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add DNS Record</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_dns_record">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="domain_name" value="<?php echo htmlspecialchars($selected_domain); ?>">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="record_type" class="form-label">Record Type</label>
                                <select class="form-select" id="record_type" name="record_type" required>
                                    <option value="">Select record type...</option>
                                    <?php foreach ($record_types as $type => $description): ?>
                                    <option value="<?php echo $type; ?>"><?php echo $description; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="ttl" class="form-label">TTL (seconds)</label>
                                <input type="number" class="form-control" id="ttl" name="ttl" value="<?php echo max(300, intval($server_settings['default_ttl'] ?? 3600)); ?>" min="300" max="86400">
                                <div class="form-text text-light">Time to live in seconds (300-86400)</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="record_name" class="form-label">Name</label>
                                <input type="text" class="form-control" id="record_name" name="record_name" 
                                       placeholder="@ for apex domain, or subdomain name" required>
                                <div class="form-text text-light">Use @ for the apex domain, or enter a subdomain name</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3" id="priority_field" style="display: none;">
                                <label for="priority" class="form-label">Priority</label>
                                <input type="number" class="form-control" id="priority" name="priority" min="0" max="65535">
                                <div class="form-text text-light">Required for MX and SRV records</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="record_content" class="form-label">Content</label>
                        <textarea class="form-control" id="record_content" name="record_content" rows="3" 
                                  placeholder="Enter record content..." required></textarea>
                        <div class="form-text text-light">
                            <strong>Examples:</strong><br>
                            A: 192.168.1.100<br>
                            AAAA: 2001:db8::1<br>
                            CNAME: example.com.<br>
                            MX: mail.example.com. (with priority)<br>
                            TXT: "v=spf1 a mx ~all"
                        </div>
                    </div>
                    

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Record</button>
                    <?php if (in_array('MX', array_keys($record_types))): ?>
                    <button type="button" class="btn btn-info" onclick="showMultipleRecordsModal()">
                        <i class="fa fa-plus"></i> Add Multiple MX/SRV/NS
                    </button>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit DNS Record Modal -->
<div class="modal fade" id="editRecordModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit DNS Record</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit_dns_record">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="domain_name" id="edit_domain_name">
                    <input type="hidden" name="record_name" id="edit_record_name">
                    <input type="hidden" name="record_type" id="edit_record_type">
                    <input type="hidden" name="original_content" id="edit_original_content">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_record_type_display" class="form-label">Record Type</label>
                                <input type="text" class="form-control" id="edit_record_type_display" readonly style="background-color: #f8f9fa; color: #495057;">
                                <div class="form-text text-light">Record type cannot be changed</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_ttl" class="form-label">TTL (seconds)</label>
                                <input type="number" class="form-control" id="edit_ttl" name="ttl" min="300" max="86400">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="edit_record_name_display" class="form-label">Name</label>
                                <input type="text" class="form-control" id="edit_record_name_display" readonly style="background-color: #f8f9fa; color: #495057;">
                                <div class="form-text text-light">Record name cannot be changed</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3" id="edit_priority_field" style="display: none;">
                                <label for="edit_priority" class="form-label">Priority</label>
                                <input type="number" class="form-control" id="edit_priority" name="priority" min="0" max="65535">
                                <div class="form-text text-light">Required for MX and SRV records</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_record_content" class="form-label">Content</label>
                        <textarea class="form-control" id="edit_record_content" name="record_content" rows="4" 
                                  placeholder="Enter record content..." required></textarea>
                        <div class="form-text text-light">
                            <strong>Examples:</strong><br>
                            A: 192.168.1.100<br>
                            AAAA: 2001:db8::1<br>
                            CNAME: example.com.<br>
                            MX: mail.example.com. (with priority)<br>
                            TXT: "v=spf1 a mx ~all"
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Record</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Multiple MX/SRV Records Modal -->
<div class="modal fade" id="multipleRecordsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Multiple MX/SRV Records</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_multiple_records">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="domain_name" value="<?php echo htmlspecialchars($selected_domain); ?>">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="multiple_record_type" class="form-label">Record Type</label>
                                <select class="form-select" id="multiple_record_type" name="record_type" required>
                                    <option value="MX">MX (Mail Exchange)</option>
                                    <option value="SRV">SRV (Service)</option>
                                    <option value="NS">NS (Name Server)</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="multiple_ttl" class="form-label">TTL (seconds)</label>
                                <input type="number" class="form-control" id="multiple_ttl" name="ttl" value="<?php echo max(300, intval($server_settings['default_ttl'] ?? 3600)); ?>" min="300" max="86400">
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="multiple_record_name" class="form-label">Name</label>
                        <input type="text" class="form-control" id="multiple_record_name" name="record_name" 
                               placeholder="@ for apex domain, or subdomain name" required>
                        <div class="form-text text-light">Use @ for the apex domain, or enter a subdomain name</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Records</label>
                        <div id="multiple_records_container">
                            <div class="row mb-2 record-row">
                                <div class="col-md-3">
                                    <input type="number" class="form-control" name="priorities[]" placeholder="Priority" min="0" max="65535" required>
                                </div>
                                <div class="col-md-7">
                                    <input type="text" class="form-control" name="contents[]" placeholder="Server address" required>
                                </div>
                                <div class="col-md-2">
                                    <button type="button" class="btn btn-danger btn-sm" onclick="removeRecordRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-secondary btn-sm" onclick="addRecordRow()">
                            <i class="fa fa-plus"></i> Add Another Record
                        </button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Records</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Show/hide priority field based on record type
document.getElementById('record_type').addEventListener('change', function() {
    const priorityField = document.getElementById('priority_field');
    const recordType = this.value;
    
    if (recordType === 'MX' || recordType === 'SRV' || recordType === 'NS') {
        // Automatically switch to multiple records modal for MX/SRV/NS
        showMultipleRecordsModal();
        return;
    } else {
        priorityField.style.display = 'none';
        document.getElementById('priority').required = false;
    }
});

// Auto-fill record name examples
document.getElementById('record_type').addEventListener('change', function() {
    const recordName = document.getElementById('record_name');
    const recordContent = document.getElementById('record_content');
    const recordType = this.value;
    
    switch(recordType) {
        case 'A':
            if (!recordName.value) recordName.value = '@';
            if (!recordContent.value) recordContent.value = '192.168.1.100';
            break;
        case 'AAAA':
            if (!recordName.value) recordName.value = '@';
            if (!recordContent.value) recordContent.value = '2001:db8::1';
            break;
        case 'CNAME':
            if (!recordName.value) recordName.value = 'www';
            if (!recordContent.value) recordContent.value = '<?php echo htmlspecialchars($selected_domain); ?>.';
            break;
        case 'MX':
            if (!recordName.value) recordName.value = '@';
            if (!recordContent.value) recordContent.value = 'mail.<?php echo htmlspecialchars($selected_domain); ?>.';
            break;
        case 'TXT':
            if (!recordName.value) recordName.value = '@';
            if (!recordContent.value) recordContent.value = '"v=spf1 a mx ~all"';
            break;
        case 'NS':
            if (!recordName.value) recordName.value = '@';
            if (!recordContent.value) recordContent.value = 'ns1.<?php echo htmlspecialchars($selected_domain); ?>.';
            break;
    }
});

// Edit DNS record function
function editRecord(domainName, recordName, recordType, recordContent, ttl, priority) {
    // For MX, SRV, and NS records, use the multiple records approach
    if (recordType === 'MX' || recordType === 'SRV' || recordType === 'NS') {
        editMultipleRecords(domainName, recordName, recordType, recordContent, ttl, priority);
        return;
    }
    
    // Set form values for regular records
    document.getElementById('edit_domain_name').value = domainName;
    document.getElementById('edit_record_name').value = recordName;
    document.getElementById('edit_record_type').value = recordType;
    document.getElementById('edit_record_name_display').value = recordName;
    document.getElementById('edit_record_type_display').value = recordType;
    document.getElementById('edit_record_content').value = recordContent;
    document.getElementById('edit_ttl').value = ttl;
    document.getElementById('edit_original_content').value = recordContent;
    
    // Handle priority field visibility
    const editPriorityField = document.getElementById('edit_priority_field');
    const editPriority = document.getElementById('edit_priority');
    
    if (recordType === 'MX' || recordType === 'SRV') {
        editPriorityField.style.display = 'block';
        editPriority.required = true;
        editPriority.value = priority || '';
    } else {
        editPriorityField.style.display = 'none';
        editPriority.required = false;
        editPriority.value = '';
    }
    
    // Show modal
    const editModal = new bootstrap.Modal(document.getElementById('editRecordModal'));
    editModal.show();
}

// Edit multiple records function
function editMultipleRecords(domainName, recordName, recordType, recordContent, ttl, priority) {
    // Set form values for multiple records modal
    document.getElementById('multiple_record_type').value = recordType;
    document.getElementById('multiple_ttl').value = ttl;
    document.getElementById('multiple_record_name').value = recordName;
    
    // Clear existing rows
    const container = document.getElementById('multiple_records_container');
    container.innerHTML = '';
    
    if (recordType === 'NS') {
        // For NS records, we need to load ALL existing NS records for this name, not just the clicked one
        // We'll make an AJAX call to get all NS records, but for now just show the clicked one
        // TODO: This could be improved by making an AJAX call to get all existing NS records
        const newRow = document.createElement('div');
        newRow.className = 'row mb-2 record-row';
        newRow.innerHTML = `
            <div class="col-md-10">
                <input type="text" class="form-control" name="contents[]" placeholder="Name server (e.g., ns1.example.com)" value="${recordContent}" required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRecordRow(this)">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        `;
        container.appendChild(newRow);
    } else {
        // For MX and SRV records, show the single record being edited
        const newRow = document.createElement('div');
        newRow.className = 'row mb-2 record-row';
        newRow.innerHTML = `
            <div class="col-md-3">
                <input type="number" class="form-control" name="priorities[]" placeholder="Priority" min="0" max="65535" value="${priority || ''}" required>
            </div>
            <div class="col-md-7">
                <input type="text" class="form-control" name="contents[]" placeholder="Server address" value="${recordContent}" required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRecordRow(this)">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        `;
        container.appendChild(newRow);
    }
    
    // Change the form action to edit_multiple_records
    const form = document.querySelector('#multipleRecordsModal form');
    const actionInput = form.querySelector('input[name="action"]');
    actionInput.value = 'edit_multiple_records';
    
    // Update modal title and button
    const modalTitle = recordType === 'NS' ? 'Edit Multiple NS Records' : 'Edit Multiple MX/SRV Records';
    document.querySelector('#multipleRecordsModal .modal-title').textContent = modalTitle;
    document.querySelector('#multipleRecordsModal .btn-primary').textContent = 'Update Records';
    
    // Show modal
    const multipleModal = new bootstrap.Modal(document.getElementById('multipleRecordsModal'));
    multipleModal.show();
}

// Show multiple records modal
function showMultipleRecordsModal() {
    // Close the add record modal first
    const addModal = bootstrap.Modal.getInstance(document.getElementById('addRecordModal'));
    if (addModal) {
        addModal.hide();
    }
    
    // Reset the form for adding new records
    const form = document.querySelector('#multipleRecordsModal form');
    const actionInput = form.querySelector('input[name="action"]');
    actionInput.value = 'add_multiple_records';
    
    // Reset modal title and button
    document.querySelector('#multipleRecordsModal .modal-title').textContent = 'Add Multiple MX/SRV/NS Records';
    document.querySelector('#multipleRecordsModal .btn-primary').textContent = 'Add Records';
    
    // Pre-populate the record type if it was selected in the add modal
    const selectedType = document.getElementById('record_type').value;
    if (selectedType === 'MX' || selectedType === 'SRV' || selectedType === 'NS') {
        document.getElementById('multiple_record_type').value = selectedType;
    }
    
    // Reset the record name if it was set
    document.getElementById('multiple_record_name').value = '';
    
    // Reset TTL to default
    document.getElementById('multiple_ttl').value = '<?php echo max(300, intval($server_settings['default_ttl'] ?? 3600)); ?>';
    
    // Clear existing rows and add one empty row
    const container = document.getElementById('multiple_records_container');
    container.innerHTML = '';
    addRecordRow();
    
    // Show multiple records modal
    const multipleModal = new bootstrap.Modal(document.getElementById('multipleRecordsModal'));
    multipleModal.show();
}

// Add a new record row to the multiple records form
function addRecordRow() {
    const container = document.getElementById('multiple_records_container');
    const newRow = document.createElement('div');
    newRow.className = 'row mb-2 record-row';
    newRow.innerHTML = `
        <div class="col-md-3">
            <input type="number" class="form-control" name="priorities[]" placeholder="Priority" min="0" max="65535" required>
        </div>
        <div class="col-md-7">
            <input type="text" class="form-control" name="contents[]" placeholder="Server address" required>
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-danger btn-sm" onclick="removeRecordRow(this)">
                <i class="fa fa-trash"></i>
            </button>
        </div>
    `;
    container.appendChild(newRow);
}

// Remove a record row from the multiple records form
function removeRecordRow(button) {
    const row = button.closest('.record-row');
    const container = document.getElementById('multiple_records_container');
    
    // Don't remove the last row
    if (container.children.length > 1) {
        row.remove();
    }
}

// Handle multiple record type changes (show/hide priority fields for NS records)
document.addEventListener('DOMContentLoaded', function() {
    const multipleRecordType = document.getElementById('multiple_record_type');
    if (multipleRecordType) {
        multipleRecordType.addEventListener('change', function() {
            updateMultipleRecordFields();
        });
    }
});

// Update multiple record fields based on record type
function updateMultipleRecordFields() {
    const recordType = document.getElementById('multiple_record_type').value;
    const container = document.getElementById('multiple_records_container');
    
    // Clear existing rows
    container.innerHTML = '';
    
    // Add new row with appropriate fields
    addRecordRow();
}

// Updated addRecordRow function to handle NS records
function addRecordRow() {
    const container = document.getElementById('multiple_records_container');
    const recordType = document.getElementById('multiple_record_type').value;
    const newRow = document.createElement('div');
    newRow.className = 'row mb-2 record-row';
    
    if (recordType === 'NS') {
        // NS records don't need priority
        newRow.innerHTML = `
            <div class="col-md-10">
                <input type="text" class="form-control" name="contents[]" placeholder="Name server (e.g., ns1.example.com)" required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRecordRow(this)">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        `;
    } else {
        // MX and SRV records need priority
        newRow.innerHTML = `
            <div class="col-md-3">
                <input type="number" class="form-control" name="priorities[]" placeholder="Priority" min="0" max="65535" required>
            </div>
            <div class="col-md-7">
                <input type="text" class="form-control" name="contents[]" placeholder="Server address" required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRecordRow(this)">
                    <i class="fa fa-trash"></i>
                </button>
            </div>
        `;
    }
    
    container.appendChild(newRow);
}
</script> 