<?php
/**
 * Time Budget Widget Partial
 * Reusable widget for displaying retainer status OR capped hourly hours on project views
 *
 * @package Freelance_Studio
 * @since 3.9.0
 * @updated 7.9.0 - Added capped hourly support
 * 
 * Expected variables:
 * For retainer mode:
 * - $retainer_service (array) - The retainer service data from project services
 * For capped hourly mode:
 * - $capped_service (array) - The capped hourly service data
 * Common:
 * - $project_id (int) - The project ID
 * - $tracked_hours (float) - Total hours tracked (optional, will calculate if not provided)
 */

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

// Determine mode: retainer or capped hourly
$widget_mode = 'retainer';
$hours_included = 0;
$monthly_amount = 0;
$allow_rollover = false;
$overage_rate = 0;
$widget_title = __('Retainer Status', 'freelance-studio');
$hours_label = __('Hours/Month', 'freelance-studio');
$progress_label_suffix = __('of monthly hours used', 'freelance-studio');

if (!empty($capped_service) && empty($retainer_service)) {
    $widget_mode = 'capped';
    $hours_included = floatval($capped_service['hour_cap'] ?? 0);
    $hourly_rate = floatval($capped_service['rate'] ?? 0);
    $overage_rate = floatval($capped_service['hour_cap_overage_rate'] ?? 0);
    if ($overage_rate <= 0) {
        $overage_rate = $hourly_rate; // Default to standard rate
    }
    $widget_title = __('Hours Budget', 'freelance-studio');
    $hours_label = __('Hours Budgeted', 'freelance-studio');
    $progress_label_suffix = __('of budgeted hours used', 'freelance-studio');
    $monthly_amount = $hours_included * $hourly_rate;
} elseif (!empty($retainer_service)) {
    $monthly_amount = floatval($retainer_service['retainer_amount'] ?? 0);
    $hours_included = floatval($retainer_service['retainer_hours'] ?? 0);
    $allow_rollover = !empty($retainer_service['retainer_rollover']);
    $overage_rate = floatval($retainer_service['retainer_overage_rate'] ?? 0);
} else {
    return; // No valid data
}

if ($hours_included <= 0) {
    return;
}

// Calculate tracked hours if not provided
if (!isset($tracked_hours)) {
    if ($widget_mode === 'retainer') {
        // Scope to current period dates only
        $current_period = FS_Retainer_Period::get_current_period($project_id);
        if ($current_period) {
            $time_summary = FS_Time_Entry::get_summary(array(
                'project_id' => $project_id,
                'date_from'  => $current_period->period_start,
                'date_to'    => $current_period->period_end,
            ));
        } else {
            $time_summary = FS_Time_Entry::get_summary(array('project_id' => $project_id));
        }
    } else {
        // Capped hourly — all time tracked against the project
        $time_summary = FS_Time_Entry::get_summary(array('project_id' => $project_id));
    }
    $tracked_hours = floatval(($time_summary->total_seconds ?? 0) / 3600);
}

// Calculate usage
$hours_remaining = $hours_included - $tracked_hours;
$usage_percent = $hours_included > 0 ? min(100, ($tracked_hours / $hours_included) * 100) : 0;
$progress_class = $usage_percent >= 100 ? 'danger' : ($usage_percent >= 75 ? 'warning' : '');

// Calculate overage
$overage_hours = max(0, $tracked_hours - $hours_included);
$overage_amount = $overage_hours * $overage_rate;
?>

<div class="fs-retainer-summary fs-retainer-widget">
    <h4>
        <span class="dashicons dashicons-clock"></span>
        <?php echo esc_html($widget_title); ?>
        <?php if ($allow_rollover): ?>
            <span class="fs-retainer-badge"><?php esc_html_e('Rollover Enabled', 'freelance-studio'); ?></span>
        <?php endif; ?>
        <?php if ($widget_mode === 'capped' && $overage_hours > 0): ?>
            <span class="fs-retainer-badge fs-badge-warning"><?php esc_html_e('Over Cap', 'freelance-studio'); ?></span>
        <?php endif; ?>
        <?php if ($widget_mode === 'retainer'): ?>
            <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-retainer-reset-btn" 
                    data-project-id="<?php echo intval($project_id); ?>"
                    title="<?php esc_attr_e('Manually start a new period now', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-update"></span> <?php esc_html_e('New Period', 'freelance-studio'); ?>
            </button>
        <?php endif; ?>
    </h4>
    
    <?php
    // Show current period dates for retainer mode
    if ($widget_mode === 'retainer') {
        // $current_period may already be set from the tracked_hours calculation above
        if (!isset($current_period)) {
            $current_period = FS_Retainer_Period::get_current_period($project_id);
        }
        if ($current_period) {
            echo '<div class="fs-retainer-period-label">';
            echo sprintf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                /* translators: 1. period start date, 2. period end date */
                __('Current period: %1$s – %2$s', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                date_i18n(get_option('date_format'), strtotime($current_period->period_start)), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                date_i18n(get_option('date_format'), strtotime($current_period->period_end)) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            );
            echo '</div>';
        } else {
            echo wp_kses_post( '<div class="fs-retainer-period-label fs-text-warning">' . __('No active period — visit the project or wait for the daily sync.', 'freelance-studio') . '</div>' );        }
    }
    ?>
    
    <div class="fs-retainer-stats">
        <div class="fs-retainer-stat">
            <span class="fs-retainer-stat-label"><?php echo esc_html($hours_label); ?></span>
            <span class="fs-retainer-stat-value"><?php echo number_format($hours_included, 1); ?></span>
        </div>
        <div class="fs-retainer-stat">
            <span class="fs-retainer-stat-label"><?php esc_html_e('Used This Period', 'freelance-studio'); ?></span>
            <span class="fs-retainer-stat-value"><?php echo number_format($tracked_hours, 1); ?></span>
        </div>
        <div class="fs-retainer-stat">
            <span class="fs-retainer-stat-label"><?php esc_html_e('Remaining', 'freelance-studio'); ?></span>
            <span class="fs-retainer-stat-value <?php echo $hours_remaining < 0 ? 'fs-text-danger' : 'fs-text-success'; ?>">
                <?php echo number_format($hours_remaining, 1); ?>
            </span>
        </div>
        <?php if ($overage_hours > 0 && $overage_rate > 0): ?>
        <div class="fs-retainer-stat">
            <span class="fs-retainer-stat-label"><?php esc_html_e('Overage', 'freelance-studio'); ?></span>
            <span class="fs-retainer-stat-value fs-text-warning">
                <?php echo number_format($overage_hours, 1); ?> hrs
            </span>
        </div>
        <?php endif; ?>
    </div>
    
    <div class="fs-retainer-progress">
        <div class="fs-retainer-progress-bar">
            <div class="fs-retainer-progress-fill <?php echo  esc_attr( $progress_class ); ?>" style="width: <?php echo  esc_attr( min(100, $usage_percent) ); ?>%;"></div>
        </div>
    </div>
    <div class="fs-retainer-progress-label">
        <?php echo  esc_html( round($usage_percent) ); ?>% <?php echo esc_html($progress_label_suffix); ?>
    </div>
    
    <?php if ($widget_mode === 'retainer' && $monthly_amount > 0): ?>
    <div class="fs-retainer-billing-summary">
        <div class="fs-retainer-billing-item">
            <span><?php esc_html_e('Monthly Retainer:', 'freelance-studio'); ?></span>
            <span><?php echo  esc_html( FS_View_Context::format_currency($monthly_amount) ); ?></span>
        </div>
        <?php if ($overage_amount > 0): ?>
        <div class="fs-retainer-billing-item fs-text-warning">
            <?php /* translators: 1. overage hours, 2. hourly rate */ ?>
            <span><?php echo wp_kses_post( sprintf( __('Overage (%1$s hrs @ %2$s/hr):', 'freelance-studio'), number_format($overage_hours, 1), FS_View_Context::format_currency($overage_rate))); ?></span>
            <span><?php echo  esc_html( FS_View_Context::format_currency($overage_amount) ); ?></span>
        </div>
        <div class="fs-retainer-billing-item fs-retainer-billing-total">
            <span><?php esc_html_e('Total This Period:', 'freelance-studio'); ?></span>
            <span><?php echo  esc_html( FS_View_Context::format_currency($monthly_amount + $overage_amount) ); ?></span>
        </div>
        <?php endif; ?>
    </div>
    <?php elseif ($widget_mode === 'capped'): ?>
    <div class="fs-retainer-billing-summary">
        <div class="fs-retainer-billing-item">
            <span><?php esc_html_e('Budget:', 'freelance-studio'); ?></span>
            <span><?php echo  esc_html( FS_View_Context::format_currency($monthly_amount) ); ?> (<?php echo number_format($hours_included, 1); ?> hrs @ <?php echo  esc_html( FS_View_Context::format_currency($hourly_rate) ); ?>/hr)</span>
        </div>
        <?php if ($overage_amount > 0): ?>
        <div class="fs-retainer-billing-item fs-text-warning">
            <?php /* translators: 1. overage hours, 2. hourly rate */ ?>
            <span><?php echo wp_kses_post( sprintf( __('Overage (%1$s hrs @ %2$s/hr):', 'freelance-studio'), number_format($overage_hours, 1), FS_View_Context::format_currency($overage_rate))); ?></span>
            <span><?php echo  esc_html( FS_View_Context::format_currency($overage_amount) ); ?></span>
        </div>
        <div class="fs-retainer-billing-item fs-retainer-billing-total">
            <span><?php esc_html_e('Total:', 'freelance-studio'); ?></span>
            <span><?php echo  esc_html( FS_View_Context::format_currency($monthly_amount + $overage_amount) ); ?></span>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<?php if ($widget_mode === 'retainer'): ?>
<script>
(function() {
    var btn = document.querySelector('.fs-retainer-reset-btn[data-project-id="<?php echo intval($project_id); ?>"]');
    if (!btn) { return; }
    // Remove any existing listeners by cloning
    var fresh = btn.cloneNode(true);
    btn.parentNode.replaceChild(fresh, btn);
    fresh.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        if (!confirm('<?php echo esc_js(__('Start a new retainer period now? The current period will be closed today and a new one will begin tomorrow.', 'freelance-studio')); ?>')) {
            return;
        }
        fresh.disabled = true;
        fresh.textContent = '...';
        var nonce = (typeof fs_ajax !== 'undefined') ? fs_ajax.nonce : '';
        var xhr = new XMLHttpRequest();
        xhr.open('POST', ajaxurl, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            try {
                var r = JSON.parse(xhr.responseText);
                if (r.success) {
                    setTimeout(function() { location.reload(); }, 800);
                } else {
                    alert((r.data && r.data.message) ? r.data.message : 'Failed to reset period.');
                    fresh.disabled = false;
                    fresh.textContent = 'New Period';
                }
            } catch(ex) {
                alert('Unexpected response. Please try again.');
                fresh.disabled = false;
                fresh.textContent = 'New Period';
            }
        };
        xhr.onerror = function() {
            alert('Request failed. Please try again.');
            fresh.disabled = false;
            fresh.textContent = 'New Period';
        };
        xhr.send('action=fs_reset_retainer_period&nonce=' + encodeURIComponent(nonce) + '&project_id=<?php echo intval($project_id); ?>');
    });
})();
</script>
<?php endif; ?>
