<?php
/**
 * Quarterly Tax Estimates Section
 * 
 * @package Freelance_Studio
 */

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

$current_year = $selected_year;
$user_id = get_current_user_id();
$quarterly_records = FS_Quarterly_Tax::get_year_records($user_id, $current_year);
$state = get_option('fs_tax_state', '');
$state_name = $state ? FS_Tax_Rates::get_state_names()[$state] : __('Not Set', 'freelance-studio');
$state_rate = FS_Tax_Rates::get_state_rate($state);
$federal_bracket = floatval(get_option('fs_federal_tax_bracket', 22));
$se_tax_rate = 15.3;
?>

<!-- Quarterly Tax Estimates Section -->
<div class="fs-report-section fs-quarterly-tax-section">
    <h2><?php esc_html_e('Quarterly Tax Estimates', 'freelance-studio'); ?></h2>
    <?php /* translators: 1. date/time */ ?>
    <p class="fs-section-description"><?php echo wp_kses_post( sprintf( __('Estimated taxes on freelance income for %s', 'freelance-studio'), $current_year)); ?></p>
    
    <?php if (!$state): ?>
        <div class="fs-tax-warning">
            <span class="dashicons dashicons-warning"></span>
            <div>
                <p><strong><?php esc_html_e('State Not Configured', 'freelance-studio'); ?></strong></p>
                <?php /* translators: 1. date/time */ ?>
                <p><?php echo wp_kses_post( sprintf( __('Please set your state in <a href="%s">Settings</a> to see accurate tax estimates.', 'freelance-studio'), admin_url('admin.php?page=fs-settings'))); ?></p>
            </div>
        </div>
    <?php endif; ?>
    
    <div class="fs-tax-info">
        <p>
            <strong><?php esc_html_e('Tax Rates:', 'freelance-studio'); ?></strong> 
            <?php esc_html_e('Self-Employment:', 'freelance-studio'); ?> <?php echo  esc_html( $se_tax_rate ); ?>% | 
            <?php esc_html_e('Federal Bracket:', 'freelance-studio'); ?> <?php echo  esc_html( $federal_bracket ); ?>% | 
            <?php esc_html_e('State', 'freelance-studio'); ?> (<?php echo esc_html($state_name); ?>): <?php echo  esc_html( $state_rate ); ?>%
        </p>
        <p class="fs-tax-info-note">
            <span class="dashicons dashicons-info"></span>
            <?php esc_html_e('SE Tax = Self-Employment Tax (Social Security 12.4% + Medicare 2.9%). 50% of SE Tax is deductible from taxable income before calculating federal/state tax.', 'freelance-studio'); ?>
        </p>
    </div>
    
    <div class="fs-quarterly-tax-table-container">
        <table class="widefat fs-table fs-quarterly-tax-table">
            <thead>
                <tr>
                    <th><?php esc_html_e('QTR', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Period', 'freelance-studio'); ?></th>
                    <th class="text-right"><?php esc_html_e('Income', 'freelance-studio'); ?></th>
                    <th class="text-right">
                        <?php esc_html_e('SE Tax + Federal', 'freelance-studio'); ?>
                        <small>(15.3% + <?php echo  esc_html( $federal_bracket ); ?>%)</small>
                    </th>
                    <th class="text-right">
                        <?php esc_html_e('State Tax', 'freelance-studio'); ?>
                        <small>(<?php echo  esc_html( $state_rate ); ?>%)</small>
                    </th>
                    <th class="text-right"><?php esc_html_e('Total Estimated', 'freelance-studio'); ?></th>
                    <th class="text-right"><?php esc_html_e('Actual Payment', 'freelance-studio'); ?></th>
                    <th class="text-right"><?php esc_html_e('Variance', 'freelance-studio'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php
                $quarter_periods = array(
                    1 => __('Jan - Mar', 'freelance-studio'),
                    2 => __('Apr - Jun', 'freelance-studio'),
                    3 => __('Jul - Sep', 'freelance-studio'),
                    4 => __('Oct - Dec', 'freelance-studio')
                );
                
                $total_income = 0;
                $total_federal = 0;
                $total_state = 0;
                $total_estimated = 0;
                $total_actual = 0;
                
                foreach ($quarterly_records as $quarter => $record):
                    $total_income += $record->income;
                    $total_federal += $record->estimated_federal;
                    $total_state += $record->estimated_state;
                    $total_estimated += $record->estimated_total;
                    $total_actual += floatval($record->actual_payment);
                    
                    $variance = floatval($record->actual_payment) - $record->estimated_total;
                    $variance_class = $variance >= 0 ? 'positive' : 'negative';
                    $row_class = floatval($record->actual_payment) > 0 ? 'paid-row' : '';
                ?>
                    <tr class="<?php echo  esc_attr( $row_class ); ?>">
                        <td><strong>Q<?php echo  esc_html( $quarter ); ?></strong></td>
                        <td><?php echo  esc_html( $quarter_periods[$quarter] ); ?></td>
                        <td class="text-right">$<?php echo number_format($record->income, 2); ?></td>
                        <td class="text-right">$<?php echo number_format($record->estimated_federal, 2); ?></td>
                        <td class="text-right">$<?php echo number_format($record->estimated_state, 2); ?></td>
                        <td class="text-right"><strong>$<?php echo number_format($record->estimated_total, 2); ?></strong></td>
                        <td class="text-right">
                            <input type="number" 
                                   class="fs-actual-payment-input" 
                                   data-record-id="<?php echo  intval( $record->id ); ?>" 
                                   value="<?php echo floatval($record->actual_payment) > 0 ? number_format(floatval($record->actual_payment), 2, '.', '') : ''; ?>"
                                   placeholder="0.00"
                                   step="0.01"
                                   min="0">
                        </td>
                        <td class="text-right fs-variance <?php echo  esc_attr( $variance_class ); ?>">
                            <?php if (floatval($record->actual_payment) > 0): ?>
                                <?php echo $variance >= 0 ? '+' : '-'; ?>$<?php echo number_format(abs($variance), 2); ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr class="fs-totals-row">
                    <td colspan="2"><strong><?php esc_html_e('TOTAL', 'freelance-studio'); ?></strong></td>
                    <td class="text-right"><strong>$<?php echo number_format($total_income, 2); ?></strong></td>
                    <td class="text-right"><strong>$<?php echo number_format($total_federal, 2); ?></strong></td>
                    <td class="text-right"><strong>$<?php echo number_format($total_state, 2); ?></strong></td>
                    <td class="text-right"><strong>$<?php echo number_format($total_estimated, 2); ?></strong></td>
                    <td class="text-right"><strong>$<?php echo number_format($total_actual, 2); ?></strong></td>
                    <td class="text-right">
                        <?php
                        $total_variance = $total_actual - $total_estimated;
                        $total_variance_class = $total_variance >= 0 ? 'positive' : 'negative';
                        ?>
                        <span class="fs-variance <?php echo  intval( $total_variance_class ); ?>">
                            <?php if ($total_actual > 0): ?>
                                <strong><?php echo $total_variance >= 0 ? '+' : '-'; ?>$<?php echo number_format(abs($total_variance), 2); ?></strong>
                            <?php endif; ?>
                        </span>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
    
    <div class="fs-tax-notes">
        <p><strong><?php esc_html_e('Note:', 'freelance-studio'); ?></strong> <?php esc_html_e('These estimates are for freelance/1099 income only. Consult with a tax professional for accurate tax planning.', 'freelance-studio'); ?></p>
        <p><strong><?php esc_html_e('Quarterly Due Dates:', 'freelance-studio'); ?></strong> <?php esc_html_e('Q1: April 15 | Q2: June 15 | Q3: September 15 | Q4: January 15 (next year)', 'freelance-studio'); ?></p>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Handle actual payment input changes
    $('.fs-actual-payment-input').on('blur', function() {
        var $input = $(this);
        var recordId = $input.data('record-id');
        var amount = parseFloat($input.val()) || 0;
        
        // Show loading state
        $input.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_quarterly_payment',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                record_id: recordId,
                amount: amount
            },
            success: function(response) {
                if (response.success) {
                    // Show success feedback
                    $input.addClass('success');
                    setTimeout(function() {
                        $input.removeClass('success');
                        // Reload page to update variance calculations
                        location.reload();
                    }, 500);
                } else {
                    alert('<?php esc_html_e('Error:', 'freelance-studio'); ?> ' + (response.data.message || '<?php esc_html_e('Failed to update payment', 'freelance-studio'); ?>'));
                    $input.addClass('error');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error: Failed to update payment', 'freelance-studio'); ?>');
                $input.addClass('error');
            },
            complete: function() {
                $input.prop('disabled', false);
            }
        });
    });
    
    // Format currency inputs on focus/blur
    $('.fs-actual-payment-input').on('focus', function() {
        var $input = $(this);
        var value = $input.val().replace(/,/g, '');
        if (value) {
            $input.val(value);
        }
    });
    
    $('.fs-actual-payment-input').on('blur', function() {
        var $input = $(this);
        var value = parseFloat($input.val());
        if (!isNaN(value) && value > 0) {
            $input.val(value.toFixed(2));
        }
    });
});
</script>
