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

// =========================================================
// 1. AJAX CART HANDLER (লাইভ কার্টে অ্যাড করার জন্য)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ajax_add_cart']) && $_POST['ajax_add_cart'] == '1') {
    header('Content-Type: application/json');
    
    if(!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }
    
    $domain_name = $_POST['domain_name'];
    
    // কার্টে ডেটা সেভ করা
    $_SESSION['cart'][$domain_name] = [
        'type' => $_POST['item_type'],
        'name' => $domain_name,
        'price' => $_POST['price'],
        'period' => $_POST['period']
    ];
    
    echo json_encode([
        'status' => 'success', 
        'cart_count' => count($_SESSION['cart'])
    ]);
    exit;
}

// =========================================================
// 2. AJAX SEARCH HANDLER (পেজ রিলোড ছাড়া সার্চ)
// =========================================================
if (isset($_GET['ajax_search']) && $_GET['ajax_search'] == '1') {
    header('Content-Type: application/json');
    
    $domain_input = isset($_GET['domain']) ? strtolower(trim($_GET['domain'])) : '';
    $base_name = preg_replace('/[^a-z0-9\-]/', '', explode('.', $domain_input)[0]);
    
    if(empty($base_name)) {
        echo json_encode(['status' => 'error', 'message' => 'Please enter a valid domain name.']);
        exit;
    }

    $extensions = [];
    try {
        $stmt = $db->query("SELECT * FROM domain_pricing WHERE status='active' ORDER BY id ASC");
        $extensions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {}

    $results = [];

    // সব TLD চেক করা
    foreach($extensions as $ext) {
        $full_domain = $base_name . '.' . $ext['extension'];
        $price = $ext['register_price'];
        
        $is_taken = false;
        if (gethostbyname($full_domain) !== $full_domain) {
            $is_taken = true;
        }

        // কার্টে আগে থেকেই আছে কি না চেক করা
        $in_cart = isset($_SESSION['cart'][$full_domain]);

        $results[] = [
            'domain' => $full_domain,
            'extension' => $ext['extension'],
            'price' => $price,
            'is_taken' => $is_taken,
            'in_cart' => $in_cart,
            'badge_text' => $ext['badge_text'] ?? '',
            'badge_color' => $ext['badge_color'] ?? 'primary'
        ];
    }

    // Suggested Domains
    $suggestions = [];
    if(!empty($extensions)) {
        $prefixes = ['my', 'get', 'the'];
        $suffixes = ['online', 'bd', 'hub'];
        
        $suggest_bases = [
            $prefixes[array_rand($prefixes)] . $base_name,
            $base_name . $suffixes[array_rand($suffixes)]
        ];
        
        foreach($suggest_bases as $sb) {
            $rand_ext = $extensions[array_rand($extensions)];
            $s_domain = $sb . '.' . $rand_ext['extension'];
            
            if (gethostbyname($s_domain) === $s_domain) {
                $suggestions[] = [
                    'domain' => $s_domain,
                    'price' => $rand_ext['register_price'],
                    'in_cart' => isset($_SESSION['cart'][$s_domain])
                ];
            }
        }
    }

    echo json_encode([
        'status' => 'success',
        'base_name' => $base_name,
        'results' => $results,
        'suggestions' => $suggestions
    ]);
    exit;
}
// ==================== AJAX END ==========================

$page_title = "Register Domain";

$extensions = [];
try {
    $stmt = $db->query("SELECT * FROM domain_pricing WHERE status='active' ORDER BY id ASC");
    $extensions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

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-search-header {
        padding: 50px 20px;
        text-align: center;
        background: radial-gradient(circle at center, rgba(37, 99, 235, 0.05) 0%, transparent 70%);
    }
    
    .domain-search-wrapper {
        background: #ffffff;
        border-radius: 50px;
        padding: 8px;
        display: flex;
        box-shadow: 0 15px 35px -5px rgba(37, 99, 235, 0.15);
        border: 1px solid rgba(37, 99, 235, 0.2);
        max-width: 600px;
        margin: 0 auto;
        align-items: center;
    }

    .domain-search-wrapper input {
        border: none;
        padding: 15px 25px;
        width: 100%;
        font-size: 18px;
        outline: none;
        background: transparent;
        color: #0f172a;
        font-weight: 600;
        text-transform: lowercase;
    }

    .btn-search {
        background: #2563eb;
        color: #ffffff !important;
        border: none;
        padding: 12px 35px;
        border-radius: 50px;
        font-weight: 700;
        font-size: 16px;
        box-shadow: 0 10px 20px -5px rgba(37, 99, 235, 0.4);
        transition: all 0.3s ease;
    }
    .btn-search:hover { transform: translateY(-2px); box-shadow: 0 15px 25px -5px rgba(37, 99, 235, 0.5); }

    .search-loader { display: none; padding: 50px 0; text-align: center; }
    .results-wrapper { display: none; max-width: 800px; margin: 0 auto; }
    
    .results-container {
        background: #ffffff;
        border-radius: 20px;
        border: 1px solid rgba(15, 23, 42, 0.05);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.03);
        overflow: hidden;
    }
    
    .result-row {
        padding: 20px 25px;
        border-bottom: 1px solid rgba(15, 23, 42, 0.05);
        display: flex;
        align-items: center;
        justify-content: space-between;
        transition: background 0.3s;
    }
    .result-row:last-child { border-bottom: none; }
    .result-row:hover { background: #f8fafc; }

    .domain-name { font-size: 1.25rem; font-weight: 800; color: #0f172a; }
    
    .status-badge { padding: 5px 12px; border-radius: 50px; font-size: 12px; font-weight: 700; }
    .status-available { background: rgba(16, 185, 129, 0.1); color: #10b981; }
    .status-taken { background: rgba(239, 68, 68, 0.1); color: #ef4444; text-decoration: line-through; }

    /* Button Styles */
    .btn-add-cart {
        background: #10b981; color: white; border: none; padding: 10px 20px;
        border-radius: 12px; font-weight: 700; font-size: 14px; transition: all 0.3s; white-space: nowrap;
    }
    .btn-add-cart:hover { background: #059669; transform: translateY(-2px); box-shadow: 0 8px 15px rgba(16, 185, 129, 0.3); }
    
    .btn-checkout {
        background: #0f172a; color: white; border: none; padding: 10px 20px;
        border-radius: 12px; font-weight: 700; font-size: 14px; transition: all 0.3s; white-space: nowrap;
        text-decoration: none; display: inline-block;
    }
    .btn-checkout:hover { background: #1e293b; color: white; transform: translateY(-2px); box-shadow: 0 8px 15px rgba(15, 23, 42, 0.3); }

    .suggestion-box {
        background: #f8fafc; border: 1px dashed rgba(37, 99, 235, 0.3);
        border-radius: 16px; padding: 20px; margin-top: 30px;
    }

    .tld-card {
        background: #ffffff; border: 1px solid rgba(15, 23, 42, 0.05);
        border-radius: 16px; padding: 25px 20px 20px; text-align: center;
        transition: all 0.3s; position: relative;
    }
    .tld-card:hover { border-color: #2563eb; transform: translateY(-5px); box-shadow: 0 10px 20px rgba(37, 99, 235, 0.1); }

    @media (max-width: 576px) {
        .domain-search-wrapper { flex-direction: column; border-radius: 20px; padding: 10px; }
        .btn-search { width: 100%; margin-top: 5px; }
        .result-row { flex-direction: column; align-items: flex-start; gap: 15px; }
        .result-action { width: 100%; display: flex; justify-content: space-between; align-items: center; }
    }
</style>

<div class="main-content flex-grow-1 w-100 d-flex flex-column" style="min-height: calc(100vh - 70px);">
    
    <!-- Hero Search Area -->
    <section class="domain-search-header">
        <div class="container">
            <h1 class="fw-bold mb-3 text-dark" style="font-size: clamp(2rem, 5vw, 3.5rem);">Find Your Perfect <span class="soft-blue-text">Domain</span></h1>
            <p class="text-secondary fs-5 mb-5">Search availability and secure your identity instantly.</p>

            <form id="domainSearchForm" class="domain-search-wrapper">
                <input type="text" id="domainInput" name="domain" placeholder="Enter domain (e.g. plexioit)" required autocomplete="off" oninput="this.value = this.value.toLowerCase()">
                <button type="submit" class="btn-search" id="searchBtn"><i class="fa-solid fa-magnifying-glass me-2"></i>Search</button>
            </form>
        </div>
    </section>

    <div class="container mb-5 pb-5">
        
        <div class="search-loader" id="searchLoader">
            <div class="spinner-border text-primary mb-3" role="status" style="width: 3rem; height: 3rem;"></div>
            <h5 class="fw-bold text-dark">Checking global servers...</h5>
            <p class="text-muted">Please wait while we check availability for all extensions.</p>
        </div>

        <div class="results-wrapper" id="resultsWrapper">
            <div class="results-container" id="mainResults"></div>

            <div class="suggestion-box d-none" id="suggestionsBox">
                <h5 class="fw-bold text-dark mb-3"><i class="fa-solid fa-lightbulb text-warning me-2"></i> Suggested Domains</h5>
                <div id="suggestionsList"></div>
            </div>
        </div>

        <div id="pricingGrid">
            <h4 class="fw-bold text-center mb-4 mt-5">Available Domain Pricing</h4>
            <div class="row g-3 justify-content-center">
                <?php if(!empty($extensions)): ?>
                    <?php foreach($extensions as $dom): ?>
                    <div class="col-lg-2 col-md-3 col-6">
                        <div class="tld-card h-100">
                            <!-- Show Admin Custom Badge/Tag if exists -->
                            <?php if(!empty($dom['badge_text'])): ?>
                                <span class="badge bg-<?= htmlspecialchars($dom['badge_color'] ?? 'primary') ?> position-absolute top-0 start-50 translate-middle-x mt-2" style="font-size: 10px; padding: 4px 8px;">
                                    <?= htmlspecialchars($dom['badge_text']) ?>
                                </span>
                            <?php endif; ?>
                            
                            <div class="fw-bold fs-4 text-dark mb-2 mt-2">.<?= htmlspecialchars($dom['extension']) ?></div>
                            <?php if($dom['fake_price']): ?>
                                <small class="text-secondary text-decoration-line-through d-block" style="font-size: 12px;">BDT <?= number_format($dom['fake_price']) ?></small>
                            <?php endif; ?>
                            <div class="fw-bold soft-blue-text fs-5">৳ <?= number_format($dom['register_price']) ?></div>
                            <div class="text-muted mt-1" style="font-size: 11px;">Per Year</div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-12 text-center text-muted">No domain extensions configured.</div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>

<script>
// ==========================================
// 1. AJAX Domain Search
// ==========================================
document.getElementById('domainSearchForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    let domainInput = document.getElementById('domainInput').value.trim();
    if(domainInput === '') return;

    document.getElementById('searchBtn').disabled = true;
    document.getElementById('searchBtn').innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';
    document.getElementById('pricingGrid').classList.add('d-none');
    document.getElementById('resultsWrapper').style.display = 'none';
    document.getElementById('searchLoader').style.display = 'block';

    fetch(`register-domain.php?ajax_search=1&domain=${encodeURIComponent(domainInput)}`)
        .then(response => response.json())
        .then(data => {
            if(data.status === 'success') renderResults(data);
            else alert(data.message);
        })
        .finally(() => {
            document.getElementById('searchLoader').style.display = 'none';
            document.getElementById('resultsWrapper').style.display = 'block';
            document.getElementById('searchBtn').disabled = false;
            document.getElementById('searchBtn').innerHTML = '<i class="fa-solid fa-magnifying-glass me-2"></i>Search';
        });
});

function renderResults(data) {
    let mainHtml = `<div class="bg-light p-3 border-bottom fw-bold text-muted text-center" style="font-size: 14px;">
                        Search Results for "${data.base_name}"
                    </div>`;
    
    data.results.forEach(item => {
        // Tag Logic
        let badgeHtml = item.badge_text ? `<span class="badge bg-${item.badge_color} ms-2 align-middle" style="font-size: 10px; position:relative; top:-2px;">${item.badge_text}</span>` : '';
        
        mainHtml += `
            <div class="result-row">
                <div>
                    <span class="domain-name ${item.is_taken ? 'text-muted' : ''}">${item.domain}</span>
                    ${badgeHtml}
                    ${!item.is_taken 
                        ? `<span class="status-badge status-available ms-2"><i class="fa-solid fa-check"></i> Available</span>` 
                        : `<span class="status-badge status-taken ms-2"><i class="fa-solid fa-xmark"></i> Taken</span>`
                    }
                </div>
                
                <div class="result-action mt-2 mt-sm-0">
                    ${!item.is_taken 
                        ? `
                        <div class="d-flex align-items-center gap-3">
                            <span class="fw-bold fs-5" style="color: #2563eb;">৳ ${parseInt(item.price).toLocaleString()} <small class="text-muted fs-6">/yr</small></span>
                            ${!item.in_cart ? `
                                <form class="m-0 ajax-cart-form">
                                    <input type="hidden" name="item_type" value="domain">
                                    <input type="hidden" name="domain_name" value="${item.domain}">
                                    <input type="hidden" name="price" value="${item.price}">
                                    <input type="hidden" name="period" value="1">
                                    <button type="submit" class="btn-add-cart"><i class="fa-solid fa-cart-plus me-1"></i> Add</button>
                                </form>
                            ` : `
                                <a href="cart.php" class="btn-checkout"><i class="fa-solid fa-bag-shopping me-1"></i> Checkout</a>
                            `}
                        </div>
                        `
                        : `<span class="text-muted fw-bold bg-light px-3 py-2 rounded-3" style="font-size: 14px;">Unavailable</span>`
                    }
                </div>
            </div>
        `;
    });
    
    document.getElementById('mainResults').innerHTML = mainHtml;

    // Suggestions Logic
    let sugBox = document.getElementById('suggestionsBox');
    let sugList = document.getElementById('suggestionsList');
    sugList.innerHTML = '';

    if(data.suggestions.length > 0) {
        sugBox.classList.remove('d-none');
        data.suggestions.forEach(item => {
            sugList.innerHTML += `
                <div class="d-flex justify-content-between align-items-center border-bottom border-light py-3">
                    <div>
                        <span class="fw-bold text-dark fs-5">${item.domain}</span>
                        <span class="status-badge status-available ms-2 py-1 px-2" style="font-size: 10px;">Suggestion</span>
                    </div>
                    ${!item.in_cart ? `
                        <form class="m-0 ajax-cart-form">
                            <input type="hidden" name="item_type" value="domain">
                            <input type="hidden" name="domain_name" value="${item.domain}">
                            <input type="hidden" name="price" value="${item.price}">
                            <input type="hidden" name="period" value="1">
                            <button type="submit" class="btn btn-sm btn-outline-primary fw-bold rounded-pill px-3">
                                Add for ৳ ${parseInt(item.price).toLocaleString()}
                            </button>
                        </form>
                    ` : `
                        <a href="cart.php" class="btn btn-sm btn-dark fw-bold rounded-pill px-3">Checkout <i class="fa-solid fa-arrow-right"></i></a>
                    `}
                </div>
            `;
        });
    } else {
        sugBox.classList.add('d-none');
    }
}

// ==========================================
// 2. AJAX Add to Cart Logic
// ==========================================
document.addEventListener('submit', function(e) {
    if(e.target && e.target.classList.contains('ajax-cart-form')) {
        e.preventDefault();
        
        let form = e.target;
        let btn = form.querySelector('button[type="submit"]');
        
        // Button loading state
        btn.disabled = true;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';
        
        let formData = new FormData(form);
        formData.append('ajax_add_cart', '1');
        
        fetch('register-domain.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if(data.status === 'success') {
                // ১. Header এ Cart Count আপডেট করা
                let badge = document.querySelector('.cart-badge');
                if(badge) {
                    badge.innerText = data.cart_count;
                    // ছোট্ট পপ এনিমেশন
                    badge.style.transform = 'translate(30%, -30%) scale(1.3)';
                    setTimeout(() => badge.style.transform = 'translate(30%, -30%) scale(1)', 200);
                }
                
                // ২. Add Button কে Checkout Button এ পরিবর্তন করা
                let container = form.parentElement;
                container.innerHTML = `<a href="cart.php" class="btn-checkout"><i class="fa-solid fa-bag-shopping me-1"></i> Checkout</a>`;
            }
        });
    }
});
</script>

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