<?php
/**
 * Quick Add Time Entry Partial
 *
 * Reusable manual time entry widget that can be included in multiple views.
 * 
 * Expected variables:
 * - $projects: Array of projects for the dropdown
 * - $activity_types: Array of activity type key => label pairs
 * - $quickadd_context: (optional) Context identifier ('main' or 'project')
 * - $quickadd_project_id: (optional) Pre-selected project ID
 * - $show_project_field: (optional) Whether to show project dropdown (default: true)
 *
 * @package Freelance_Studio
 */

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

$quickadd_context = isset($quickadd_context) ? $quickadd_context : 'main';
$quickadd_project_id = isset($quickadd_project_id) ? $quickadd_project_id : (isset($quickadd_project_id) ? $quickadd_project_id : 0);
$show_project_field = isset($show_project_field) ? $show_project_field : true;
$default_rate = get_option('fs_default_hourly_rate', 75);

// Get hourly rate for pre-selected project from its hourly services
if ($quickadd_project_id) {
    $proj_to_check = null;
    
    // First check if current $project variable exists with the right ID
    if (isset($project) && $project->id == $quickadd_project_id) {
        $proj_to_check = $project;
    } elseif (!empty($projects)) {
        // Search in projects list
        foreach ($projects as $proj) {
            if ($proj->id == $quickadd_project_id) {
                $proj_to_check = $proj;
                break;
            }
        }
    }
    
    // Fallback: fetch the project directly
    if (!$proj_to_check) {
        $proj_to_check = FS_Project::get($quickadd_project_id);
    }
    
    // Get rate from project's hourly services
    if ($proj_to_check) {
        $proj_services = $proj_to_check->services;
        if (is_string($proj_services)) {
            $proj_services = json_decode($proj_services, true);
        }
        if (!empty($proj_services) && is_array($proj_services)) {
            foreach ($proj_services as $svc) {
                if (isset($svc['pricing_type']) && $svc['pricing_type'] === 'hourly' && !empty($svc['rate'])) {
                    $default_rate = floatval($svc['rate']);
                    break;
                }
            }
        }
    }
}

// Helper function to get hourly rate from project services
if (!function_exists('fs_get_project_hourly_rate')) {
    function fs_get_project_hourly_rate($proj) {
    $rate = get_option('fs_default_hourly_rate', 75);
    $services = $proj->services;
    if (is_string($services)) {
        $services = json_decode($services, true);
    }
    if (!empty($services) && is_array($services)) {
        foreach ($services as $svc) {
            if (isset($svc['pricing_type']) && $svc['pricing_type'] === 'hourly' && !empty($svc['rate'])) {
                return floatval($svc['rate']);
            }
        }
    }
    return $rate;
}
}
// Get tasks for the task dropdown
// When in project context and timer widget already loaded tasks, reuse them
if ($quickadd_context === 'project' && isset($timer_tasks) && !empty($timer_tasks)) {
    $all_tasks = $timer_tasks;
} else {
    $quickadd_task_args = array(
        'status' => array('requested', 'pending', 'in_progress', 'needs_info', 'with_client'),
        'orderby' => 'project_id',
        'order' => 'ASC',
        'exclude_recurring_children' => true,
    );
    if ($quickadd_context === 'project' && $quickadd_project_id) {
        $quickadd_task_args['project_id'] = $quickadd_project_id;
    }
    $all_tasks = FS_Task::get_all($quickadd_task_args);
    
    // Fallback: if no tasks found for project, try without status filter (excluding completed/cancelled/archived)
    if (empty($all_tasks) && $quickadd_context === 'project' && $quickadd_project_id) {
        $all_tasks = FS_Task::get_all(array(
            'project_id' => $quickadd_project_id,
            'exclude_archived' => true,
            'exclude_recurring_children' => true,
        ));
        // Remove completed/cancelled tasks
        $all_tasks = array_filter($all_tasks, function($t) {
            return !in_array($t->status, array('completed', 'cancelled', 'archived'));
        });
    }
}

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

<div class="fs-quickadd-card" data-context="<?php echo esc_attr($quickadd_context); ?>">
    <div class="fs-card-header">
        <span class="dashicons dashicons-plus-alt2"></span>
        <?php esc_html_e('Quick Add', 'freelance-studio'); ?>
    </div>
    <form id="fs-quickadd-form" class="fs-quickadd-form">
        <div class="fs-quickadd-row">
            <?php if ($show_project_field): ?>
            <div class="fs-quickadd-field fs-quickadd-field-project">
                <label><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                <select name="project_id" id="quickadd-project">
                    <option value=""><?php esc_html_e('Select project...', 'freelance-studio'); ?></option>
                    <?php foreach ($projects as $proj_item): ?>
                        <option value="<?php echo esc_attr($proj_item->id); ?>" 
                                data-rate="<?php echo esc_attr(fs_get_project_hourly_rate($proj_item)); ?>"
                                <?php selected($quickadd_project_id, $proj_item->id); ?>>
                            <?php echo esc_html($proj_item->name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php else: ?>
            <input type="hidden" name="project_id" id="quickadd-project" value="<?php echo esc_attr($quickadd_project_id); ?>">
            <?php endif; ?>
            <div class="fs-quickadd-field fs-quickadd-field-task">
                <label><?php esc_html_e('Task', 'freelance-studio'); ?> <span class="description">(<?php esc_html_e('optional', 'freelance-studio'); ?>)</span></label>
                <select name="task_id" id="quickadd-task">
                    <option value=""><?php esc_html_e('Select task...', 'freelance-studio'); ?></option>
                    <?php if (!empty($all_tasks)): ?>
                        <?php if ($quickadd_context === 'project'): ?>
                            <?php // In project context, just list all tasks directly (already filtered server-side) ?>
                            <?php foreach ($all_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 echo esc_html($task->title); ?><?php if (!empty($task->is_non_billable)): ?> (non-billable)<?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <?php // On main page, group by project with optgroups
                            foreach ($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 echo esc_html($task->title); ?><?php if (!empty($task->is_non_billable)): ?> (non-billable)<?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    <?php endif; ?>
                </select>
            </div>
        </div>
        <div class="fs-quickadd-row">
            <div class="fs-quickadd-field fs-quickadd-field-activity">
                <label><?php esc_html_e('Activity', 'freelance-studio'); ?></label>
                <select name="activity" id="quickadd-activity">
                    <?php 
                    $default_activity = get_option('fs_default_activity', 'development');
                    foreach ($activity_types as $key => $label): ?>
                        <option value="<?php echo esc_attr($key); ?>" <?php selected($default_activity, $key); ?>><?php echo esc_html($label); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fs-quickadd-field fs-quickadd-field-desc">
                <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                <input type="text" name="description" id="quickadd-description" placeholder="<?php esc_attr_e('What did you work on?', 'freelance-studio'); ?>">
            </div>
        </div>
        <div class="fs-quickadd-row">
            <div class="fs-quickadd-field fs-quickadd-field-date">
                <label><?php esc_html_e('Date', 'freelance-studio'); ?></label>
                <?php
                // Use the user's configured timezone for default date
                $qa_tz_string = get_option('fs_user_timezone', wp_timezone_string());
                $qa_now = new DateTime('now', new DateTimeZone($qa_tz_string));
                ?>
                <input type="date" name="start_date" id="quickadd-date" value="<?php echo  esc_attr( $qa_now->format('Y-m-d') ); ?>">
            </div>
            <div class="fs-quickadd-field fs-quickadd-field-duration">
                <label><?php esc_html_e('Duration', 'freelance-studio'); ?></label>
                <div class="fs-quickadd-duration">
                    <input type="number" name="duration_hours" id="quickadd-hours" min="0" value="0" placeholder="0">
                    <span>h</span>
                    <input type="number" name="duration_minutes" id="quickadd-minutes" min="0" max="59" value="0" placeholder="0">
                    <span>m</span>
                </div>
            </div>
            <div class="fs-quickadd-field fs-quickadd-field-billable">
                <label>&nbsp;</label>
                <label class="fs-quickadd-checkbox">
                    <input type="checkbox" name="billable" id="quickadd-billable" value="1" checked>
                    <?php esc_html_e('Billable', 'freelance-studio'); ?>
                </label>
            </div>
        </div>
        <div class="fs-quickadd-actions">
            <button type="submit" class="fs-btn fs-btn-secondary">
                <span class="dashicons dashicons-plus-alt2"></span>
                <?php esc_html_e('Add Entry', 'freelance-studio'); ?>
            </button>
        </div>
        <input type="hidden" name="hourly_rate" id="quickadd-rate" value="<?php echo esc_attr($default_rate); ?>">
    </form>
</div>

<?php if ($show_project_field): ?>
<script>
jQuery(document).ready(function($) {
    var $qaProject = $('#quickadd-project');
    var $qaTask = $('#quickadd-task');
    if ($qaProject.length && $qaTask.length) {
        var $allQaTaskOptions = $qaTask.children().clone(true);
        
        $qaProject.on('change.qaTaskFilter', function() {
            var projectId = $(this).val();
            var currentVal = $qaTask.val();
            
            $qaTask.empty().append($allQaTaskOptions.clone(true));
            
            if (projectId) {
                $qaTask.find('optgroup').each(function() {
                    if (String($(this).data('project-id')) !== String(projectId) && 
                        String($(this).attr('label')) !== '<?php echo esc_js(__('Project Tasks', 'freelance-studio')); ?>') {
                        $(this).remove();
                    }
                });
                // Also remove individual options not matching (for non-grouped)
                $qaTask.find('option[data-project]').each(function() {
                    if (String($(this).data('project')) !== String(projectId)) {
                        $(this).remove();
                    }
                });
            }
            
            if ($qaTask.find('option[value="' + currentVal + '"]').length) {
                $qaTask.val(currentVal);
            } else {
                $qaTask.val('');
            }
        });
        
        // Apply filter on load if project is pre-selected
        if ($qaProject.val()) {
            $qaProject.trigger('change.qaTaskFilter');
        }
    }
    
});
</script>
<?php endif; ?>

<script>
jQuery(document).ready(function($) {
    // Auto-manage billable checkbox when a non-billable task is selected (quickadd)
    $('#quickadd-task').on('change.nonbillable', function() {
        var $selected = $(this).find(':selected');
        var isNonBillable = parseInt($selected.data('non-billable')) === 1;
        var $billable = $('#quickadd-billable');
        
        if (isNonBillable) {
            $billable.prop('checked', false).prop('disabled', true);
            $billable.closest('label').attr('title', '<?php echo esc_js(__('This task is marked as non-billable', 'freelance-studio')); ?>');
        } else {
            $billable.prop('disabled', false).prop('checked', true);
            $billable.closest('label').removeAttr('title');
        }
    });
});
</script>
