<?php
/**
 * Time Entry Form View
 *
 * @package Freelance_Studio
 */

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

$is_edit = !empty($entry);
$page_title = $is_edit ? __('Edit Time Entry', 'freelance-studio') : __('New Time Entry', 'freelance-studio');

// Determine return URL - if coming from a project, return there
$from_project_id = isset($_GET['from_project']) ? intval($_GET['from_project']) : 0;
if (!$from_project_id && isset($_GET['project_id'])) {
    $from_project_id = intval($_GET['project_id']);
}
if (!$from_project_id && $is_edit && !empty($entry->project_id)) {
    // Check referrer for project context
    $referer = wp_get_referer();
    if ($referer && strpos($referer, 'page=fs-projects') !== false && strpos($referer, 'action=view') !== false) {
        $from_project_id = intval($entry->project_id);
    }
}
$return_url = $from_project_id 
    ? admin_url('admin.php?page=fs-projects&action=view&id=' . $from_project_id . '&tab=timer')
    : admin_url('admin.php?page=fs-time-tracking');

// Calculate hours, minutes, and seconds from duration
$duration_hours = 0;
$duration_minutes = 0;
$duration_seconds = 0;
if ($is_edit && $entry->duration) {
    $duration_hours = floor($entry->duration / 3600);
    $duration_minutes = floor(($entry->duration % 3600) / 60);
    $duration_seconds = $entry->duration % 60;
}
?>

<div class="wrap fs-wrap">
    <h1><?php echo esc_html($page_title); ?></h1>
    
    <form method="post" action="" id="fs-time-entry-form" class="fs-form">
        <?php wp_nonce_field('fs_save_time_entry', 'fs_time_entry_nonce'); ?>
        <input type="hidden" name="action" value="save_time_entry">
        <?php if ($is_edit): ?>
            <input type="hidden" name="entry_id" value="<?php echo esc_attr($entry->id); ?>">
        <?php endif; ?>
        
        <div class="fs-form-section">
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="project_id"><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <select name="project_id" id="project_id" class="regular-text">
                            <option value=""><?php esc_html_e('— No project —', 'freelance-studio'); ?></option>
                            <?php 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 selected(
                                            ($is_edit && $entry->project_id == $proj_item->id) || 
                                            (!$is_edit && $from_project_id == $proj_item->id)
                                        ); ?>>
                                    <?php echo esc_html($proj_item->name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                
                <tr class="fs-task-row" <?php if ((!$is_edit && !$from_project_id) || ($is_edit && !$entry->project_id)) echo 'style="display: none;"'; ?>>
                    <th scope="row">
                        <label for="task_id"><?php esc_html_e('Task', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <select name="task_id" id="task_id" class="regular-text">
                            <option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>
                            <?php 
                            $preload_project_id = $is_edit ? $entry->project_id : $from_project_id;
                            if ($preload_project_id): 
                                $project_tasks = FS_Task::get_all(array('project_id' => $preload_project_id));
                                foreach ($project_tasks as $task): ?>
                                    <option value="<?php echo esc_attr($task->id); ?>" <?php selected($is_edit && $entry->task_id == $task->id); ?>>
                                        <?php echo esc_html($task->title); ?>
                                    </option>
                                <?php endforeach; 
                            endif; ?>
                        </select>
                        <p class="description"><?php esc_html_e('Optionally assign this time entry to a specific task', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <textarea name="description" id="description" rows="3" class="large-text"><?php echo $is_edit ? esc_textarea($entry->description) : ''; ?></textarea>
                        <p class="description"><?php esc_html_e('What did you work on?', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="activity"><?php esc_html_e('Activity Type', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <select name="activity" id="activity" class="regular-text">
                            <?php 
                            $default_activity = get_option('fs_default_activity', 'development');
                            foreach ($activity_types as $key => $label): 
                                $is_selected = $is_edit ? ($entry->activity === $key) : ($default_activity === $key);
                            ?>
                                <option value="<?php echo esc_attr($key); ?>" <?php selected($is_selected); ?>>
                                    <?php echo esc_html($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="start_date"><?php esc_html_e('Date', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <input type="date" name="start_date" id="start_date" class="regular-text" 
                               value="<?php echo $is_edit ? esc_attr(FS_Time_Entry::utc_to_local($entry->start_time, 'Y-m-d')) : esc_attr(gmdate('Y-m-d')); ?>">
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label><?php esc_html_e('Duration', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <div class="fs-duration-inputs">
                            <input type="number" name="duration_hours" id="duration_hours" min="0" step="1" 
                                   value="<?php echo esc_attr($duration_hours); ?>" class="small-text"> 
                            <span><?php esc_html_e('hours', 'freelance-studio'); ?></span>
                            <input type="number" name="duration_minutes" id="duration_minutes" min="0" max="59" step="1" 
                                   value="<?php echo esc_attr($duration_minutes); ?>" class="small-text">
                            <span><?php esc_html_e('minutes', 'freelance-studio'); ?></span>
                            <input type="number" name="duration_seconds" id="duration_seconds" min="0" max="59" step="1" 
                                   value="<?php echo esc_attr($duration_seconds); ?>" class="small-text">
                            <span><?php esc_html_e('seconds', 'freelance-studio'); ?></span>
                        </div>
                        <input type="hidden" name="duration" id="duration" value="<?php echo $is_edit ? esc_attr($entry->duration) : ''; ?>">
                        <p class="description"><?php esc_html_e('Enter the time spent on this task', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                
                <tr class="fs-time-range-row">
                    <th scope="row">
                        <label><?php esc_html_e('Time Range (optional)', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <input type="time" name="start_time" id="start_time" step="1"
                               value="<?php echo $is_edit ? esc_attr(FS_Time_Entry::utc_to_local($entry->start_time, 'H:i:s')) : ''; ?>">
                        <span><?php esc_html_e('to', 'freelance-studio'); ?></span>
                        <input type="time" name="end_time" id="end_time" step="1"
                               value="<?php echo $is_edit && $entry->end_time ? esc_attr(FS_Time_Entry::utc_to_local($entry->end_time, 'H:i:s')) : ''; ?>">
                        <p class="description"><?php esc_html_e('Optional: Specify exact start and end times. Changing duration with start time set will auto-calculate end time.', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="hourly_rate"><?php esc_html_e('Hourly Rate', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <input type="number" name="hourly_rate" id="hourly_rate" step="0.01" min="0" class="regular-text" 
                               value="<?php 
                                if ($is_edit) {
                                    echo esc_attr($entry->hourly_rate);
                                } elseif ($from_project_id) {
                                    // Get rate from pre-selected project
                                    $form_rate = get_option('fs_default_hourly_rate', 75);
                                    foreach ($projects as $fp) {
                                        if ($fp->id == $from_project_id) {
                                            $fp_services = $fp->services;
                                            if (is_string($fp_services)) $fp_services = json_decode($fp_services, true);
                                            if (!empty($fp_services) && is_array($fp_services)) {
                                                foreach ($fp_services as $fpsvc) {
                                                    if (isset($fpsvc['pricing_type']) && $fpsvc['pricing_type'] === 'hourly' && !empty($fpsvc['rate'])) {
                                                        $form_rate = floatval($fpsvc['rate']);
                                                        break;
                                                    }
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    echo esc_attr($form_rate);
                                } else {
                                    echo esc_attr(get_option('fs_default_hourly_rate', 75));
                                }
                               ?>">
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <label for="billable"><?php esc_html_e('Billable', 'freelance-studio'); ?></label>
                    </th>
                    <td>
                        <label>
                            <input type="checkbox" name="billable" id="billable" value="1" 
                                   <?php checked(!$is_edit || $entry->billable); ?>>
                            <?php esc_html_e('This time is billable to the client', 'freelance-studio'); ?>
                        </label>
                    </td>
                </tr>
            </table>
        </div>
        
        <p class="submit">
            <input type="submit" name="submit" class="fs-btn fs-btn-submit" value="<?php echo  esc_attr( $is_edit ? __('Update Entry', 'freelance-studio') : __('Save Entry', 'freelance-studio') ); ?>">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking') ); ?>" class="fs-btn fs-btn-secondary"><?php esc_html_e('Cancel', 'freelance-studio'); ?></a>
        </p>
    </form>
</div>

<style>
.fs-duration-inputs {
    display: flex;
    align-items: center;
    gap: 8px;
}
.fs-duration-inputs input {
    width: 70px !important;
}
.fs-time-range-row td {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 10px;
}
.fs-time-range-row input[type="time"] {
    width: 130px;
}
.fs-time-range-row .description {
    width: 100%;
    margin-top: 5px;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Update hourly rate and load tasks when project changes
    $('#project_id').on('change', function() {
        var projectId = $(this).val();
        var rate = $(this).find(':selected').data('rate');
        
        // Update hourly rate
        if (rate) {
            $('#hourly_rate').val(rate);
        }
        
        // Show/hide task row and load tasks
        if (projectId) {
            $('.fs-task-row').show();
            loadProjectTasks(projectId);
        } else {
            $('.fs-task-row').hide();
            $('#task_id').html('<option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>');
        }
    });
    
    // Load tasks for a project via AJAX
    function loadProjectTasks(projectId) {
        $('#task_id').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>';
                    });
                }
                $('#task_id').html(options);
            },
            error: function() {
                $('#task_id').html('<option value=""><?php esc_html_e('— No task —', 'freelance-studio'); ?></option>');
            }
        });
    }
    
    // Calculate duration from hours, minutes, and seconds
    function updateDuration(calculateEndTime) {
        var hours = parseInt($('#duration_hours').val()) || 0;
        var minutes = parseInt($('#duration_minutes').val()) || 0;
        var seconds = parseInt($('#duration_seconds').val()) || 0;
        var totalSeconds = (hours * 3600) + (minutes * 60) + seconds;
        $('#duration').val(totalSeconds);
        
        // If start time is set and calculateEndTime is true, auto-calculate end time
        if (calculateEndTime !== false) {
            var startTime = $('#start_time').val();
            if (startTime && totalSeconds > 0) {
                calculateEndTimeFromDuration();
            }
        }
    }
    
    // Auto-manage billable checkbox when a non-billable task is selected
    $('#task_id').on('change', function() {
        var $selected = $(this).find(':selected');
        var isNonBillable = parseInt($selected.data('non-billable')) === 1;
        var $billable = $('#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');
        }
    });
    
    // Calculate end time from start time + duration
    function calculateEndTimeFromDuration() {
        var startTime = $('#start_time').val();
        var totalSeconds = parseInt($('#duration').val()) || 0;
        
        if (startTime && totalSeconds > 0) {
            // Parse start time (handle both HH:MM and HH:MM:SS formats)
            var timeParts = startTime.split(':');
            var startDate = new Date('2000-01-01 ' + startTime);
            
            // Add duration
            var endDate = new Date(startDate.getTime() + (totalSeconds * 1000));
            
            // Format as HH:MM:SS
            var endHours = String(endDate.getHours()).padStart(2, '0');
            var endMinutes = String(endDate.getMinutes()).padStart(2, '0');
            var endSeconds = String(endDate.getSeconds()).padStart(2, '0');
            
            $('#end_time').val(endHours + ':' + endMinutes + ':' + endSeconds);
        }
    }
    
    $('#duration_hours, #duration_minutes, #duration_seconds').on('change input', function() {
        updateDuration(true);
    });
    
    // Calculate duration from start/end times if they change
    function calculateFromTimeRange() {
        var startTime = $('#start_time').val();
        var endTime = $('#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 diff = Math.floor((end - start) / 1000);
            if (diff > 0) {
                var hours = Math.floor(diff / 3600);
                var minutes = Math.floor((diff % 3600) / 60);
                var seconds = diff % 60;
                
                $('#duration_hours').val(hours);
                $('#duration_minutes').val(minutes);
                $('#duration_seconds').val(seconds);
                $('#duration').val(diff);
            }
        }
    }
    
    // When end time changes, calculate duration from time range
    $('#end_time').on('change', calculateFromTimeRange);
    
    // When start time changes, calculate end time if duration exists
    $('#start_time').on('change', function() {
        var duration = parseInt($('#duration').val()) || 0;
        if (duration > 0) {
            calculateEndTimeFromDuration();
        }
    });
    
    // Initialize duration on page load (don't auto-calculate end time on load)
    updateDuration(false);
    
    // Form submission via AJAX
    $('#fs-time-entry-form').on('submit', function(e) {
        e.preventDefault();
        
        // Make sure duration is updated
        updateDuration();
        
        var formData = $(this).serialize();
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData + '&action=fs_save_time_entry&nonce=<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
            success: function(response) {
                if (response.success) {
                    window.location.href = '<?php echo esc_js($return_url); ?>';
                } else {
                    alert(response.data || 'Error saving entry');
                }
            },
            error: function() {
                alert('Error saving entry');
            }
        });
    });
});
</script>
