<?php
// Session Start
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'config/database.php';

// ডাটাবেস এরর যাতে স্পষ্টভাবে দেখা যায়
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// লগইন চেক
if (!isset($_SESSION['is_user_logged_in']) || $_SESSION['is_user_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: my-domains.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$domain_id = $_GET['id'];

// =========================================================
// 🚀 1. DYNAMIC API CONFIGURATION (Admin Panel থেকে)
// =========================================================
$system_settings = [];
try {
    $stmt = $db->query("SELECT * FROM system_settings WHERE id = 1");
    $system_settings = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

$api_key = $system_settings['domain_api_key'] ?? '';
$api_email = $system_settings['domain_api_email'] ?? '';
$api_endpoint = rtrim($system_settings['domain_api_url'] ?? '', '/');

// 🛠️ API Call Helper Function
function callResellerAPI($action, $method = 'GET', $params = []) {
    global $api_key, $api_email, $api_endpoint;
    
    $token = base64_encode(hash_hmac("sha256", $api_key, $api_email . ":" . gmdate("y-m-d H")));
    $headers = [
        "username: " . $api_email,
        "token: " . $token
    ];

    $curl = curl_init();
    $url = $api_endpoint . $action;

    if ($method === 'GET' && !empty($params)) {
        $url .= '?' . http_build_query($params);
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    if ($method === 'POST') {
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    }

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) return ['success' => false, 'message' => "cURL Error: $err"];
    
    $decoded = json_decode($response, true);
    if ($decoded === null) {
        return ['success' => false, 'message' => "Invalid API Response"];
    }
    return $decoded;
}
// =========================================================

// ইউজারের প্রোফাইল ডাটা আনা (Fallback এর জন্য)
$user_details = [];
try {
    $u_stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $u_stmt->execute([$user_id]);
    $user_details = $u_stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

// ইউজারের ডোমেইন চেক (Active ডোমেইন)
try {
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ? AND item_type = 'domain' AND status = 'active'");
    $stmt->execute([$domain_id, $user_id]);
    $domain = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$domain) { header("Location: my-domains.php"); exit(); }
} catch(PDOException $e) { die("Database Error!"); }

$domain_name = $domain['item_name'];
$encoded_domain = urlencode($domain_name);

// =========================================================
// 🚀 2. AJAX REQUEST: Fetch EPP Code Live
// =========================================================
if (isset($_GET['ajax_epp']) && $_GET['ajax_epp'] == '1') {
    header('Content-Type: application/json');
    $api_res = callResellerAPI("/domains/{$encoded_domain}/eppcode", 'GET', ['domain' => $domain_name]);
    echo json_encode($api_res);
    exit;
}

$success_msg = '';
$error_msg = '';

// =========================================================
// 🚀 3. FORM SUBMISSIONS (POST Requests)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // A. Update Nameservers
    if (isset($_POST['update_ns'])) {
        $params = [
            'domain' => $domain_name, // 🚀 FIX: Required by API Docs
            'ns1' => trim($_POST['ns1']),
            'ns2' => trim($_POST['ns2']),
            'ns3' => trim($_POST['ns3']),
            'ns4' => trim($_POST['ns4']),
            'ns5' => trim($_POST['ns5'])
        ];
        $api_res = callResellerAPI("/domains/{$encoded_domain}/nameservers", 'POST', $params);
        
        $is_success = isset($api_res['result']) && strtolower($api_res['result']) === 'success';
        if (!$is_success && isset($api_res['status'])) $is_success = strtolower($api_res['status']) === 'success';
        if (!$is_success && isset($api_res['success'])) $is_success = $api_res['success'] === true;

        if ($is_success) {
            $success_msg = "Nameservers updated successfully!";
        } else {
            $error_msg = "API Error: " . ($api_res['message'] ?? ($api_res['error'] ?? 'Failed to update nameservers.'));
        }
    }
    
    // B. Register Personal Nameserver
    elseif (isset($_POST['register_personal_ns'])) {
        $params = [
            'domain' => $domain_name, // 🚀 FIX: Required by API Docs
            'nameserver' => trim($_POST['ns_prefix']) . '.' . $domain_name,
            'ipaddress' => trim($_POST['ip_address'])
        ];
        $api_res = callResellerAPI("/domains/{$encoded_domain}/nameservers/register", 'POST', $params);
        
        if (isset($api_res['result']) && strtolower($api_res['result']) === 'success') {
            $success_msg = "Personal Nameserver registered successfully!";
        } else {
            $error_msg = "API Error: " . ($api_res['message'] ?? 'Failed to register personal NS.');
        }
    }

    // C. Email Forwarding
    elseif (isset($_POST['setup_email_forward'])) {
        $params = [
            'domain' => $domain_name, // 🚀 FIX: Required by API Docs
            'prefix' => [trim($_POST['email_prefix'])],
            'forwardto' => [trim($_POST['forward_to'])]
        ];
        $api_res = callResellerAPI("/domains/{$encoded_domain}/email", 'POST', $params);
        
        if (isset($api_res['result']) && strtolower($api_res['result']) === 'success') {
            $success_msg = "Email forwarder added successfully!";
        } else {
            $error_msg = "API Error: " . ($api_res['message'] ?? 'Failed to set up email forwarding.');
        }
    }

    // D. Update Contact Details
    elseif (isset($_POST['update_contact'])) {
        $contact_info = [
            "firstname" => trim($_POST['firstname']),
            "lastname" => trim($_POST['lastname']),
            "fullname" => trim($_POST['firstname']) . ' ' . trim($_POST['lastname']),
            "companyname" => trim($_POST['companyname']),
            "email" => trim($_POST['email']),
            "address1" => trim($_POST['address1']),
            "city" => trim($_POST['city']),
            "state" => trim($_POST['state']),
            "postcode" => trim($_POST['postcode']),
            "country" => trim($_POST['country']),
            "phonenumber" => trim($_POST['phonenumber'])
        ];

        $params = [
            'domain' => $domain_name, // 🚀 FIX: Required by API Docs
            'contactdetails' => [
                'Registrant' => $contact_info,
                'Technical' => $contact_info,
                'Billing' => $contact_info,
                'Admin' => $contact_info
            ]
        ];

        $api_res = callResellerAPI("/domains/{$encoded_domain}/contact", 'POST', $params);

        $is_success = isset($api_res['result']) && strtolower($api_res['result']) === 'success';
        if (!$is_success && isset($api_res['status'])) $is_success = strtolower($api_res['status']) === 'success';
        if (!$is_success && isset($api_res['success'])) $is_success = $api_res['success'] === true;

        if ($is_success) {
            $success_msg = "Contact details updated successfully!";
        } else {
            $error_msg = "API Error: " . ($api_res['message'] ?? 'Failed to update contact details.');
        }
    }
}

// =========================================================
// 🚀 4. FETCH CURRENT LIVE DATA FROM API
// =========================================================

// A. Fetch Current Nameservers (উন্নত চেকিং সহ)
$current_ns_api = callResellerAPI("/domains/{$encoded_domain}/nameservers", 'GET', ['domain' => $domain_name]);

// API যদি nameservers অবজেক্টের ভেতরে ডেটা দেয়
if (isset($current_ns_api['nameservers'])) {
    $ns_data = $current_ns_api['nameservers'];
} else {
    $ns_data = $current_ns_api; // সরাসরি ফ্ল্যাট অ্যারে দিলে
}

// যদি মেইন API ফেইল করে, তাহলে ডোমেইন ইনফো API থেকে ট্রাই করা
if (empty($ns_data['ns1'])) {
    $info_api = callResellerAPI("/domains/{$encoded_domain}/information", 'GET');
    if (isset($info_api['nameservers'])) {
        $ns_data = $info_api['nameservers'];
    } elseif (isset($info_api['domain']['nameservers'])) {
        $ns_data = $info_api['domain']['nameservers'];
    }
}

$ns1_val = $ns_data['ns1'] ?? '';
$ns2_val = $ns_data['ns2'] ?? '';
$ns3_val = $ns_data['ns3'] ?? '';
$ns4_val = $ns_data['ns4'] ?? '';
$ns5_val = $ns_data['ns5'] ?? '';

// B. Fetch Current Contact Details (উন্নত নেস্টেড চেকিং সহ)
$current_contact_api = callResellerAPI("/domains/{$encoded_domain}/contact", 'GET', ['domain' => $domain_name]);
$contact_data = [];

if (isset($current_contact_api['contactdetails']['Registrant'])) {
    $contact_data = $current_contact_api['contactdetails']['Registrant'];
} elseif (isset($current_contact_api['contactdetails']['registrant'])) {
    $contact_data = $current_contact_api['contactdetails']['registrant'];
} elseif (isset($current_contact_api['registrant'])) {
    $contact_data = $current_contact_api['registrant'];
} elseif (isset($current_contact_api['contactdetails']) && !isset($current_contact_api['contactdetails']['Registrant'])) {
    $contact_data = $current_contact_api['contactdetails'];
}

// 🚀 Fallback Logic: API যদি কোনো কারণে ডেটা না দেয়, তাহলে ইউজারের প্রোফাইল থেকে ডেমো ডেটা নেবে (ফর্ম যেন ব্ল্যাংক না থাকে)
$name_parts = explode(' ', trim($user_details['name']), 2);

$c_firstname = !empty($contact_data['firstname']) ? $contact_data['firstname'] : ($name_parts[0] ?? '');
$c_lastname = !empty($contact_data['lastname']) ? $contact_data['lastname'] : ($name_parts[1] ?? 'User');
$c_company = !empty($contact_data['companyname']) ? $contact_data['companyname'] : ($user_details['company_name'] ?? '');
$c_email = !empty($contact_data['email']) ? $contact_data['email'] : ($user_details['email'] ?? '');
$c_address = !empty($contact_data['address1']) ? $contact_data['address1'] : ($user_details['address'] ?? '');
$c_city = !empty($contact_data['city']) ? $contact_data['city'] : ($user_details['city'] ?? '');
$c_state = !empty($contact_data['state']) ? $contact_data['state'] : ($user_details['state'] ?? '');
$c_postcode = !empty($contact_data['postcode']) ? $contact_data['postcode'] : ($user_details['postcode'] ?? '');
$c_country = !empty($contact_data['country']) ? $contact_data['country'] : 'BD';
$c_phone = !empty($contact_data['phonenumber']) ? $contact_data['phonenumber'] : ($user_details['phone'] ?? '');

// Date calculations
$order_date = isset($domain['order_date']) ? $domain['order_date'] : $domain['created_at'];
$created_date = new DateTime($order_date);
$expiry_date = clone $created_date;
$expiry_date->modify('+' . $domain['period'] . ' years');

$page_title = "Manage " . htmlspecialchars($domain_name);
require_once 'includes/user_header.php';
require_once 'includes/user_sidebar.php';
?>

<style>
    body {
        background-color: #ffffff !important;
        background-image: 
            linear-gradient(rgba(37, 99, 235, 0.03) 1px, transparent 1px),
            linear-gradient(90deg, rgba(37, 99, 235, 0.03) 1px, transparent 1px) !important;
        background-size: 30px 30px !important;
        color: #1e293b !important;
    }

    .domain-header-box {
        background: linear-gradient(135deg, #1e293b, #0f172a); border-radius: 20px;
        padding: 30px; color: white; margin-bottom: 30px; box-shadow: 0 15px 30px rgba(15, 23, 42, 0.15);
        position: relative; overflow: hidden;
    }
    .domain-header-box::after {
        content: '\f0ac'; font-family: 'FontAwesome'; position: absolute;
        right: -20px; bottom: -40px; font-size: 150px; opacity: 0.05;
    }

    .manage-nav-pills {
        background: #ffffff; border-radius: 20px; padding: 15px;
        border: 1px solid rgba(15, 23, 42, 0.05); box-shadow: 0 10px 30px rgba(0, 0, 0, 0.02);
    }
    .manage-nav-pills .nav-link {
        color: #64748b; font-weight: 600; padding: 12px 20px; border-radius: 12px;
        margin-bottom: 5px; text-align: left; transition: all 0.3s;
    }
    .manage-nav-pills .nav-link i { width: 25px; }
    .manage-nav-pills .nav-link:hover { background: rgba(37, 99, 235, 0.05); color: #2563eb; }
    .manage-nav-pills .nav-link.active { background: #2563eb; color: #ffffff; box-shadow: 0 5px 15px rgba(37, 99, 235, 0.3); }

    .tab-content-box {
        background: #ffffff; border-radius: 20px; padding: 30px;
        border: 1px solid rgba(15, 23, 42, 0.05); box-shadow: 0 10px 30px rgba(0, 0, 0, 0.02); min-height: 400px;
    }

    .form-control { border-radius: 12px; padding: 12px 18px; border: 1px solid rgba(15, 23, 42, 0.1); background: #f8fafc; font-weight: 500; transition: all 0.3s; }
    .form-control:focus { background: #ffffff; border-color: #2563eb; box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1); }
    
    .btn-save { background: #10b981; color: white; border: none; padding: 12px 30px; border-radius: 12px; font-weight: 700; transition: all 0.3s; }
    .btn-save:hover { background: #059669; transform: translateY(-2px); box-shadow: 0 8px 15px rgba(16, 185, 129, 0.3); }

    .epp-box { background: #f8fafc; border: 1px dashed rgba(37, 99, 235, 0.3); border-radius: 16px; padding: 30px; text-align: center; }
    
    @media (max-width: 991px) {
        .manage-nav-pills { display: flex; overflow-x: auto; white-space: nowrap; padding: 10px; margin-bottom: 20px; }
        .manage-nav-pills .nav-link { margin-bottom: 0; margin-right: 10px; text-align: center; }
        .manage-nav-pills .nav-link i { display: none; }
    }
</style>

<div class="main-content flex-grow-1 w-100 d-flex flex-column py-4" style="min-height: calc(100vh - 70px);">
    <div class="container" style="max-width: 1200px;">
        
        <div class="mb-3">
            <a href="my-domains.php" class="text-muted text-decoration-none fw-bold"><i class="fa-solid fa-arrow-left me-2"></i>Back to My Domains</a>
        </div>

        <?php if($success_msg): ?>
            <div class="alert alert-success border-0 shadow-sm rounded-3"><i class="fa-solid fa-circle-check me-2"></i> <?= $success_msg ?></div>
        <?php endif; ?>
        <?php if($error_msg): ?>
            <div class="alert alert-danger border-0 shadow-sm rounded-3"><i class="fa-solid fa-triangle-exclamation me-2"></i> <?= $error_msg ?></div>
        <?php endif; ?>

        <div class="domain-header-box d-flex flex-column flex-md-row justify-content-between align-items-center">
            <div>
                <span class="badge bg-success bg-opacity-25 text-success border border-success mb-2 px-3 py-1 rounded-pill">Active</span>
                <h2 class="fw-bold mb-1"><?= htmlspecialchars($domain_name) ?></h2>
                <div class="text-light opacity-75" style="font-size: 14px;">
                    <i class="fa-solid fa-calendar-check me-1"></i> Registered: <?= $created_date->format('d M, Y') ?> &nbsp;|&nbsp; 
                    <i class="fa-solid fa-calendar-xmark me-1"></i> Expires: <span class="text-warning fw-bold"><?= $expiry_date->format('d M, Y') ?></span>
                </div>
            </div>
            <div class="mt-4 mt-md-0 text-md-end">
                <a href="<?= 'http://' . htmlspecialchars($domain_name) ?>" target="_blank" class="btn btn-light rounded-pill fw-bold px-4">
                    Visit Website <i class="fa-solid fa-arrow-up-right-from-square ms-2"></i>
                </a>
            </div>
        </div>

        <div class="row">
            <!-- Sidebar Tabs -->
            <div class="col-lg-3 mb-4">
                <div class="nav flex-column nav-pills manage-nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
                    <button class="nav-link active" id="v-pills-ns-tab" data-bs-toggle="pill" data-bs-target="#v-pills-ns" type="button" role="tab"><i class="fa-solid fa-server"></i> Nameservers</button>
                    <button class="nav-link" id="v-pills-contact-tab" data-bs-toggle="pill" data-bs-target="#v-pills-contact" type="button" role="tab"><i class="fa-solid fa-address-card"></i> Contact Info</button>
                    <button class="nav-link" id="v-pills-dns-tab" data-bs-toggle="pill" data-bs-target="#v-pills-dns" type="button" role="tab"><i class="fa-solid fa-network-wired"></i> DNS Records</button>
                    <button class="nav-link" id="v-pills-pns-tab" data-bs-toggle="pill" data-bs-target="#v-pills-pns" type="button" role="tab"><i class="fa-solid fa-share-nodes"></i> Personal NS</button>
                    <button class="nav-link" id="v-pills-email-tab" data-bs-toggle="pill" data-bs-target="#v-pills-email" type="button" role="tab"><i class="fa-solid fa-envelope-open-text"></i> Email Forward</button>
                    <button class="nav-link" id="v-pills-epp-tab" data-bs-toggle="pill" data-bs-target="#v-pills-epp" type="button" role="tab"><i class="fa-solid fa-key"></i> Get EPP Code</button>
                </div>
            </div>

            <!-- Tab Contents -->
            <div class="col-lg-9">
                <div class="tab-content tab-content-box" id="v-pills-tabContent">
                    
                    <!-- 1. Nameservers -->
                    <div class="tab-pane fade show active" id="v-pills-ns" role="tabpanel">
                        <h4 class="fw-bold mb-4">Manage Nameservers</h4>
                        <div class="alert alert-info border-0 shadow-sm mb-4" style="font-size: 14px;">
                            <i class="fa-solid fa-circle-info me-2"></i> Current Nameservers are fetched directly from the registrar.
                        </div>
                        <form action="" method="POST">
                            <div class="row g-3 mb-4">
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Nameserver 1</label>
                                    <input type="text" name="ns1" class="form-control" value="<?= htmlspecialchars($ns1_val) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Nameserver 2</label>
                                    <input type="text" name="ns2" class="form-control" value="<?= htmlspecialchars($ns2_val) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Nameserver 3 <span class="text-muted fw-normal">(Optional)</span></label>
                                    <input type="text" name="ns3" class="form-control" value="<?= htmlspecialchars($ns3_val) ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Nameserver 4 <span class="text-muted fw-normal">(Optional)</span></label>
                                    <input type="text" name="ns4" class="form-control" value="<?= htmlspecialchars($ns4_val) ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Nameserver 5 <span class="text-muted fw-normal">(Optional)</span></label>
                                    <input type="text" name="ns5" class="form-control" value="<?= htmlspecialchars($ns5_val) ?>">
                                </div>
                            </div>
                            <button type="submit" name="update_ns" class="btn-save"><i class="fa-solid fa-floppy-disk me-2"></i> Save Nameservers</button>
                        </form>
                    </div>

                    <!-- 2. Contact Info -->
                    <div class="tab-pane fade" id="v-pills-contact" role="tabpanel">
                        <h4 class="fw-bold mb-4">Registrant Contact Info</h4>
                        <form action="" method="POST">
                            <div class="row g-3 mb-4">
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">First Name</label>
                                    <input type="text" name="firstname" class="form-control" value="<?= htmlspecialchars($c_firstname) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Last Name</label>
                                    <input type="text" name="lastname" class="form-control" value="<?= htmlspecialchars($c_lastname) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Email Address</label>
                                    <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($c_email) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold text-dark mb-2">Phone Number</label>
                                    <input type="text" name="phonenumber" class="form-control" value="<?= htmlspecialchars($c_phone) ?>" required>
                                </div>
                                <div class="col-12">
                                    <label class="fw-bold text-dark mb-2">Company Name <span class="text-muted fw-normal">(Optional)</span></label>
                                    <input type="text" name="companyname" class="form-control" value="<?= htmlspecialchars($c_company) ?>">
                                </div>
                                <div class="col-12">
                                    <label class="fw-bold text-dark mb-2">Address</label>
                                    <input type="text" name="address1" class="form-control" value="<?= htmlspecialchars($c_address) ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold text-dark mb-2">City</label>
                                    <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($c_city) ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold text-dark mb-2">State/Region</label>
                                    <input type="text" name="state" class="form-control" value="<?= htmlspecialchars($c_state) ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold text-dark mb-2">Postcode</label>
                                    <input type="text" name="postcode" class="form-control" value="<?= htmlspecialchars($c_postcode) ?>" required>
                                </div>
                                <div class="col-md-12">
                                    <label class="fw-bold text-dark mb-2">Country (2-Letter Code e.g. BD, US)</label>
                                    <input type="text" name="country" class="form-control" value="<?= htmlspecialchars($c_country) ?>" maxlength="2" required>
                                </div>
                            </div>
                            <button type="submit" name="update_contact" class="btn-save"><i class="fa-solid fa-floppy-disk me-2"></i> Save Contact Info</button>
                        </form>
                    </div>

                    <!-- 3. DNS Records -->
                    <div class="tab-pane fade" id="v-pills-dns" role="tabpanel">
                        <h4 class="fw-bold mb-4">DNS Management</h4>
                        <div class="alert alert-warning border-0 shadow-sm" style="font-size: 14px;">
                            <i class="fa-solid fa-circle-info me-2"></i> Domain must use default nameservers to manage DNS records via API.
                        </div>
                        <p class="text-muted">DNS record fetching and management UI can be built here. Payload requires formatting as <code>dnsrecords</code> array.</p>
                    </div>

                    <!-- 4. Personal NS -->
                    <div class="tab-pane fade" id="v-pills-pns" role="tabpanel">
                        <h4 class="fw-bold mb-4">Register Personal Nameservers</h4>
                        <form action="" method="POST" class="bg-light p-4 rounded-4 border">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="fw-bold mb-2">Prefix</label>
                                    <div class="input-group">
                                        <input type="text" name="ns_prefix" class="form-control" placeholder="ns1" required>
                                        <span class="input-group-text bg-white">.<?= htmlspecialchars($domain_name) ?></span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold mb-2">IP Address</label>
                                    <input type="text" name="ip_address" class="form-control" placeholder="192.168.1.1" required>
                                </div>
                                <div class="col-12">
                                    <button type="submit" name="register_personal_ns" class="btn btn-primary fw-bold mt-2"><i class="fa-solid fa-plus me-2"></i> Register</button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- 5. Email Forwarding -->
                    <div class="tab-pane fade" id="v-pills-email" role="tabpanel">
                        <h4 class="fw-bold mb-4">Email Forwarding</h4>
                        <form action="" method="POST" class="bg-light p-4 rounded-4 border">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="fw-bold mb-2">Prefix (e.g., admin)</label>
                                    <div class="input-group">
                                        <input type="text" name="email_prefix" class="form-control" placeholder="admin" required>
                                        <span class="input-group-text bg-white">@<?= htmlspecialchars($domain_name) ?></span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold mb-2">Forward To</label>
                                    <input type="email" name="forward_to" class="form-control" placeholder="your.email@gmail.com" required>
                                </div>
                                <div class="col-12">
                                    <button type="submit" name="setup_email_forward" class="btn btn-primary fw-bold mt-2"><i class="fa-solid fa-plus me-2"></i> Add Forwarder</button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- 6. Get EPP Code -->
                    <div class="tab-pane fade" id="v-pills-epp" role="tabpanel">
                        <h4 class="fw-bold mb-4">Transfer EPP/Auth Code</h4>
                        <div class="epp-box">
                            <i class="fa-solid fa-shield-halved fs-1 text-primary mb-3"></i>
                            <h5 class="fw-bold text-dark">Domain Authorization Code</h5>
                            <p class="text-muted mb-4">You need this code to transfer your domain to another registrar.</p>
                            
                            <div class="d-none" id="eppCodeDisplay">
                                <div class="bg-dark text-warning fs-4 fw-bold py-3 rounded-3 mb-3 font-monospace letter-spacing-2" id="eppValue">
                                    Loading...
                                </div>
                            </div>

                            <button type="button" class="btn btn-primary fw-bold px-4 py-2 rounded-pill shadow-sm" id="btnRevealEPP" onclick="fetchEPPCode()">
                                <i class="fa-solid fa-eye me-2"></i> Request EPP Code
                            </button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Live API call for EPP Code
    function fetchEPPCode() {
        let btn = document.getElementById('btnRevealEPP');
        let displayBox = document.getElementById('eppCodeDisplay');
        let valBox = document.getElementById('eppValue');
        
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Fetching from Registrar...';
        btn.disabled = true;

        fetch(`manage-domain.php?id=<?= $domain_id ?>&ajax_epp=1`)
            .then(res => res.json())
            .then(data => {
                btn.style.display = 'none';
                displayBox.classList.remove('d-none');
                
                if(data.eppcode) {
                    valBox.innerText = data.eppcode;
                } else if (data.message) {
                    valBox.innerHTML = `<span class="text-danger fs-6">${data.message}</span>`;
                } else if (data.error) {
                    valBox.innerHTML = `<span class="text-danger fs-6">${data.error}</span>`;
                } else {
                    valBox.innerText = "Error fetching code.";
                }
            })
            .catch(err => {
                btn.innerHTML = '<i class="fa-solid fa-eye me-2"></i> Try Again';
                btn.disabled = false;
                alert("Failed to connect to API.");
            });
    }
</script>

<?php require_once 'includes/user_footer.php'; ?>