<?php
/**
 * Timer Widget Partial
 *
 * Reusable timer clock widget that can be included in multiple views.
 * 
 * Expected variables:
 * - $running_timer: The currently running timer entry (or null)
 * - $projects: Array of projects for the dropdown
 * - $timer_context: (optional) Context identifier for the timer ('main' or 'project')
 * - $selected_project_id: (optional) Pre-selected project ID
 *
 * @package Freelance_Studio
 */

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

$timer_context = isset($timer_context) ? $timer_context : 'main';
$selected_project_id = isset($selected_project_id) ? $selected_project_id : 0;

// Get tasks - filter to project if in project context
$timer_task_args = array(
    'status' => array('requested', 'pending', 'in_progress', 'needs_info', 'with_client'),
    'orderby' => 'project_id',
    'order' => 'ASC',
    'exclude_recurring_children' => true,
);
if ($timer_context === 'project' && $selected_project_id) {
    $timer_task_args['project_id'] = $selected_project_id;
}
$timer_tasks = FS_Task::get_all($timer_task_args);

// Group tasks by project for easier selection
$timer_tasks_by_project = array();
foreach ($timer_tasks as $task) {
    $project_key = $task->project_id ? $task->project_id : 0;
    if (!isset($timer_tasks_by_project[$project_key])) {
        $timer_tasks_by_project[$project_key] = array();
    }
    $timer_tasks_by_project[$project_key][] = $task;
}

// Get activity types
$activity_types = FS_Time_Entry::get_activity_types();
?>

<div class="fs-timer-card" data-context="<?php echo esc_attr($timer_context); ?>">
    <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
    <div class="fs-timer-pro-overlay">
        <div class="fs-timer-pro-overlay-content">
            <span class="fs-upgrade-badge">PRO</span>
            <p><?php esc_html_e( 'The live timer is available with Freelance Studio Pro.', 'freelance-studio' ); ?></p>
            <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
            </a>
        </div>
    </div>
    <?php endif; ?>
    <div class="fs-card-header">
        <span class="dashicons dashicons-controls-play"></span>
        <?php esc_html_e('Timer', 'freelance-studio'); ?>
    </div>
    <div class="fs-timer-widget-modern">
        <div class="fs-timer-ring-container">
            <svg class="fs-timer-ring" viewBox="0 0 120 120">
                <defs>
                    <linearGradient id="timerGradient<?php echo esc_attr($timer_context); ?>" x1="0%" y1="0%" x2="100%" y2="100%">
                        <stop offset="0%" style="stop-color:#f2b6f6"/>
                        <stop offset="100%" style="stop-color:#ffa26e"/>
                    </linearGradient>
                </defs>
                <circle class="fs-timer-ring-bg" cx="60" cy="60" r="52"/>
                <?php if ($running_timer): ?>
                <circle class="fs-timer-ring-progress" cx="60" cy="60" r="52" id="timer-progress-ring" style="stroke: url(#timerGradient<?php echo esc_attr($timer_context); ?>);"/>
                <?php endif; ?>
            </svg>
            <div class="fs-timer-time <?php echo !$running_timer ? 'idle' : ''; ?>" id="fs-timer-display">
                <?php 
                if ($running_timer) {
                    if (!empty($running_timer->is_paused)) {
                        // When paused, paused_duration already contains all accumulated time
                        $elapsed = intval($running_timer->paused_duration);
                    } else {
                        // When running, add current segment to accumulated paused_duration
                        $elapsed = (time() - strtotime($running_timer->start_time . ' UTC')) + intval($running_timer->paused_duration);
                    }
                    $parts = explode(':', FS_Time_Entry::format_duration($elapsed));
                    echo wp_kses_post( '<span class="fs-timer-hours">' . $parts[0] . '</span>:<span class="fs-timer-mins">' . $parts[1] . '</span>:<span class="fs-timer-secs">' . $parts[2] . '</span>' );                } else {
                    echo '<span class="fs-timer-hours">00</span>:<span class="fs-timer-mins">00</span>:<span class="fs-timer-secs">00</span>';
                }
                ?>
            </div>
        </div>
        
        <div class="fs-timer-form-fields">
            <!-- Row 1: Project and Task -->
            <div class="fs-timer-form-row">
                <div class="fs-timer-field fs-timer-field-project">
                    <label for="fs-timer-project"><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                    <select id="fs-timer-project" class="fs-timer-select">
                        <option value=""><?php esc_html_e('Select project...', 'freelance-studio'); ?></option>
                        <?php foreach ($projects as $project): ?>
                            <option value="<?php echo esc_attr($project->id); ?>" <?php selected($running_timer ? $running_timer->project_id : $selected_project_id, $project->id); ?>>
                                <?php echo esc_html($project->name); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="fs-timer-field fs-timer-field-task">
                    <label for="fs-timer-task"><?php esc_html_e('Task', 'freelance-studio'); ?> <span class="fs-optional">(<?php esc_html_e('optional', 'freelance-studio'); ?>)</span></label>
                    <select id="fs-timer-task" class="fs-timer-select">
                        <option value=""><?php esc_html_e('Select task...', 'freelance-studio'); ?></option>
                        <?php if (!empty($timer_tasks)): ?>
                            <?php foreach ($timer_tasks_by_project as $project_id => $project_tasks): 
                                $project_name = $project_id ? '' : __('No Project', 'freelance-studio');
                                if ($project_id) {
                                    foreach ($projects as $p) {
                                        if ($p->id == $project_id) {
                                            $project_name = $p->name;
                                            break;
                                        }
                                    }
                                }
                            ?>
                                <optgroup label="<?php echo esc_attr($project_name); ?>" data-project-id="<?php echo esc_attr($project_id); ?>">
                                    <?php foreach ($project_tasks as $task): ?>
                                        <option value="<?php echo esc_attr($task->id); ?>" 
                                                data-project="<?php echo esc_attr($task->project_id); ?>"
                                                data-non-billable="<?php echo !empty($task->is_non_billable) ? '1' : '0'; ?>"
                                                <?php selected($running_timer && isset($running_timer->task_id) ? $running_timer->task_id : 0, $task->id); ?>>
                                            <?php echo esc_html($task->title); ?><?php if (!empty($task->is_non_billable)): ?> (non-billable)<?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
            </div>
            
            <!-- Row 2: Activity and Description -->
            <div class="fs-timer-form-row">
                <div class="fs-timer-field fs-timer-field-activity">
                    <label for="fs-timer-activity"><?php esc_html_e('Activity', 'freelance-studio'); ?></label>
                    <select id="fs-timer-activity" class="fs-timer-select">
                        <?php 
                        $default_activity = get_option('fs_default_activity', 'development');
                        foreach ($activity_types as $key => $label): ?>
                            <option value="<?php echo esc_attr($key); ?>" <?php selected($running_timer && isset($running_timer->activity) ? $running_timer->activity : $default_activity, $key); ?>>
                                <?php echo esc_html($label); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="fs-timer-field fs-timer-field-description">
                    <label for="fs-timer-description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                    <input type="text" id="fs-timer-description" class="fs-timer-input" 
                           placeholder="<?php esc_attr_e('What did you work on?', 'freelance-studio'); ?>" 
                           value="<?php echo $running_timer ? esc_attr($running_timer->description) : ''; ?>">
                </div>
            </div>
        </div>
        
        <div class="fs-timer-controls-modern">
            <?php if ($running_timer): ?>
                <?php if (!empty($running_timer->is_paused)): ?>
                <button type="button" class="fs-timer-btn-circle" id="fs-resume-timer" title="<?php esc_attr_e('Resume', 'freelance-studio'); ?>">
                    <span class="dashicons dashicons-controls-play"></span>
                </button>
                <?php else: ?>
                <button type="button" class="fs-timer-btn-circle" id="fs-pause-timer" title="<?php esc_attr_e('Pause', 'freelance-studio'); ?>">
                    <span class="dashicons dashicons-controls-pause"></span>
                </button>
                <?php endif; ?>
            <button type="button" class="fs-timer-btn-stop" id="fs-timer-toggle">
                <svg class="fs-icon-stop" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><rect x="9" y="9" width="6" height="6" rx="1"/></svg>
                <?php esc_html_e('Stop', 'freelance-studio'); ?>
            </button>
            <button type="button" class="fs-timer-btn-circle" id="fs-discard-timer" title="<?php esc_attr_e('Discard', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-trash"></span>
            </button>
            <?php 
            $popout_task_name = '';
            if ($running_timer->task_id) {
                $popout_task = FS_Task::get($running_timer->task_id);
                if ($popout_task) $popout_task_name = $popout_task->title;
            }
            ?>
            <button type="button" class="fs-timer-popout-btn" id="fs-popout-timer" 
                    data-task-id="<?php echo esc_attr($running_timer->task_id ?: 0); ?>"
                    data-project-id="<?php echo esc_attr($running_timer->project_id ?: 0); ?>"
                    data-task-name="<?php echo esc_attr($popout_task_name); ?>"
                    title="<?php esc_attr_e('Pop out timer', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-external"></span>
            </button>
            <?php else: ?>
            <button type="button" class="fs-timer-btn-start" id="fs-timer-toggle">
                <span class="dashicons dashicons-controls-play"></span>
                <?php esc_html_e('Start', 'freelance-studio'); ?>
            </button>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if ($running_timer): ?>
        <input type="hidden" id="fs-running-timer-id" value="<?php echo esc_attr($running_timer->id); ?>">
        <input type="hidden" id="fs-running-timer-start" value="<?php echo esc_attr(strtotime($running_timer->start_time . ' UTC')); ?>">
        <input type="hidden" id="fs-timer-paused" value="<?php echo !empty($running_timer->is_paused) ? '1' : '0'; ?>">
        <input type="hidden" id="fs-timer-paused-duration" value="<?php echo intval($running_timer->paused_duration); ?>">
    <?php endif; ?>
</div>

<script>
jQuery(document).ready(function($) {
    // Filter task dropdown when project changes in timer widget
    var $timerTask = $('#fs-timer-task');
    if ($timerTask.length) {
        var $allTaskOptions = $timerTask.children().clone(true);
        
        $('#fs-timer-project').on('change.taskFilter', function() {
            var projectId = $(this).val();
            var currentVal = $timerTask.val();
            
            $timerTask.empty().append($allTaskOptions.clone(true));
            
            if (projectId) {
                $timerTask.find('optgroup').each(function() {
                    if (String($(this).data('project-id')) !== String(projectId)) {
                        $(this).remove();
                    }
                });
            }
            
            if ($timerTask.find('option[value="' + currentVal + '"]').length) {
                $timerTask.val(currentVal);
            } else {
                $timerTask.val('');
            }
        });
        
        // Apply filter on load if project is pre-selected
        if ($('#fs-timer-project').val()) {
            $('#fs-timer-project').trigger('change.taskFilter');
        }
    }
    
    // Pop-out timer button
    $('#fs-popout-timer').on('click', function() {
        var taskId = $(this).data('task-id') || 0;
        var projectId = $(this).data('project-id') || '';
        var taskName = $(this).data('task-name') || '';
        
        var url = (typeof ajaxurl !== 'undefined' ? ajaxurl : '').replace('admin-ajax.php', 'admin.php') + 
            '?page=fs-time-tracking&action=popup_timer' +
            '&task_id=' + taskId +
            '&project_id=' + projectId +
            '&task_name=' + encodeURIComponent(taskName);
        
        var w = 340, h = 440;
        var left = (screen.width - w) / 2;
        var top = (screen.height - h) / 2;
        
        window.open(url, 'fs_popup_timer', 
            'width=' + w + ',height=' + h + ',left=' + left + ',top=' + top + 
            ',menubar=no,toolbar=no,location=no,status=no,resizable=yes');
    });
});
</script>
