<?php
/*
Plugin Name: Domain Name Generator
Plugin URI: https://yourwebsite.com/
Description: Generates domain name suggestions and checks availability via GoDaddy API.
Version: 1.0
Author: Your Name
Author URI: https://yourwebsite.com/
License: GPLv2 or later
*/

// Enqueue necessary scripts and styles
function dng_enqueue_scripts() {
    wp_enqueue_style('dng-style', plugins_url('style.css', __FILE__));
    wp_enqueue_script('dng-script', plugins_url('script.js', __FILE__), array('jquery'), '1.0', true);
    wp_localize_script('dng-script', 'dng_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'dng_enqueue_scripts');

// Default suffixes
function dng_get_default_suffixes() {
    return array(
        'hq', 'app', 'io', 'ai', 'ly', 'up', 'zen', 'nomad', 'ninja', 'today',
        'now', 'space', 'digital', 'online', 'site', 'web', 'net', 'tech', 'co', 'studio'
    );
}

// Shortcode for the domain generator form
function dng_domain_generator_shortcode() {
    ob_start();
    ?>
    <div class="domain-generator-container">
        <h3>Find Your Perfect Domain</h3>
        <form id="domain-generator-form">
            <div class="form-group">
                <label for="prefix">Enter your brand name:</label>
                <input type="text" id="prefix" name="prefix" placeholder="e.g. mybusiness" required>
            </div>
            
            <div class="form-group">
                <label>Select suffix types:</label>
                <div class="suffix-options">
                    <?php 
                    $suffixes = dng_get_default_suffixes();
                    foreach ($suffixes as $suffix) {
                        echo '<label><input type="checkbox" name="suffixes[]" value="'.$suffix.'" checked> .'.$suffix.'</label>';
                    }
                    ?>
                </div>
            </div>
            
            <div class="form-group">
                <label for="tld">Or enter custom suffix:</label>
                <input type="text" id="custom-suffix" name="custom_suffix" placeholder="e.g. shop">
            </div>
            
            <button type="submit" id="generate-domains">Generate Domains</button>
        </form>
        
        <div id="domain-results">
            <h4>Generated Domains</h4>
            <div id="domain-list"></div>
            <div id="availability-results"></div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('domain_generator', 'dng_domain_generator_shortcode');

// AJAX handler for domain generation
function dng_generate_domains() {
    $prefix = sanitize_text_field($_POST['prefix']);
    $suffixes = isset($_POST['suffixes']) ? $_POST['suffixes'] : array();
    $custom_suffix = sanitize_text_field($_POST['custom_suffix']);
    
    // Add custom suffix if provided
    if (!empty($custom_suffix)) {
        $suffixes[] = $custom_suffix;
    }
    
    // Generate domain combinations
    $domains = array();
    foreach ($suffixes as $suffix) {
        $domain = $prefix . $suffix . '.com';
        $domains[] = array(
            'name' => $domain,
            'display' => $domain
        );
        
        // Also add version with hyphen
        $domain_hyphen = $prefix . '-' . $suffix . '.com';
        $domains[] = array(
            'name' => $domain_hyphen,
            'display' => $domain_hyphen
        );
    }
    
    wp_send_json_success($domains);
}
add_action('wp_ajax_dng_generate_domains', 'dng_generate_domains');
add_action('wp_ajax_nopriv_dng_generate_domains', 'dng_generate_domains');

// AJAX handler for domain availability check
function dng_check_availability() {
    $domain = sanitize_text_field($_POST['domain']);
    
    // Get GoDaddy API credentials from settings
    $options = get_option('dng_settings');
    $api_key = isset($options['api_key']) ? $options['api_key'] : '';
    $api_secret = isset($options['api_secret']) ? $options['api_secret'] : '';
    
        // if (empty($api_key) {
        //     wp_send_json_error(array('message' => 'API not configured. Please contact site administrator.'));
        // }
    
    // Prepare API request
    $url = 'https://api.godaddy.com/v1/domains/available?domain=' . $domain;
    
    $args = array(
        'headers' => array(
            'Authorization' => 'sso-key ' . $api_key . ':' . $api_secret,
            'Accept' => 'application/json'
        )
    );
    
    $response = wp_remote_get($url, $args);
    
    if (is_wp_error($response)) {
        wp_send_json_error(array('message' => 'Error connecting to GoDaddy API.'));
    }
    
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    if (isset($body['available'])) {
        wp_send_json_success(array(
            'available' => $body['available'],
            'price' => isset($body['price']) ? $body['price'] : 'N/A'
        ));
    } else {
        wp_send_json_error(array('message' => 'Error checking domain availability.'));
    }
}
add_action('wp_ajax_dng_check_availability', 'dng_check_availability');
add_action('wp_ajax_nopriv_dng_check_availability', 'dng_check_availability');

// Admin settings page
function dng_add_admin_menu() {
    add_options_page('Domain Name Generator Settings', 'Domain Generator', 'manage_options', 'domain-name-generator', 'dng_options_page');
}
add_action('admin_menu', 'dng_add_admin_menu');

function dng_options_page() {
    ?>
    <div class="wrap">
        <h1>Domain Name Generator Settings</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('dng_settings');
            do_settings_sections('dng_settings');
            ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">GoDaddy API Key</th>
                    <td><input type="text" name="dng_settings[api_key]" value="<?php echo esc_attr(get_option('dng_settings')['api_key']); ?>" /></td>
                </tr>
                <tr valign="top">
                    <th scope="row">GoDaddy API Secret</th>
                    <td><input type="password" name="dng_settings[api_secret]" value="<?php echo esc_attr(get_option('dng_settings')['api_secret']); ?>" /></td>
                </tr>
                <tr valign="top">
                    <th scope="row">Default Suffixes</th>
                    <td>
                        <textarea name="dng_settings[custom_suffixes]" rows="5" cols="50"><?php 
                            $suffixes = dng_get_default_suffixes();
                            echo implode("\n", $suffixes);
                        ?></textarea>
                        <p class="description">Enter one suffix per line</p>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

function dng_settings_init() {
    register_setting('dng_settings', 'dng_settings');
}
add_action('admin_init', 'dng_settings_init');

// Create a style.css file in the same directory
function dng_create_style_file() {
    $style_content = '
    .domain-generator-container {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background: #f9f9f9;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .form-group {
        margin-bottom: 15px;
    }
    
    .suffix-options {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .suffix-options label {
        display: flex;
        align-items: center;
        gap: 5px;
        white-space: nowrap;
    }
    
    #domain-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 10px;
        margin: 20px 0;
    }
    
    .domain-item {
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .domain-item.available {
        background-color: #e6f7e6;
        border-color: #a3d8a3;
    }
    
    .domain-item.taken {
        background-color: #ffebeb;
        border-color: #ffb3b3;
    }
    
    .check-availability {
        background: #4CAF50;
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 3px;
        cursor: pointer;
    }
    
    .check-availability:hover {
        background: #3e8e41;
    }
    
    .price {
        font-weight: bold;
        margin-left: 10px;
    }
    ';
    
    file_put_contents(plugin_dir_path(__FILE__) . 'style.css', $style_content);
}

// Create a script.js file in the same directory
function dng_create_script_file() {
    $script_content = '
    jQuery(document).ready(function($) {
        $("#domain-generator-form").on("submit", function(e) {
            e.preventDefault();
            
            var prefix = $("#prefix").val().trim();
            if (!prefix) {
                alert("Please enter a prefix");
                return;
            }
            
            var suffixes = [];
            $("input[name=\"suffixes[]\"]:checked").each(function() {
                suffixes.push($(this).val());
            });
            
            var customSuffix = $("#custom-suffix").val().trim();
            
            $("#domain-list").html("<p>Generating domains...</p>");
            
            $.ajax({
                url: dng_ajax.ajax_url,
                type: "POST",
                data: {
                    action: "dng_generate_domains",
                    prefix: prefix,
                    suffixes: suffixes,
                    custom_suffix: customSuffix
                },
                success: function(response) {
                    if (response.success) {
                        var domains = response.data;
                        var html = "";
                        
                        domains.forEach(function(domain) {
                            html += `
                                <div class="domain-item" data-domain="${domain.name}">
                                    ${domain.display}
                                    <button class="check-availability" data-domain="${domain.name}">Check</button>
                                </div>
                            `;
                        });
                        
                        $("#domain-list").html(html || "<p>No domains generated. Please try different suffixes.</p>");
                        
                        $(".check-availability").on("click", function() {
                            var domain = $(this).data("domain");
                            var domainItem = $(this).closest(".domain-item");
                            
                            $(this).text("Checking...").prop("disabled", true);
                            
                            $.ajax({
                                url: dng_ajax.ajax_url,
                                type: "POST",
                                data: {
                                    action: "dng_check_availability",
                                    domain: domain
                                },
                                success: function(response) {
                                    if (response.success) {
                                        if (response.data.available) {
                                            domainItem.addClass("available").removeClass("taken");
                                            domainItem.append(`<span class="price">$${response.data.price}/year</span>`);
                                        } else {
                                            domainItem.addClass("taken").removeClass("available");
                                            domainItem.append(`<span class="price">Taken</span>`);
                                        }
                                    } else {
                                        alert("Error checking availability: " + response.data.message);
                                    }
                                },
                                error: function() {
                                    alert("Error checking availability");
                                },
                                complete: function() {
                                    $(this).remove();
                                }
                            });
                        });
                    } else {
                        $("#domain-list").html("<p>Error generating domains. Please try again.</p>");
                    }
                },
                error: function() {
                    $("#domain-list").html("<p>Error generating domains. Please try again.</p>");
                }
            });
        });
    });
    ';
    
    file_put_contents(plugin_dir_path(__FILE__) . 'script.js', $script_content);
}

// Create necessary files on plugin activation
function dng_activate_plugin() {
    dng_create_style_file();
    dng_create_script_file();
}
register_activation_hook(__FILE__, 'dng_activate_plugin');