<?php
/**
 * Time Entry Modal Form Partial
 *
 * Unified time entry form for use in modals (week view, dashboard, etc.)
 * Contains all required fields for a time entry.
 * 
 * Expected variables:
 * - $projects: Array of projects for the dropdown (optional - will load if not set)
 * - $activity_types: Array of activity type key => label pairs (optional - will load if not set)
 * - $modal_id: (optional) Modal ID prefix for unique form IDs (default: 'fs-time-entry')
 *
 * @package Freelance_Studio
 */

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

$modal_id = isset($modal_id) ? $modal_id : 'fs-time-entry';
$default_rate = get_option('fs_default_hourly_rate', 75);

// Ensure projects are available - load active only if not passed
if (!isset($projects) || empty($projects)) {
    $projects = FS_Project::get_all(array('status' => array('draft', 'pending', 'active', 'on_hold'), 'orderby' => 'name', 'order' => 'ASC'));
}

// Ensure activity types are available
if (!isset($activity_types) || empty($activity_types)) {
    $activity_types = FS_Time_Entry::get_activity_types();
}
?>

<!-- Time Entry Modal -->
<div id="<?php echo esc_attr($modal_id); ?>-modal" class="fs-modal">
    <div class="fs-modal-content">
        <div class="fs-modal-header">
            <h2 id="<?php echo esc_attr($modal_id); ?>-modal-title"><?php esc_html_e('Add Time Entry', 'freelance-studio'); ?></h2>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <form id="<?php echo esc_attr($modal_id); ?>-form" class="fs-time-entry-modal-form">
                <input type="hidden" name="entry_id" id="<?php echo esc_attr($modal_id); ?>-entry-id" value="">
                <input type="hidden" name="start_date" id="<?php echo esc_attr($modal_id); ?>-date" value="">
                
                <!-- Project -->
                <div class="fs-form-row">
                    <label for="<?php echo esc_attr($modal_id); ?>-project"><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                    <select name="project_id" id="<?php echo esc_attr($modal_id); ?>-project" class="widefat">
                        <option value=""><?php esc_html_e('— Select project —', 'freelance-studio'); ?></option>
                        <?php if (!empty($projects)): foreach ($projects as $proj_item): 
                            // Get hourly rate from services
                            $proj_rate = get_option('fs_default_hourly_rate', 75);
                            $proj_services = $proj_item->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'])) {
                                        $proj_rate = floatval($svc['rate']);
                                        break;
                                    }
                                }
                            }
                        ?>
                            <option value="<?php echo esc_attr($proj_item->id); ?>" data-rate="<?php echo esc_attr($proj_rate); ?>">
                                <?php echo esc_html($proj_item->name); ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>
                
                <!-- Task (dynamically loaded) -->
                <div class="fs-form-row fs-task-row" style="display: none;">
                    <label for="<?php echo esc_attr($modal_id); ?>-task"><?php esc_html_e('Task', 'freelance-studio'); ?> <span class="fs-optional">(<?php esc_html_e('optional', 'freelance-studio'); ?>)</span></label>
                    <select name="task_id" id="<?php echo esc_attr($modal_id); ?>-task" class="widefat">
                        <option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>
                    </select>
                </div>
                
                <!-- Activity -->
                <div class="fs-form-row">
                    <label for="<?php echo esc_attr($modal_id); ?>-activity"><?php esc_html_e('Activity', 'freelance-studio'); ?></label>
                    <select name="activity" id="<?php echo esc_attr($modal_id); ?>-activity" class="widefat">
                        <?php if (!empty($activity_types)): 
                            $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; endif; ?>
                    </select>
                </div>
                
                <!-- Duration -->
                <div class="fs-form-row">
                    <label><?php esc_html_e('Duration', 'freelance-studio'); ?></label>
                    <div class="fs-duration-row">
                        <input type="number" name="duration_hours" id="<?php echo esc_attr($modal_id); ?>-hours" min="0" value="0" class="fs-duration-input">
                        <span class="fs-duration-label"><?php esc_html_e('hours', 'freelance-studio'); ?></span>
                        <input type="number" name="duration_minutes" id="<?php echo esc_attr($modal_id); ?>-minutes" min="0" max="59" value="0" class="fs-duration-input">
                        <span class="fs-duration-label"><?php esc_html_e('minutes', 'freelance-studio'); ?></span>
                        <input type="number" name="duration_seconds" id="<?php echo esc_attr($modal_id); ?>-seconds" min="0" max="59" value="0" class="fs-duration-input">
                        <span class="fs-duration-label"><?php esc_html_e('seconds', 'freelance-studio'); ?></span>
                    </div>
                </div>
                
                <!-- Time Range (optional) -->
                <div class="fs-form-row">
                    <label><?php esc_html_e('Time Range', 'freelance-studio'); ?> <span class="fs-optional">(<?php esc_html_e('optional', 'freelance-studio'); ?>)</span></label>
                    <div class="fs-time-range-row">
                        <input type="time" name="start_time" id="<?php echo esc_attr($modal_id); ?>-start-time" class="fs-time-input">
                        <span><?php esc_html_e('to', 'freelance-studio'); ?></span>
                        <input type="time" name="end_time" id="<?php echo esc_attr($modal_id); ?>-end-time" class="fs-time-input">
                    </div>
                </div>
                
                <!-- Hourly Rate -->
                <div class="fs-form-row">
                    <label for="<?php echo esc_attr($modal_id); ?>-rate"><?php esc_html_e('Hourly Rate', 'freelance-studio'); ?></label>
                    <input type="number" name="hourly_rate" id="<?php echo esc_attr($modal_id); ?>-rate" step="0.01" min="0" value="<?php echo esc_attr($default_rate); ?>" class="widefat">
                </div>
                
                <!-- Description -->
                <div class="fs-form-row">
                    <label for="<?php echo esc_attr($modal_id); ?>-description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                    <textarea name="description" id="<?php echo esc_attr($modal_id); ?>-description" class="widefat" rows="2" placeholder="<?php esc_attr_e('What did you work on?', 'freelance-studio'); ?>"></textarea>
                </div>
                
                <!-- Billable -->
                <div class="fs-form-row">
                    <label class="fs-checkbox-label">
                        <input type="checkbox" name="billable" id="<?php echo esc_attr($modal_id); ?>-billable" value="1" checked>
                        <?php esc_html_e('Billable', 'freelance-studio'); ?>
                    </label>
                </div>
            </form>
        </div>
        <div class="fs-modal-footer">
            <button type="button" class="fs-btn fs-btn-secondary fs-modal-cancel"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
            <button type="button" class="fs-btn fs-btn-primary fs-modal-save"><?php esc_html_e('Add Entry', 'freelance-studio'); ?></button>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    var modalId = '<?php echo esc_js($modal_id); ?>';
    var $modal = $('#' + modalId + '-modal');
    var $form = $('#' + modalId + '-form');
    
    // Project change handler - load tasks and update hourly rate
    $('#' + modalId + '-project').on('change', function() {
        var projectId = $(this).val();
        var rate = $(this).find(':selected').data('rate');
        var $taskRow = $form.find('.fs-task-row');
        var $taskSelect = $('#' + modalId + '-task');
        
        // Update hourly rate
        if (rate) {
            $('#' + modalId + '-rate').val(rate);
        }
        
        // Show/hide and load tasks
        if (projectId) {
            $taskRow.show();
            $taskSelect.html('<option value=""><?php esc_html_e('Loading...', 'freelance-studio'); ?></option>');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_get_project_tasks',
                    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                    project_id: projectId
                },
                success: function(response) {
                    var options = '<option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>';
                    if (response.success && response.data && response.data.length > 0) {
                        response.data.forEach(function(task) {
                            options += '<option value="' + task.id + '" data-non-billable="' + (task.is_non_billable || 0) + '">' + task.title + (task.is_non_billable ? ' (non-billable)' : '') + '</option>';
                        });
                    }
                    $taskSelect.html(options);
                },
                error: function() {
                    $taskSelect.html('<option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>');
                }
            });
        } else {
            $taskRow.hide();
            $taskSelect.html('<option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>');
        }
    });
    
    // Calculate end time when duration changes and start time is set
    function calculateEndTime() {
        var startTime = $('#' + modalId + '-start-time').val();
        var hours = parseInt($('#' + modalId + '-hours').val()) || 0;
        var minutes = parseInt($('#' + modalId + '-minutes').val()) || 0;
        var seconds = parseInt($('#' + modalId + '-seconds').val()) || 0;
        
        if (startTime && (hours > 0 || minutes > 0 || seconds > 0)) {
            var totalSeconds = (hours * 3600) + (minutes * 60) + seconds;
            var startDate = new Date('2000-01-01 ' + startTime);
            var endDate = new Date(startDate.getTime() + (totalSeconds * 1000));
            
            var endHours = String(endDate.getHours()).padStart(2, '0');
            var endMinutes = String(endDate.getMinutes()).padStart(2, '0');
            
            $('#' + modalId + '-end-time').val(endHours + ':' + endMinutes);
        }
    }
    
    // Calculate duration when end time changes
    function calculateDuration() {
        var startTime = $('#' + modalId + '-start-time').val();
        var endTime = $('#' + modalId + '-end-time').val();
        
        if (startTime && endTime) {
            var start = new Date('2000-01-01 ' + startTime);
            var end = new Date('2000-01-01 ' + endTime);
            
            // Handle overnight
            if (end < start) {
                end.setDate(end.getDate() + 1);
            }
            
            var diffSeconds = Math.floor((end - start) / 1000);
            if (diffSeconds > 0) {
                var hours = Math.floor(diffSeconds / 3600);
                var minutes = Math.floor((diffSeconds % 3600) / 60);
                var secs = diffSeconds % 60;
                
                $('#' + modalId + '-hours').val(hours);
                $('#' + modalId + '-minutes').val(minutes);
                $('#' + modalId + '-seconds').val(secs);
            }
        }
    }
    
    $('#' + modalId + '-hours, #' + modalId + '-minutes, #' + modalId + '-seconds').on('change', calculateEndTime);
    $('#' + modalId + '-start-time').on('change', calculateEndTime);
    $('#' + modalId + '-end-time').on('change', calculateDuration);
    
    // Auto-manage billable checkbox when a non-billable task is selected
    $('#' + modalId + '-task').on('change', function() {
        var $selected = $(this).find(':selected');
        var isNonBillable = parseInt($selected.data('non-billable')) === 1;
        var $billable = $('#' + modalId + '-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);
            $billable.closest('label').removeAttr('title');
            // Only re-check if it was disabled by a previous non-billable task selection
            if (!$billable.data('user-unchecked')) {
                $billable.prop('checked', true);
            }
        }
    });
    
    // Track if user manually unchecked billable
    $('#' + modalId + '-billable').on('change', function() {
        if (!$(this).prop('disabled')) {
            $(this).data('user-unchecked', !$(this).prop('checked'));
        }
    });
    
    // Modal close handlers
    $modal.find('.fs-modal-close, .fs-modal-cancel').on('click', function() {
        $modal.removeClass('active');
        resetForm();
    });
    
    // Close on backdrop click
    $modal.on('click', function(e) {
        if ($(e.target).is($modal)) {
            $modal.removeClass('active');
            resetForm();
        }
    });
    
    // Reset form
    function resetForm() {
        $form[0].reset();
        $('#' + modalId + '-entry-id').val('');
        $('#' + modalId + '-hours').val(0);
        $('#' + modalId + '-minutes').val(0);
        $('#' + modalId + '-seconds').val(0);
        $form.find('.fs-task-row').hide();
        $('#' + modalId + '-task').html('<option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>');
        $('#' + modalId + '-rate').val('<?php echo esc_js($default_rate); ?>');
        $('#' + modalId + '-billable').prop('disabled', false).prop('checked', true).data('user-unchecked', false);
        $('#' + modalId + '-billable').closest('label').removeAttr('title');
        $modal.find('.fs-modal-save').text('<?php esc_html_e('Add Entry', 'freelance-studio'); ?>');
        $('#' + modalId + '-modal-title').text('<?php esc_html_e('Add Time Entry', 'freelance-studio'); ?>');
    }
    
    // Save handler
    $modal.find('.fs-modal-save').on('click', function() {
        var entryId = $('#' + modalId + '-entry-id').val();
        var date = $('#' + modalId + '-date').val() || '<?php echo  esc_html( gmdate('Y-m-d') ); ?>';
        var projectId = $('#' + modalId + '-project').val();
        var taskId = $('#' + modalId + '-task').val();
        var activity = $('#' + modalId + '-activity').val();
        var hours = parseInt($('#' + modalId + '-hours').val()) || 0;
        var minutes = parseInt($('#' + modalId + '-minutes').val()) || 0;
        var seconds = parseInt($('#' + modalId + '-seconds').val()) || 0;
        var duration = (hours * 3600) + (minutes * 60) + seconds;
        var startTime = $('#' + modalId + '-start-time').val();
        var endTime = $('#' + modalId + '-end-time').val();
        var hourlyRate = parseFloat($('#' + modalId + '-rate').val()) || 0;
        var description = $('#' + modalId + '-description').val();
        var billable = $('#' + modalId + '-billable').is(':checked') ? 1 : 0;
        
        if (duration === 0) {
            alert('<?php esc_html_e('Please enter a duration', 'freelance-studio'); ?>');
            return;
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_save_time_entry',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                entry_id: entryId,
                start_date: date,
                start_time: startTime,
                end_time: endTime,
                project_id: projectId,
                task_id: taskId,
                activity: activity,
                duration: duration,
                hourly_rate: hourlyRate,
                description: description,
                billable: billable
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || '<?php esc_html_e('Error saving entry', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error saving entry', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Expose open function for external use
    window.openTimeEntryModal = function(options) {
        options = options || {};
        
        if (options.date) {
            $('#' + modalId + '-date').val(options.date);
        }
        
        if (options.entryId) {
            $('#' + modalId + '-entry-id').val(options.entryId);
            $modal.find('.fs-modal-save').text('<?php esc_html_e('Update Entry', 'freelance-studio'); ?>');
            $('#' + modalId + '-modal-title').text('<?php esc_html_e('Edit Time Entry', 'freelance-studio'); ?>');
        }
        
        if (options.projectId) {
            $('#' + modalId + '-project').val(options.projectId).trigger('change');
        }
        
        $modal.addClass('active');
    };
});
</script>
