<?php
/**
 * Public Proposal View
 *
 * @package Freelance_Studio
 */

if (!defined('ABSPATH')) {
    exit;
}

$services = is_array($proposal->services) ? $proposal->services : array();
$custom_sections = is_array($proposal->custom_sections) ? $proposal->custom_sections : array();
$primary_color = !empty($settings['invoice_primary_color']) ? $settings['invoice_primary_color'] : '#2271b1';
$primary_color_mode = !empty($settings['invoice_primary_color_mode']) ? $settings['invoice_primary_color_mode'] : 'solid';
$primary_color_2 = !empty($settings['invoice_primary_color_2']) ? $settings['invoice_primary_color_2'] : $primary_color;
$gradient_direction = !empty($settings['invoice_gradient_direction']) ? $settings['invoice_gradient_direction'] : '135';
$just_signed = isset($_GET['signed']) && $_GET['signed'] === '1';
$revision_requested = isset($_GET['revision_requested']) && $_GET['revision_requested'] === '1';
$is_expired = !empty($proposal->valid_until) && strtotime($proposal->valid_until) < time();
$deposit_amount = FS_Proposal::calculate_deposit($proposal);

// Separate custom sections by position
$sections_before = array_filter($custom_sections, function($s) { return ($s['position'] ?? 'before_pricing') === 'before_pricing'; });
$sections_after = array_filter($custom_sections, function($s) { return ($s['position'] ?? '') === 'after_pricing'; });

// Get contractor signature settings
$contractor_signature = !empty($settings['contractor_signature']) ? $settings['contractor_signature'] : '';
$contractor_signer_name = !empty($settings['contractor_signer_name']) ? $settings['contractor_signer_name'] : $settings['business_name'];
$contractor_signer_title = !empty($settings['contractor_signer_title']) ? $settings['contractor_signer_title'] : '';

// Can sign?
$can_sign = !in_array($proposal->status, array('approved', 'converted', 'revision_requested')) && !$is_expired;

// Status for badge
$status_class = 'status-' . $proposal->status;
if ($is_expired && $proposal->status !== 'approved') {
    $status_class = 'status-expired';
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title><?php echo esc_html($proposal->title); ?> - <?php echo esc_html($settings['business_name']); ?></title>
    <?php include dirname(__FILE__) . '/document-styles.php'; ?>
</head>
<body>
    <div class="fs-doc-container">
        <?php if (!empty($portal_url)): ?>
        <a href="<?php echo esc_url($portal_url); ?>" class="fs-doc-back-link">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="15 18 9 12 15 6"/>
            </svg>
            <?php esc_html_e('Back to Dashboard', 'freelance-studio'); ?>
        </a>
        <?php endif; ?>
        
        <div class="fs-doc-card">
            <!-- Header -->
            <div class="fs-doc-header">
                <?php
                    $header_logo = !empty($settings['business_logo_light']) ? $settings['business_logo_light'] : (!empty($settings['business_logo']) ? $settings['business_logo'] : '');
                ?>
                <?php if ($header_logo): ?>
                    <img src="<?php echo esc_url($header_logo); ?>" alt="<?php echo esc_attr($settings['business_name']); ?>" class="fs-doc-logo">
                <?php endif; ?>
                <div class="fs-doc-business-name"><?php echo esc_html($settings['business_name']); ?></div>
                <h1 class="fs-doc-title"><?php echo esc_html($proposal->title); ?></h1>
                <div class="fs-doc-number"><?php esc_html_e('Proposal', 'freelance-studio'); ?></div>
                
                <?php if ($proposal->status === 'approved'): ?>
                    <span class="fs-status-badge status-approved"><?php esc_html_e('Approved', 'freelance-studio'); ?></span>
                <?php elseif ($is_expired): ?>
                    <span class="fs-status-badge status-expired"><?php esc_html_e('Expired', 'freelance-studio'); ?></span>
                <?php elseif ($proposal->status === 'revision_requested'): ?>
                    <span class="fs-status-badge status-revision"><?php esc_html_e('Revision Requested', 'freelance-studio'); ?></span>
                <?php elseif ($just_signed): ?>
                    <span class="fs-status-badge status-approved"><?php esc_html_e('Approved', 'freelance-studio'); ?></span>
                <?php else: ?>
                    <span class="fs-status-badge <?php echo esc_attr($status_class); ?>"><?php echo esc_html(ucfirst($proposal->status)); ?></span>
                <?php endif; ?>
            </div>
            
            <!-- Body -->
            <div class="fs-doc-body">
                <!-- Success messages -->
                <?php if ($just_signed): ?>
                    <div class="fs-doc-notes" style="background: #d1fae5; margin-bottom: 24px;">
                        <p style="color: #065f46; text-align: center; margin: 0;">✓ <?php esc_html_e('Thank you! Your signature has been recorded.', 'freelance-studio'); ?></p>
                    </div>
                <?php elseif ($revision_requested): ?>
                    <div class="fs-doc-notes" style="background: #fef3c7; margin-bottom: 24px;">
                        <p style="color: #92400e; text-align: center; margin: 0;">✓ <?php esc_html_e('Thank you! Your revision request has been submitted.', 'freelance-studio'); ?></p>
                    </div>
                <?php endif; ?>
                
                <!-- Parties -->
                <div class="fs-doc-parties">
                    <h2 class="fs-doc-section-title"><?php esc_html_e('Parties', 'freelance-studio'); ?></h2>
                    <div class="fs-doc-parties-grid">
                        <div class="fs-doc-party-card">
                            <div class="fs-doc-party-label contractor"><?php esc_html_e('Contractor', 'freelance-studio'); ?></div>
                            <div class="fs-doc-party-name"><?php echo esc_html($settings['business_name']); ?></div>
                            <?php if (!empty($settings['business_email'])): ?>
                                <p><?php echo esc_html($settings['business_email']); ?></p>
                            <?php endif; ?>
                            <?php if (!empty($settings['business_phone'])): ?>
                                <p><?php echo esc_html($settings['business_phone']); ?></p>
                            <?php endif; ?>
                        </div>
                        
                        <div class="fs-doc-party-card">
                            <div class="fs-doc-party-label client"><?php esc_html_e('Client', 'freelance-studio'); ?></div>
                            <?php if ($client): ?>
                                <?php if (!empty($client->company_name)): ?>
                                    <div class="fs-doc-party-name"><?php echo esc_html($client->company_name); ?></div>
                                    <p><?php echo esc_html($client->name); ?></p>
                                <?php else: ?>
                                    <div class="fs-doc-party-name"><?php echo esc_html($client->name); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($client->email)): ?>
                                    <p><?php echo esc_html($client->email); ?></p>
                                <?php endif; ?>
                                <?php if (!empty($client->phone)): ?>
                                    <p><?php echo esc_html($client->phone); ?></p>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Dates -->
                <?php if ($proposal->start_date || $proposal->valid_until): ?>
                <div class="fs-doc-dates">
                    <?php if ($proposal->start_date): ?>
                    <div class="fs-doc-date-item">
                        <label><?php esc_html_e('Start Date', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($proposal->start_date)) ); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($proposal->valid_until): ?>
                    <div class="fs-doc-date-item <?php echo $is_expired ? 'overdue' : ''; ?>">
                        <label><?php esc_html_e('Valid Until', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($proposal->valid_until)) ); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <!-- Custom Sections: Before Pricing -->
                <?php if (!empty($sections_before)): ?>
                    <?php foreach ($sections_before as $section): ?>
                        <div class="fs-doc-custom-section">
                            <?php if (!empty($section['title'])): ?>
                                <h3><?php echo esc_html($section['title']); ?></h3>
                            <?php endif; ?>
                            <div class="fs-doc-custom-section-content">
                                <?php echo wp_kses_post($section['content']); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
                
                <!-- Services -->
                <?php if (!empty($services)): ?>
                <div class="fs-doc-section">
                    <h2 class="fs-doc-section-title"><?php esc_html_e('Services', 'freelance-studio'); ?></h2>
                    <table class="fs-doc-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Service', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($services as $service): ?>
                            <tr>
                                <td>
                                    <div class="fs-doc-item-name"><?php echo esc_html($service['name']); ?></div>
                                    <?php if (!empty($service['description'])): ?>
                                        <div class="fs-doc-item-description"><?php echo nl2br(esc_html($service['description'])); ?></div>
                                    <?php endif; ?>
                                    <?php 
                                    $rate_type = $service['rate_type'] ?? 'flat';
                                    if ($rate_type === 'hourly' && !empty($service['hours'])): ?>
                                        <div class="fs-doc-item-meta">
                                            <?php echo esc_html($service['hours']); ?> <?php esc_html_e('hours', 'freelance-studio'); ?> 
                                            × <?php echo  esc_html( FS_View_Context::format_currency($service['rate'] ?? 0) ); ?>
                                        </div>
                                    <?php elseif ($rate_type === 'quantity' && !empty($service['quantity'])): ?>
                                        <div class="fs-doc-item-meta">
                                            <?php echo esc_html($service['quantity']); ?> <?php esc_html_e('items', 'freelance-studio'); ?> 
                                            × <?php echo  esc_html( FS_View_Context::format_currency($service['rate'] ?? 0) ); ?>
                                        </div>
                                    <?php elseif ($rate_type === 'flat'): ?>
                                        <div class="fs-doc-item-meta"><?php esc_html_e('Flat fee', 'freelance-studio'); ?></div>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo  esc_html( FS_View_Context::format_currency($service['amount'] ?? 0) ); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <!-- Totals -->
                    <div class="fs-doc-totals">
                        <div class="fs-doc-totals-row">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Subtotal', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($proposal->total_amount) ); ?></span>
                        </div>
                        <?php if ($deposit_amount > 0): ?>
                        <div class="fs-doc-totals-row">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Deposit Due', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($deposit_amount) ); ?></span>
                        </div>
                        <?php endif; ?>
                        <div class="fs-doc-totals-row grand-total">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Total', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($proposal->total_amount) ); ?></span>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Custom Sections: After Pricing -->
                <?php if (!empty($sections_after)): ?>
                    <?php foreach ($sections_after as $section): ?>
                        <div class="fs-doc-custom-section">
                            <?php if (!empty($section['title'])): ?>
                                <h3><?php echo esc_html($section['title']); ?></h3>
                            <?php endif; ?>
                            <div class="fs-doc-custom-section-content">
                                <?php echo wp_kses_post($section['content']); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
                
                <!-- Notes -->
                <?php if (!empty($proposal->notes)): ?>
                <div class="fs-doc-notes">
                    <h3><?php esc_html_e('Notes', 'freelance-studio'); ?></h3>
                    <p><?php echo nl2br(esc_html($proposal->notes)); ?></p>
                </div>
                <?php endif; ?>
                
                <!-- Signatures Section -->
                <?php if ($proposal->status === 'approved' || !empty($contractor_signature)): ?>
                <div class="fs-doc-signatures">
                    <div class="fs-doc-signatures-grid">
                        <div class="fs-doc-signature-block">
                            <div class="fs-doc-signature-label"><?php esc_html_e('Contractor', 'freelance-studio'); ?></div>
                            <?php if (!empty($contractor_signature)): ?>
                                <div class="fs-doc-signature-image">
                                    <img src="<?php echo esc_attr($contractor_signature); ?>" alt="<?php esc_attr_e('Contractor Signature', 'freelance-studio'); ?>">
                                </div>
                            <?php else: ?>
                                <div class="fs-doc-signature-pending"><?php esc_html_e('Pending', 'freelance-studio'); ?></div>
                            <?php endif; ?>
                            <div class="fs-doc-signature-line"></div>
                            <div class="fs-doc-signature-name"><?php echo esc_html($contractor_signer_name); ?></div>
                            <?php if (!empty($contractor_signer_title)): ?>
                                <div class="fs-doc-signature-title"><?php echo esc_html($contractor_signer_title); ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="fs-doc-signature-block">
                            <div class="fs-doc-signature-label"><?php esc_html_e('Client', 'freelance-studio'); ?></div>
                            <?php if ($proposal->status === 'approved' && !empty($proposal->signature_client)): ?>
                                <div class="fs-doc-signature-image">
                                    <img src="<?php echo esc_attr($proposal->signature_client); ?>" alt="<?php esc_attr_e('Client Signature', 'freelance-studio'); ?>">
                                </div>
                                <div class="fs-doc-signature-line"></div>
                                <div class="fs-doc-signature-name"><?php echo esc_html($proposal->signature_client_name); ?></div>
                                <div class="fs-doc-signature-date"><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($proposal->signature_date)) ); ?></div>
                            <?php else: ?>
                                <div class="fs-doc-signature-pending"><?php esc_html_e('Awaiting signature', 'freelance-studio'); ?></div>
                                <div class="fs-doc-signature-line"></div>
                                <div class="fs-doc-signature-name"><?php echo esc_html($client->name); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Sign Form -->
                <?php if ($can_sign): ?>
                <div class="fs-doc-sign-section">
                    <h3 class="fs-doc-sign-title"><?php esc_html_e('Approve This Proposal', 'freelance-studio'); ?></h3>
                    
                    <form id="fs-signature-form" method="post">
                        <?php wp_nonce_field('fs_sign_proposal', 'fs_sign_nonce'); ?>
                        <input type="hidden" name="action" value="fs_sign_proposal">
                        <input type="hidden" name="proposal_id" value="<?php echo esc_attr($proposal->id); ?>">
                        <input type="hidden" name="signature_data" id="signature-data" value="">
                        
                        <div class="fs-doc-form-group">
                            <label><?php esc_html_e('Your Signature', 'freelance-studio'); ?></label>
                            <div class="fs-doc-signature-pad-container" id="signature-pad-container">
                                <canvas id="signature-pad" class="fs-doc-signature-pad"></canvas>
                                <div class="fs-doc-signature-hint"><?php esc_html_e('Sign here', 'freelance-studio'); ?></div>
                                <button type="button" class="fs-doc-clear-signature" id="clear-signature"><?php esc_html_e('Clear', 'freelance-studio'); ?></button>
                            </div>
                        </div>
                        
                        <div class="fs-doc-form-group">
                            <label for="signer-name"><?php esc_html_e('Your Full Name', 'freelance-studio'); ?></label>
                            <input type="text" id="signer-name" name="signer_name" required value="<?php echo esc_attr($client->name); ?>">
                        </div>
                        
                        <button type="submit" class="fs-doc-sign-btn" id="submit-signature" disabled>
                            <?php esc_html_e('Approve Proposal', 'freelance-studio'); ?>
                        </button>
                    </form>
                    
                    <a href="#" class="fs-doc-revision-link" id="show-revision-form">
                        <?php esc_html_e('Request changes instead', 'freelance-studio'); ?>
                    </a>
                    
                    <div class="fs-doc-revision-form" id="revision-form">
                        <form method="post" id="fs-revision-form">
                            <?php wp_nonce_field('fs_public_proposal', 'fs_revision_nonce'); ?>
                            <input type="hidden" name="action" value="fs_request_revision">
                            <input type="hidden" name="token" value="<?php echo esc_attr($proposal->view_token); ?>">
                            
                            <div class="fs-doc-form-group">
                                <label for="revision-notes"><?php esc_html_e('What changes would you like?', 'freelance-studio'); ?></label>
                                <textarea id="revision-notes" name="revision_notes" rows="4" required placeholder="<?php esc_attr_e('Please describe the changes you\'d like us to make...', 'freelance-studio'); ?>"></textarea>
                            </div>
                            
                            <button type="submit" class="fs-doc-revision-btn">
                                <?php esc_html_e('Submit Revision Request', 'freelance-studio'); ?>
                            </button>
                            <button type="button" class="fs-doc-cancel-revision" id="cancel-revision">
                                <?php esc_html_e('Cancel', 'freelance-studio'); ?>
                            </button>
                        </form>
                    </div>
                </div>
                <?php elseif ($proposal->status === 'revision_requested'): ?>
                <div class="fs-doc-notes">
                    <p style="text-align: center;"><?php esc_html_e('Your revision request is being reviewed. We will send you an updated proposal soon.', 'freelance-studio'); ?></p>
                </div>
                <?php elseif ($is_expired && $proposal->status !== 'approved'): ?>
                <div class="fs-doc-notes">
                    <p style="text-align: center;"><?php esc_html_e('This proposal has expired. Please contact us for a new proposal.', 'freelance-studio'); ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <footer class="fs-doc-footer">
            <?php /* translators: 1. sent by value */ ?>
            <p><?php echo wp_kses_post( sprintf( __('Sent by %s', 'freelance-studio'), esc_html($settings['business_name']))); ?></p>
            <?php if ( function_exists( 'fs_studio_show_powered_badge' ) && fs_studio_show_powered_badge() ): ?>
                <div class="fs-powered-badge">
                    <a href="https://freelancestud.io?ref=proposal" target="_blank" rel="noopener">Powered by Freelance Studio</a>
                </div>
            <?php endif; ?>
        </footer>
    </div>
    
    <?php if ($can_sign): ?>
    <script>
    (function() {
        var canvas = document.getElementById('signature-pad');
        var container = document.getElementById('signature-pad-container');
        var clearBtn = document.getElementById('clear-signature');
        var form = document.getElementById('fs-signature-form');
        var submitBtn = document.getElementById('submit-signature');
        var signatureData = document.getElementById('signature-data');
        
        var ctx = canvas.getContext('2d');
        var isDrawing = false;
        var lastX = 0;
        var lastY = 0;
        var hasSignature = false;
        
        function resizeCanvas() {
            var rect = canvas.getBoundingClientRect();
            canvas.width = rect.width;
            canvas.height = rect.height;
            ctx.strokeStyle = '#000';
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
        }
        
        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);
        
        function getCoords(e) {
            var rect = canvas.getBoundingClientRect();
            if (e.touches) {
                return { x: e.touches[0].clientX - rect.left, y: e.touches[0].clientY - rect.top };
            }
            return { x: e.clientX - rect.left, y: e.clientY - rect.top };
        }
        
        function startDrawing(e) {
            e.preventDefault();
            isDrawing = true;
            var coords = getCoords(e);
            lastX = coords.x;
            lastY = coords.y;
        }
        
        function draw(e) {
            if (!isDrawing) return;
            e.preventDefault();
            var coords = getCoords(e);
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(coords.x, coords.y);
            ctx.stroke();
            lastX = coords.x;
            lastY = coords.y;
            hasSignature = true;
            container.classList.add('has-signature');
            submitBtn.disabled = false;
        }
        
        function stopDrawing() {
            isDrawing = false;
        }
        
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
        canvas.addEventListener('touchstart', startDrawing);
        canvas.addEventListener('touchmove', draw);
        canvas.addEventListener('touchend', stopDrawing);
        
        clearBtn.addEventListener('click', function() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            hasSignature = false;
            container.classList.remove('has-signature');
            submitBtn.disabled = true;
        });
        
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            if (!hasSignature) {
                alert('<?php esc_html_e('Please sign the proposal first.', 'freelance-studio'); ?>');
                return;
            }
            signatureData.value = canvas.toDataURL('image/png');
            submitBtn.disabled = true;
            submitBtn.textContent = '<?php esc_html_e('Processing...', 'freelance-studio'); ?>';
            
            var formData = new FormData(form);
            fetch('<?php echo  esc_url( admin_url('admin-ajax.php') ); ?>', {
                method: 'POST',
                body: formData
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    window.location.href = window.location.pathname + window.location.search + (window.location.search ? '&' : '?') + 'signed=1';
                } else {
                    var errorMsg = (data.data && data.data.message) ? data.data.message : '<?php esc_html_e('An error occurred. Please try again.', 'freelance-studio'); ?>';
                    alert(errorMsg);
                    submitBtn.disabled = false;
                    submitBtn.textContent = '<?php esc_html_e('Approve Proposal', 'freelance-studio'); ?>';
                }
            })
            .catch(function() {
                alert('<?php esc_html_e('An error occurred. Please try again.', 'freelance-studio'); ?>');
                submitBtn.disabled = false;
                submitBtn.textContent = '<?php esc_html_e('Approve Proposal', 'freelance-studio'); ?>';
            });
        });
        
        var showRevisionBtn = document.getElementById('show-revision-form');
        var revisionForm = document.getElementById('revision-form');
        var cancelRevisionBtn = document.getElementById('cancel-revision');
        
        if (showRevisionBtn) {
            showRevisionBtn.addEventListener('click', function(e) {
                e.preventDefault();
                revisionForm.classList.add('active');
                showRevisionBtn.style.display = 'none';
            });
        }
        
        if (cancelRevisionBtn) {
            cancelRevisionBtn.addEventListener('click', function() {
                revisionForm.classList.remove('active');
                showRevisionBtn.style.display = 'block';
            });
        }
        
        // Handle revision form AJAX submission
        var revisionFormEl = document.getElementById('fs-revision-form');
        if (revisionFormEl) {
            revisionFormEl.addEventListener('submit', function(e) {
                e.preventDefault();
                
                var submitBtn = revisionFormEl.querySelector('.fs-doc-revision-btn');
                var originalText = submitBtn.textContent;
                submitBtn.disabled = true;
                submitBtn.textContent = '<?php echo esc_js(__('Submitting...', 'freelance-studio')); ?>';
                
                var formData = new FormData(revisionFormEl);
                formData.append('nonce', formData.get('fs_revision_nonce'));
                
                fetch('<?php echo  esc_url( admin_url('admin-ajax.php') ); ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    if (data.success) {
                        if (data.data && data.data.redirect) {
                            window.location.href = data.data.redirect;
                        } else {
                            window.location.reload();
                        }
                    } else {
                        alert(data.data && data.data.message ? data.data.message : '<?php echo esc_js(__('An error occurred. Please try again.', 'freelance-studio')); ?>');
                        submitBtn.disabled = false;
                        submitBtn.textContent = originalText;
                    }
                })
                .catch(function() {
                    alert('<?php echo esc_js(__('An error occurred. Please try again.', 'freelance-studio')); ?>');
                    submitBtn.disabled = false;
                    submitBtn.textContent = originalText;
                });
            });
        }
    })();
    </script>
    <?php endif; ?>
</body>
</html>
