/**
 * Candidate Pricing Calculator JavaScript
 */

jQuery(document).ready(function($) {
    
    // Initialize pricing calculator
    function initPricingCalculator() {
        $('.candidate-pricing-calculator').each(function() {
            var $calculator = $(this);
            var $hoursInput = $calculator.find('.pricing-hours-input');
            var $calculateBtn = $calculator.find('.pricing-calculate-btn');
            var $resultDiv = $calculator.find('.pricing-result');
            var candidateId = $calculator.data('candidate-id');
            
            $calculateBtn.on('click', function() {
                var hours = parseInt($hoursInput.val());
                
                if (hours > 0) {
                    calculateCandidateRate(candidateId, hours, $resultDiv);
                } else {
                    $resultDiv.html('<div class="candidate-pricing-result">' + 
                        'Please enter a valid number of hours.' + 
                        '</div>');
                }
            });
            
            // Calculate on Enter key
            $hoursInput.on('keypress', function(e) {
                if (e.which === 13) {
                    $calculateBtn.click();
                }
            });
        });
    }
    
    // Calculate candidate rate via AJAX
    function calculateCandidateRate(candidateId, hours, $resultDiv) {
        $resultDiv.html('<div class="candidate-pricing-result">Calculating...</div>');
        
        $.ajax({
            url: jobster_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'jobster_calculate_candidate_rate',
                candidate_id: candidateId,
                hours: hours,
                nonce: jobster_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    var result = response.data;
                    var resultHtml = '<div class="candidate-pricing-result">';
                    resultHtml += '<strong>Estimated Cost:</strong> ' + result.formatted + '<br>';
                    
                    if (result.type === 'hourly') {
                        resultHtml += 'Based on hourly rate of ' + result.rate + ' per hour for ' + result.hours + ' hours';
                    } else if (result.type === 'daily') {
                        resultHtml += 'Based on daily rate of ' + result.rate + ' for ' + result.days + ' day(s) (' + result.hours_per_day + ' hours per day)';
                    }
                    
                    resultHtml += '</div>';
                    $resultDiv.html(resultHtml);
                } else {
                    $resultDiv.html('<div class="candidate-pricing-result">Error calculating rate. Please try again.</div>');
                }
            },
            error: function() {
                $resultDiv.html('<div class="candidate-pricing-result">Error calculating rate. Please try again.</div>');
            }
        });
    }
    
    // Validate pricing form fields
    function validatePricingFields() {
        var isValid = true;
        
        $('input[name="candidate_hourly_rate"], input[name="candidate_daily_rate"], input[name="candidate_hours_per_day"]').each(function() {
            var $field = $(this);
            var value = parseFloat($field.val());
            
            if ($field.attr('required') && (isNaN(value) || value <= 0)) {
                $field.addClass('error');
                isValid = false;
            } else {
                $field.removeClass('error');
            }
        });
        
        return isValid;
    }
    
    // Add validation to candidate form
    $('form#post').on('submit', function(e) {
        if (!validatePricingFields()) {
            e.preventDefault();
            alert('Please fill in all required pricing fields with valid values.');
            return false;
        }
    });
    
    // Real-time validation
    $('input[name="candidate_hourly_rate"], input[name="candidate_daily_rate"], input[name="candidate_hours_per_day"]').on('blur', function() {
        var $field = $(this);
        var value = parseFloat($field.val());
        
        if ($field.attr('required') && (isNaN(value) || value <= 0)) {
            $field.addClass('error');
        } else {
            $field.removeClass('error');
        }
    });
    
    // Initialize calculator when page loads
    initPricingCalculator();
    
    // Re-initialize calculator after AJAX content loads
    $(document).on('candidate_pricing_loaded', function() {
        initPricingCalculator();
    });
    
});

/**
 * Global function to calculate candidate rate (for external use)
 */
function jobsterCalculateCandidateRate(candidateId, hours, callback) {
    jQuery.ajax({
        url: jobster_ajax.ajax_url,
        type: 'POST',
        data: {
            action: 'jobster_calculate_candidate_rate',
            candidate_id: candidateId,
            hours: hours,
            nonce: jobster_ajax.nonce
        },
        success: function(response) {
            if (typeof callback === 'function') {
                callback(response);
            }
        }
    });
} 