<?php
function getData($key, $default = '') {
    return isset($_POST[$key]) ? $_POST[$key] : $default;
}

function getError($key, $error) {
    return isset($error[$key]) ? '<div class="text-danger small">'. $error[$key] .'</div>'  : '';
}

function safeGet($func, $default = 'N/A') {
    try {
        if (function_exists($func)) {
            $result = call_user_func($func);
            return ($result !== false && $result !== null && $result !== '') ? $result : $default;
        }
        return $default;
    } catch (Exception $e) {
        return $default;
    }
}

function safeGetValue($value, $default = 'N/A') {
    return ($value !== false && $value !== null && $value !== '') ? $value : $default;
}

$allow_installed = true;
$serverReq = [];
try {
    $serverReq = function_exists('checkReq') ? checkReq() : [];
} catch (Exception $e) {
    $serverReq = [];
}

// Safely get system information
$maxExecutionTime = safeGet('php_max_execution_time', 'N/A');
$architecture = safeGetValue(php_uname('m'), 'Unknown');
$serverOS = safeGet('server_os', 'Unknown');
$serverIP = safeGet('check_server_ip', 'Unknown');
$memoryLimit = safeGet('check_limit', 'Unknown');
$maxUploadSize = safeGet('php_max_upload_size', 'N/A');
$maxPostSize = safeGet('php_max_post_size', 'N/A');
$maxInputVars = safeGetValue(ini_get('max_input_vars'), 'N/A');
$isSSL = safeGet('is_ssl', false);
$phpVersion = safeGetValue(PHP_VERSION, 'Unknown');

// Try to get existing database config
$existingConfig = getExistingDbConfig();

// Try to get existing license config
$existingLicense = getExistingLicenseConfig();

// Use existing config as defaults if available
$defaultHostname = $existingConfig ? $existingConfig['hostname'] : 'localhost';
$defaultPort = $existingConfig ? $existingConfig['port'] : '3306';
$defaultDbUsername = $existingConfig ? $existingConfig['username'] : '';
$defaultPassword = $existingConfig ? $existingConfig['password'] : '';
$defaultDatabase = $existingConfig ? $existingConfig['database'] : '';

// License defaults
$defaultPurchaseCode = $existingLicense ? $existingLicense['purchase_code'] : '';
$defaultLicenseUsername = $existingLicense ? $existingLicense['username'] : 'admin';
?>

<!-- Progress Steps -->
<div class="row mb-2">
    <div class="col-12">
        <div class="d-flex justify-content-center align-items-center">
            <div class="text-center me-3">
                <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                    <span class="fw-bold small">1</span>
                </div>
                <div class="mt-1 fw-bold text-primary small">Installation</div>
            </div>
            <div class="bg-primary rounded" style="height: 2px; width: 40px;"></div>
            <div class="text-center ms-3">
                <div class="bg-light text-muted rounded-circle d-inline-flex align-items-center justify-content-center border" style="width: 30px; height: 30px;">
                    <span class="fw-bold small">2</span>
                </div>
                <div class="mt-1 text-muted small">Complete</div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <!-- Installation Form -->
    <div class="col-lg-8">
        <div class="card shadow-sm">
            <div class="card-header bg-primary text-white py-2">
                <h6 class="card-title mb-0">
                    <i class="bi bi-database-gear me-2"></i>
                    Installation Configuration
                </h6>
            </div>
            <div class="card-body p-3">
                <?php if($checkIsInstall ?? false): ?>
                    <div class="alert alert-info py-2 mb-3">
                        <small class="fw-semibold">Re-installation Detected</small>
                        <div class="small">Re-type your CodeCanyon details and database info, then continue. 
                        <a class="alert-link" href="https://codecanyon.net/item/affiliate-management-system/25393355" target="_blank">Need a license?</a></div>
                    </div>
                <?php elseif($existingConfig || $existingLicense): ?>
                    <div class="alert alert-success py-2 mb-3">
                        <small class="fw-semibold">
                            <i class="bi bi-check-circle me-1"></i>
                            Existing Configuration Detected
                        </small>
                        <div class="small">Form fields have been pre-filled with your existing settings. Review and update as needed.</div>
                    </div>
                    
                    <!-- License Information Card (Compact) -->
                    <?php if($existingLicense && isset($existingLicense['license_type'])): ?>
                    <div class="card border-success mb-3">
                        <div class="card-header bg-success text-white py-2">
                            <h6 class="card-title mb-0">
                                <i class="bi bi-shield-check me-2"></i>
                                License Information
                            </h6>
                        </div>
                        <div class="card-body p-2">
                            <div class="row g-2 text-center">
                                <div class="col-3">
                                    <div class="border rounded p-2">
                                        <small class="text-muted d-block">License Type</small>
                                        <small class="fw-bold text-success"><?= htmlspecialchars($existingLicense['license_type']) ?></small>
                                    </div>
                                </div>
                                <div class="col-3">
                                    <div class="border rounded p-2">
                                        <small class="text-muted d-block">Owner</small>
                                        <small class="fw-bold text-primary"><?= htmlspecialchars($existingLicense['username']) ?></small>
                                    </div>
                                </div>
                                <div class="col-3">
                                    <div class="border rounded p-2">
                                        <small class="text-muted d-block">Purchased</small>
                                        <small class="fw-bold text-info">
                                            <?php if(!empty($existingLicense['purchase_date'])): ?>
                                                <?= date('M Y', strtotime($existingLicense['purchase_date'])) ?>
                                            <?php else: ?>
                                                N/A
                                            <?php endif; ?>
                                        </small>
                                    </div>
                                </div>
                                <div class="col-3">
                                    <div class="border rounded p-2">
                                        <small class="text-muted d-block">Usage</small>
                                        <small class="fw-bold text-warning"><?= $existingLicense['purchase_count'] ?>x</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>

                <form id="register_form">
                    <!-- Purchase Code Section -->
                    <div class="mb-3">
                        <small class="text-primary fw-semibold d-block mb-2">
                            <i class="bi bi-key-fill me-1"></i>
                            CodeCanyon License
                        </small>
                        
                        <div class="row g-2 align-items-start">
                            <div class="col-md-6">
                                <input type="text" name="purchase_code" class="form-control form-control-sm" 
                                       placeholder="Enter your CodeCanyon purchase code"
                                       value="<?= getData('purchase_code', $defaultPurchaseCode) ?>"
                                       maxlength="36" 
                                       pattern="[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}"
                                       autocomplete="off">
                                <div class="form-text small">Format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX</div>
                            </div>

                            <div class="col-md-6">
                                <input type="text" name="username" class="form-control form-control-sm" placeholder="Username (Auto-filled)" 
                                       value="<?= getData('username', $defaultLicenseUsername) ?>" readonly autocomplete="off">
                                <div class="form-text small text-muted">Buyer username auto-filled after validation</div>
                            </div>
                        </div>
                    </div>

                    <!-- Database Configuration Section -->
                    <div class="mb-3">
                        <small class="text-primary fw-semibold d-block mb-2">
                            <i class="bi bi-database me-1"></i>
                            Database Configuration
                        </small>

                        <div class="row g-2">
                            <div class="col-md-8">
                                <input type="text" name="db_hostname" class="form-control form-control-sm" placeholder="Database Hostname (localhost)" 
                                       value="<?= getData('db_hostname', $defaultHostname) ?>" autocomplete="off">
                                <?= isset($error) ? getError('db_hostname', $error) : '' ?>
                            </div>
                            <div class="col-md-4">
                                <input type="text" name="db_port" class="form-control form-control-sm" placeholder="Port (3306)" 
                                       value="<?= getData('db_port', $defaultPort) ?>" autocomplete="off">
                                <?= isset($error) ? getError('db_port', $error) : '' ?>
                            </div>
                        </div>

                        <div class="row g-2 mt-1">
                            <div class="col-md-6">
                                <input type="text" name="db_username" class="form-control form-control-sm" placeholder="Database Username" 
                                       value="<?= getData('db_username', $defaultDbUsername) ?>" autocomplete="off">
                                <?= isset($error) ? getError('db_username', $error) : '' ?>
                            </div>
                            
                            <div class="col-md-6">
                                <input type="password" name="db_password" class="form-control form-control-sm" placeholder="Database Password"
                                       value="<?= getData('db_password', $defaultPassword) ?>" autocomplete="new-password">
                            </div>
                        </div>
                        
                        <div class="mt-2">
                            <input type="text" name="db_database" class="form-control form-control-sm" placeholder="Database Name" 
                                   value="<?= getData('db_database', $defaultDatabase) ?>" autocomplete="off">
                            <?= isset($error) ? getError('db_error', $error) : '' ?>
                            <?= isset($error) ? getError('db_database', $error) : '' ?>
                        </div>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="bi bi-arrow-right-circle me-2"></i>
                            Continue Installation
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

<!-- Server Requirements -->
<div class="col-lg-4">
    <div class="card shadow-sm">
        <div class="card-header <?= empty($serverReq) ? 'bg-success' : 'bg-danger' ?> text-white py-2">
            <h6 class="card-title mb-0">
                <i class="bi bi-<?= empty($serverReq) ? 'check-circle' : 'x-circle' ?> me-2"></i>
                Server Status
            </h6>
        </div>
        <div class="card-body p-0">
            <div class="list-group list-group-flush">
                <!-- Core Requirements -->
                <div class="list-group-item d-flex justify-content-between align-items-center py-1">
                    <span class="small">
                        <i class="bi bi-code-slash me-2"></i>
                        PHP <?= $phpVersion ?>
                    </span>
                    <span class="<?= array_key_exists('php', $serverReq) ? 'text-danger' : 'text-success' ?>">
                        <i class="bi bi-<?= array_key_exists('php', $serverReq) ? 'x-circle-fill' : 'check-circle-fill' ?>"></i>
                    </span>
                </div>
                
                <div class="list-group-item d-flex justify-content-between align-items-center py-1">
                    <span class="small"><i class="bi bi-database me-2"></i>MySQLi</span>
                    <span class="<?= array_key_exists('mysqli', $serverReq) ? 'text-danger' : 'text-success' ?>">
                        <i class="bi bi-<?= array_key_exists('mysqli', $serverReq) ? 'x-circle-fill' : 'check-circle-fill' ?>"></i>
                    </span>
                </div>
                
                <div class="list-group-item d-flex justify-content-between align-items-center py-1">
                    <span class="small"><i class="bi bi-globe me-2"></i>cURL Extension</span>
                    <span class="<?= array_key_exists('curl', $serverReq) ? 'text-danger' : 'text-success' ?>">
                        <i class="bi bi-<?= array_key_exists('curl', $serverReq) ? 'x-circle-fill' : 'check-circle-fill' ?>"></i>
                    </span>
                </div>
                
                <div class="list-group-item d-flex justify-content-between align-items-center py-1">
                    <span class="small"><i class="bi bi-shield-check me-2"></i>SSL Status</span>
                    <span class="<?= $isSSL ? 'text-success' : 'text-warning' ?>">
                        <i class="bi bi-<?= $isSSL ? 'check-circle-fill' : 'exclamation-triangle-fill' ?>"></i>
                    </span>
                </div>
                
                <div class="list-group-item d-flex justify-content-between align-items-center py-1">
                    <span class="small"><i class="bi bi-file-zip me-2"></i>Zip Extension</span>
                    <span class="<?= array_key_exists('zip', $serverReq) ? 'text-danger' : 'text-success' ?>">
                        <i class="bi bi-<?= array_key_exists('zip', $serverReq) ? 'x-circle-fill' : 'check-circle-fill' ?>"></i>
                    </span>
                </div>
                
                <div class="list-group-item d-flex justify-content-between align-items-center py-1">
                    <span class="small"><i class="bi bi-image me-2"></i>GD Library</span>
                    <span class="<?= array_key_exists('gd', $serverReq) ? 'text-danger' : 'text-success' ?>">
                        <i class="bi bi-<?= array_key_exists('gd', $serverReq) ? 'x-circle-fill' : 'check-circle-fill' ?>"></i>
                    </span>
                </div>
                <div class="list-group-item d-flex justify-content-between align-items-center py-1">
                    <span class="small"><i class="bi bi-input-cursor me-2"></i>Max Input Vars</span>
                    <span class="<?= array_key_exists('max_input_vars', $serverReq) ? 'text-danger' : 'text-success' ?>">
                        <i class="bi bi-<?= array_key_exists('max_input_vars', $serverReq) ? 'x-circle-fill' : 'check-circle-fill' ?>"></i>
                    </span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- PHP Configuration -->
    <div class="card shadow-sm mt-3">
        <div class="card-header bg-info text-white py-2">
            <h6 class="card-title mb-0">
                <i class="bi bi-gear me-2"></i>
                PHP Configuration
            </h6>
        </div>
        <div class="card-body p-2">
            <div class="row g-2 text-center">
                <div class="col-6">
                    <div class="border rounded p-2">
                        <small class="text-muted d-block">Memory Limit</small>
                        <small class="fw-bold"><?= $memoryLimit ?></small>
                    </div>
                </div>
                <div class="col-6">
                    <div class="border rounded p-2">
                        <small class="text-muted d-block">Max Execution</small>
                        <small class="fw-bold"><?= $maxExecutionTime ?>s</small>
                    </div>
                </div>
                <div class="col-6">
                    <div class="border rounded p-2 <?= array_key_exists('upload_max_filesize', $serverReq) ? 'border-danger' : 'border-success' ?>">
                        <small class="text-muted d-block">Upload Limit</small>
                        <small class="fw-bold <?= array_key_exists('upload_max_filesize', $serverReq) ? 'text-danger' : 'text-success' ?>">
                            <?= $maxUploadSize ?>
                            <i class="bi bi-<?= array_key_exists('upload_max_filesize', $serverReq) ? 'exclamation-triangle' : 'check-circle' ?> ms-1"></i>
                        </small>
                    </div>
                </div>
                <div class="col-6">
                    <div class="border rounded p-2 <?= array_key_exists('post_max_size', $serverReq) ? 'border-danger' : 'border-success' ?>">
                        <small class="text-muted d-block">Post Limit</small>
                        <small class="fw-bold <?= array_key_exists('post_max_size', $serverReq) ? 'text-danger' : 'text-success' ?>">
                            <?= $maxPostSize ?>
                            <i class="bi bi-<?= array_key_exists('post_max_size', $serverReq) ? 'exclamation-triangle' : 'check-circle' ?> ms-1"></i>
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Server Information -->
    <div class="card shadow-sm mt-3">
        <div class="card-header bg-secondary text-white py-2">
            <h6 class="card-title mb-0">
                <i class="bi bi-server me-2"></i>
                Server Information
            </h6>
        </div>
        <div class="card-body p-2">
            <div class="row g-2 text-center">
                <div class="col-6">
                    <div class="border rounded p-2">
                        <small class="text-muted d-block">Server OS</small>
                        <small class="fw-bold"><?= $serverOS ?></small>
                    </div>
                </div>
                <div class="col-6">
                    <div class="border rounded p-2">
                        <small class="text-muted d-block">Server IP</small>
                        <small class="fw-bold"><?= $serverIP ?></small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
</div>
</div>

<!-- Error Messages Section (Compact) -->
<?php if (!empty($serverReq)): ?>
<div class="row mt-2">
    <div class="col-12">
        <div class="alert alert-warning py-2">
            <small class="fw-bold">
                <i class="bi bi-exclamation-triangle me-2"></i>
                Issues Found (<?= count($serverReq) ?>):
            </small>
            <div class="row g-1 mt-1">
                <?php foreach (array_slice($serverReq, 0, 4) as $key => $error): ?>
                <div class="col-md-6 col-lg-3">
                    <small>
                        <strong><?= ucfirst(str_replace('_', ' ', $key)) ?>:</strong> 
                        <?= str_replace('Warning: ', '', $error) ?>
                    </small>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script type="text/javascript">
    // Form submission with Bootstrap 5 styling
    $("#register_form").submit(function(){
        $this = $(this);
        
        // Clear ALL previous errors and alerts
        $this.find(".is-invalid").removeClass("is-invalid");
        $this.find(".invalid-feedback").remove();
        $this.find(".alert").remove();
        
        $.ajax({
            url:'proccess.php',
            type:'POST',
            dataType:'json',
            data:$this.serialize()+'&page=step2',
            beforeSend:function(){
                $this.find("button[type=submit]")
                    .prop('disabled', true)
                    .html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Processing...');
            },
            complete:function(){
                $this.find("button[type=submit]")
                    .prop('disabled', false)
                    .html('<i class="bi bi-arrow-right-circle me-2"></i>Continue Installation');
            },
            success:function(json){
                if(json && json['html']){
                    $("#main").html(json['html']);
                    
                    setTimeout(function() {
                        const adminBtn = document.querySelector('.btn-primary');
                        if (adminBtn && !document.activeElement.matches('button, a, input')) {
                            adminBtn.focus();
                            adminBtn.style.boxShadow = '0 0 0 3px rgba(13, 110, 253, 0.25)';
                            setTimeout(function() {
                                adminBtn.style.boxShadow = '';
                            }, 3000);
                        }
                        
                        const removeBtn = document.querySelector('.remove-installer-btn');
                        if (removeBtn) {
                            console.log('Remove button found:', removeBtn);
                            console.log('License:', removeBtn.dataset.license);
                            console.log('Endpoint:', removeBtn.dataset.endpoint);
                            
                            removeBtn.addEventListener('click', function(e) {
                                e.preventDefault();
                                console.log('Button clicked!');
                                
                                const feedback = document.querySelector('.remove-installer-feedback');
                                if (!removeBtn.dataset.license) {
                                    if (feedback) {
                                        feedback.classList.add('text-danger', 'fw-semibold');
                                        feedback.textContent = 'License key missing. Please remove the folder manually.';
                                    }
                                    console.error('No license key found');
                                    removeBtn.disabled = false;
                                    return;
                                }
                                
                                removeBtn.disabled = true;
                                removeBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Removing...';
                                
                                if (feedback) {
                                    feedback.classList.remove('text-success', 'text-danger');
                                    feedback.textContent = 'Removing installer directory...';
                                }
                                
                                console.log('Sending request to:', removeBtn.dataset.endpoint);
                                console.log('With license:', removeBtn.dataset.license);

                                fetch(removeBtn.dataset.endpoint, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                                        'X-Requested-With': 'XMLHttpRequest'
                                    },
                                    body: 'license=' + encodeURIComponent(removeBtn.dataset.license)
                                })
                                .then(response => {
                                    console.log('Response status:', response.status);
                                    return response.text();
                                })
                                .then(text => {
                                    console.log('Response text:', text);
                                    let json;
                                    try {
                                        json = JSON.parse(text);
                                    } catch (e) {
                                        console.error('Failed to parse JSON:', e);
                                        if (feedback) {
                                            feedback.classList.add('text-danger', 'fw-semibold');
                                            feedback.textContent = 'Server error: ' + text.substring(0, 100);
                                        }
                                        removeBtn.disabled = false;
                                        removeBtn.innerHTML = '<i class="bi bi-trash me-2"></i>Remove Installer Folder Now';
                                        return;
                                    }
                                    
                                    console.log('Parsed JSON:', json);
                                    
                                    if (json.success) {
                                        const alertBox = removeBtn.closest('.alert');
                                        if (alertBox) {
                                            alertBox.classList.remove('alert-warning', 'border-warning');
                                            alertBox.classList.add('alert-success', 'border-success');
                                            alertBox.innerHTML = '<div class="d-flex align-items-start">' +
                                                '<div class="flex-shrink-0"><i class="bi bi-check-circle-fill fs-3 text-success"></i></div>' +
                                                '<div class="flex-grow-1 ms-3">' +
                                                    '<h5 class="alert-heading mb-2 fw-bold"><i class="bi bi-shield-check me-2"></i>Installation Secured</h5>' +
                                                    '<p class="mb-0">' + (json.message || 'Installer directory removed successfully. Your installation is now secure.') + '</p>' +
                                                '</div>' +
                                            '</div>';
                                        }
                                    } else {
                                        removeBtn.disabled = false;
                                        removeBtn.innerHTML = '<i class="bi bi-trash me-2"></i>Remove Installer Folder Now';
                                        if (feedback) {
                                            feedback.classList.add('text-danger', 'fw-semibold');
                                            feedback.textContent = json.message || 'Unable to remove installer directory.';
                                        }
                                    }
                                })
                                .catch(err => {
                                    console.error('Fetch error:', err);
                                    removeBtn.disabled = false;
                                    removeBtn.innerHTML = '<i class="bi bi-trash me-2"></i>Remove Installer Folder Now';
                                    if (feedback) {
                                        feedback.classList.add('text-danger', 'fw-semibold');
                                        feedback.textContent = 'Request failed: ' + err.message;
                                    }
                                });
                            });
                        } else {
                            console.error('Remove button not found!');
                        }
                    }, 100);
                }

                if(json && json['errors']){
                    $.each(json['errors'], function(i,j){
                        $ele = $this.find('[name="'+ i +'"]');
                        if($ele.length){
                            $ele.addClass("is-invalid");
                            $ele.after('<div class="invalid-feedback small">'+ j +'</div>');
                        }
                    });
                    
                    if(Object.keys(json['errors']).length > 0) {
                        $this.prepend('<div class="alert alert-danger alert-dismissible fade show py-2" role="alert">' +
                            '<i class="bi bi-exclamation-triangle-fill me-2"></i>' +
                            'Please fix the errors below and try again.' +
                            '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
                            '</div>');
                    }
                }
            },
            error: function(xhr, status, error) {
                $this.prepend('<div class="alert alert-danger alert-dismissible fade show py-2" role="alert">' +
                    '<i class="bi bi-exclamation-triangle-fill me-2"></i>' +
                    'An error occurred while processing your request. Please try again.' +
                    '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
                    '</div>');
            }
        });

        return false;
    });
    
    // Purchase code validation with Bootstrap 5 styling
    $('[name="purchase_code"]').on('input blur change', function(){
        $this = $(this);
        $form = $("#register_form");
        
        var purchaseCode = $this.val().trim();
        var isValidFormat = /^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$/i.test(purchaseCode);
        
        $this.removeClass('is-valid is-invalid');
        $this.siblings('.form-text').removeClass('text-success text-danger').addClass('text-muted');
        
        if (purchaseCode.length === 0) {
            $this.siblings('.form-text').text('Format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX').removeClass('text-success text-danger').addClass('text-muted');
            return;
        }
        
        if (purchaseCode.length !== 36) {
            $this.addClass('is-invalid');
            $this.siblings('.form-text').text('Purchase code must be exactly 36 characters').removeClass('text-muted text-success').addClass('text-danger');
            return;
        }
        
        if (!isValidFormat) {
            $this.addClass('is-invalid');
            $this.siblings('.form-text').text('Invalid format. Use: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX').removeClass('text-muted text-success').addClass('text-danger');
            return;
        }
        
        if (isValidFormat && purchaseCode.length === 36) {
            $this.addClass('is-valid');
            $this.siblings('.form-text').text('Validating purchase code...').removeClass('text-muted text-danger').addClass('text-primary');
            
            $form.find(".is-invalid").not($this).removeClass("is-invalid");
            $form.find(".invalid-feedback").remove();
            $form.find(".alert").remove();
            
            $.ajax({
                url:'codecanyon.php',
                type:'POST',
                dataType:'json',
                data:{
                    code: purchaseCode
                },
                success:function(json){
                    if(json && json['errors']){
                        $('[name="username"]').val('');
                        $this.removeClass('is-valid').addClass('is-invalid');
                        $this.siblings('.form-text').text('Invalid purchase code').removeClass('text-primary text-success').addClass('text-danger');
                        
                        $.each(json['errors'], function(i,j){
                            $ele = $form.find('[name="'+ i +'"]');
                            if($ele.length && $ele[0] !== $this[0]){
                                $ele.addClass("is-invalid");
                                $ele.after('<div class="invalid-feedback small">'+ j +'</div>');
                            }
                        });
                    }else{
                        if(json && json.response && json.response.buyer){
                            $('[name="username"]').val(json.response.buyer);
                            $this.removeClass('is-invalid').addClass('is-valid');
                            $this.siblings('.form-text').text('Purchase code validated successfully!').removeClass('text-primary text-danger').addClass('text-success');
                            
                            // Show license information
                            var licenseInfo = json.response;
                            var licenseCard = '<div class="card border-success mb-3" id="license-info-card">' +
                                '<div class="card-header bg-success text-white py-2">' +
                                    '<h6 class="card-title mb-0">' +
                                        '<i class="bi bi-shield-check me-2"></i>License Information' +
                                    '</h6>' +
                                '</div>' +
                                '<div class="card-body p-2">' +
                                    '<div class="row g-2 text-center">' +
                                        '<div class="col-3">' +
                                            '<div class="border rounded p-2">' +
                                                '<small class="text-muted d-block">License Type</small>' +
                                                '<small class="fw-bold text-success">' + (licenseInfo.license || 'Regular License') + '</small>' +
                                            '</div>' +
                                        '</div>' +
                                        '<div class="col-3">' +
                                            '<div class="border rounded p-2">' +
                                                '<small class="text-muted d-block">Owner</small>' +
                                                '<small class="fw-bold text-primary">' + licenseInfo.buyer + '</small>' +
                                            '</div>' +
                                        '</div>' +
                                        '<div class="col-3">' +
                                            '<div class="border rounded p-2">' +
                                                '<small class="text-muted d-block">Purchased</small>' +
                                                '<small class="fw-bold text-info">' + (licenseInfo.sold_at ? new Date(licenseInfo.sold_at).toLocaleDateString('en-US', {month: 'short', year: 'numeric'}) : 'N/A') + '</small>' +
                                            '</div>' +
                                        '</div>' +
                                        '<div class="col-3">' +
                                            '<div class="border rounded p-2">' +
                                                '<small class="text-muted d-block">Usage</small>' +
                                                '<small class="fw-bold text-warning">' + (licenseInfo.purchase_count || 0) + 'x</small>' +
                                            '</div>' +
                                        '</div>' +
                                    '</div>' +
                                '</div>' +
                            '</div>';
                            
                            // Remove existing license card if any
                            $('#license-info-card').remove();
                            
                            // Add license card after the success alert
                            $('.alert-success').after(licenseCard);
                            
                            // AUTO-FILL DATABASE DETAILS
                            <?php if($existingConfig): ?>
                            $('[name="db_hostname"]').val('<?= addslashes($existingConfig['hostname']) ?>');
                            $('[name="db_port"]').val('<?= addslashes($existingConfig['port']) ?>');
                            $('[name="db_username"]').val('<?= addslashes($existingConfig['username']) ?>');
                            $('[name="db_password"]').val('<?= addslashes($existingConfig['password']) ?>');
                            $('[name="db_database"]').val('<?= addslashes($existingConfig['database']) ?>');
                            
                            // Remove old messages and show new auto-fill notification
                            $('.mb-3').has('[name="db_hostname"]').find('.text-success').remove();
                            $('.mb-3').has('[name="db_hostname"]').find('small.text-primary').after(
                                '<div class="mt-1 text-success small">' +
                                '<i class="bi bi-check-circle-fill me-1"></i>' +
                                'Database details auto-filled from existing configuration' +
                                '</div>'
                            );
                            <?php endif; ?>
                        }
                    }
                },
                error: function() {
                    $this.siblings('.form-text').text('Unable to validate purchase code at this time').removeClass('text-primary text-success').addClass('text-warning');
                }
            });
        }
    });
</script>
</script>