<?php
/**
 * Provide a admin area view for the work logs page
 *
 * @link       https://example.com
 * @since      1.0.0
 *
 * @package    Subscription_System
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Enqueue WordPress media scripts for the visual editor
wp_enqueue_media();
wp_enqueue_editor();

// Enqueue jQuery UI datepicker
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_script('jquery-ui-timepicker', plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/js/jquery-ui-timepicker-addon.min.js', array('jquery-ui-datepicker'), '1.6.3', true);
wp_enqueue_style('jquery-ui-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');
wp_enqueue_style('jquery-ui-timepicker', plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/css/jquery-ui-timepicker-addon.min.css');
?>

<div class="wrap">
    <?php if ($user): ?>
        <?php 
        /* translators: %s: user's display name */
        ?><h1><?php echo esc_html(sprintf(__('Work Logs for %s', 'subscription-system'), $user->display_name)); ?></h1>
    <?php else: ?>
        <h1><?php echo esc_html__('Work Logs', 'subscription-system'); ?></h1>
        <div class="notice notice-error">
            <p><?php echo esc_html__('Invalid user ID. Please select a valid user.', 'subscription-system'); ?></p>
        </div>
        <?php if (current_user_can('manage_options')): ?>
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=subscription-subscribers')); ?>" class="button"><?php echo esc_html__('Back to Subscribers', 'subscription-system'); ?></a></p>
        <?php endif; ?>
        <?php return; ?>
    <?php endif; ?>
    
    <?php if (current_user_can('manage_options')): ?>
        <p><a href="<?php echo esc_url(admin_url('admin.php?page=subscription-subscribers')); ?>" class="button"><?php echo esc_html__('Back to Subscribers', 'subscription-system'); ?></a></p>
    <?php endif; ?>
    
    <?php settings_errors('subscription_messages'); ?>
    
    <div class="subscription-admin-container">
        <div class="subscription-admin-main">
            <div class="subscription-admin-card">
                <h2><?php echo esc_html__('All Work Logs', 'subscription-system'); ?></h2>
                
                <?php if (empty($work_logs)): ?>
                    <p><?php echo esc_html__('No work logs found for this user.', 'subscription-system'); ?></p>
                <?php else: ?>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php echo esc_html__('ID', 'subscription-system'); ?></th>
                                <th><?php echo esc_html__('Channel', 'subscription-system'); ?></th>
                                <th><?php echo esc_html__('Work Item', 'subscription-system'); ?></th>
                                <th><?php echo esc_html__('Importance', 'subscription-system'); ?></th>
                                <th><?php echo esc_html__('Notes', 'subscription-system'); ?></th>
                                <th><?php echo esc_html__('Performed At', 'subscription-system'); ?></th>
                                <th><?php echo esc_html__('Created At', 'subscription-system'); ?></th>
                                <th><?php echo esc_html__('Actions', 'subscription-system'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($work_logs as $work_log): ?>
                                <tr>
                                    <td><?php echo esc_html($work_log->id); ?></td>
                                    <td><?php echo esc_html($work_log->channel_name ? $work_log->channel_name : __('None', 'subscription-system')); ?></td>
                                    <td><?php echo esc_html($work_log->work_item_name ? $work_log->work_item_name : __('None', 'subscription-system')); ?></td>
                                    <td><?php echo esc_html($work_log->importance); ?></td>
                                    <td>
                                        <div class="work-log-notes-preview">
                                            <?php echo wp_kses_post(substr(strip_tags($work_log->notes), 0, 100) . (strlen(strip_tags($work_log->notes)) > 100 ? '...' : '')); ?>
                                            <?php if (strlen(strip_tags($work_log->notes)) > 100): ?>
                                                <a href="#" class="view-full-notes" data-notes="<?php echo esc_attr($work_log->notes); ?>"><?php echo esc_html__('View Full Notes', 'subscription-system'); ?></a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($work_log->performed_at))); ?></td>
                                    <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($work_log->created_at))); ?></td>
                                    <td>
                                        <a href="#" class="edit-work-log" 
                                           data-id="<?php echo esc_attr($work_log->id); ?>" 
                                           data-channel-id="<?php echo esc_attr($work_log->channel_id); ?>" 
                                           data-work-item-id="<?php echo esc_attr($work_log->work_item_id); ?>" 
                                           data-importance="<?php echo esc_attr($work_log->importance); ?>" 
                                           data-notes="<?php echo esc_attr($work_log->notes); ?>"
                                           data-performed-at="<?php echo esc_attr(date('Y-m-d H:i', strtotime($work_log->performed_at))); ?>">
                                            <?php echo esc_html__('Edit', 'subscription-system'); ?>
                                        </a> | 
                                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=subscription-work-logs&action=delete&work_log_id=' . $work_log->id . '&user_id=' . $user_id), 'delete_work_log_' . $work_log->id)); ?>" class="delete-work-log" onclick="return confirm('<?php echo esc_js(__('Are you sure you want to delete this work log?', 'subscription-system')); ?>')">
                                            <?php echo esc_html__('Delete', 'subscription-system'); ?>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="subscription-admin-sidebar">
            <div class="subscription-admin-card">
                <h2><?php echo esc_html__('Add New Work Log', 'subscription-system'); ?></h2>
                
                <form method="post" action="">
                    <?php wp_nonce_field('subscription_add_work_log', 'subscription_nonce'); ?>
                    <input type="hidden" name="user_id" value="<?php echo esc_attr($user_id); ?>">
                    
                    <div class="form-field">
                        <label for="channel_id"><?php echo esc_html__('Channel', 'subscription-system'); ?> <span class="required">*</span></label>
                        <select id="channel_id" name="channel_id" required>
                            <option value=""><?php echo esc_html__('-- Select Channel --', 'subscription-system'); ?></option>
                            <?php foreach ($channels as $channel): ?>
                                <?php if ($channel->status === 'active'): ?>
                                    <option value="<?php echo esc_attr($channel->id); ?>"><?php echo esc_html($channel->name); ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-field">
                        <label for="work_item_id"><?php echo esc_html__('Work Item', 'subscription-system'); ?> <span class="required">*</span></label>
                        <select id="work_item_id" name="work_item_id" required disabled>
                            <option value=""><?php echo esc_html__('-- Select Channel First --', 'subscription-system'); ?></option>
                        </select>
                    </div>
                    
                    <div class="form-field">
                        <label for="importance"><?php echo esc_html__('Importance', 'subscription-system'); ?></label>
                        <textarea id="importance" name="importance" rows="3"></textarea>
                    </div>
                    
                    <div class="form-field">
                        <label for="notes"><?php echo esc_html__('Notes', 'subscription-system'); ?></label>
                        <?php 
                        $editor_settings = array(
                            'textarea_name' => 'notes',
                            'textarea_rows' => 10,
                            'media_buttons' => true,
                            'teeny' => true,
                            'quicktags' => true,
                        );
                        wp_editor('', 'notes', $editor_settings);
                        ?>
                    </div>
                    
                    <div class="form-field">
                        <label for="performed_at"><?php echo esc_html__('Performed At', 'subscription-system'); ?></label>
                        <input type="text" id="performed_at" name="performed_at" class="datetimepicker" value="<?php echo esc_attr(date_i18n('Y-m-d H:i')); ?>" autocomplete="off">
                    </div>
                    
                    <p class="submit">
                        <input type="submit" name="add_work_log" class="button button-primary" value="<?php echo esc_attr__('Add Work Log', 'subscription-system'); ?>">
                    </p>
                </form>
            </div>
            
            <div class="subscription-admin-card" id="edit-work-log-form" style="display: none;">
                <h2><?php echo esc_html__('Edit Work Log', 'subscription-system'); ?></h2>
                
                <form method="post" action="">
                    <?php wp_nonce_field('subscription_edit_work_log', 'subscription_nonce'); ?>
                    <input type="hidden" id="edit_work_log_id" name="work_log_id">
                    
                    <div class="form-field">
                        <label for="edit_channel_id"><?php echo esc_html__('Channel', 'subscription-system'); ?> <span class="required">*</span></label>
                        <select id="edit_channel_id" name="channel_id" required>
                            <option value=""><?php echo esc_html__('-- Select Channel --', 'subscription-system'); ?></option>
                            <?php foreach ($channels as $channel): ?>
                                <?php if ($channel->status === 'active'): ?>
                                    <option value="<?php echo esc_attr($channel->id); ?>"><?php echo esc_html($channel->name); ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-field">
                        <label for="edit_work_item_id"><?php echo esc_html__('Work Item', 'subscription-system'); ?> <span class="required">*</span></label>
                        <select id="edit_work_item_id" name="work_item_id" required>
                            <option value=""><?php echo esc_html__('-- Select Channel First --', 'subscription-system'); ?></option>
                        </select>
                    </div>
                    
                    <div class="form-field">
                        <label for="edit_importance"><?php echo esc_html__('Importance', 'subscription-system'); ?></label>
                        <textarea id="edit_importance" name="importance" rows="3"></textarea>
                    </div>
                    
                    <div class="form-field">
                        <label for="edit_notes"><?php echo esc_html__('Notes', 'subscription-system'); ?></label>
                        <?php 
                        $editor_settings = array(
                            'textarea_name' => 'notes',
                            'textarea_rows' => 10,
                            'media_buttons' => true,
                            'teeny' => true,
                            'quicktags' => true,
                        );
                        wp_editor('', 'edit_notes', $editor_settings);
                        ?>
                    </div>
                    
                    <div class="form-field">
                        <label for="edit_performed_at"><?php echo esc_html__('Performed At', 'subscription-system'); ?></label>
                        <input type="text" id="edit_performed_at" name="performed_at" class="datetimepicker" autocomplete="off">
                    </div>
                    
                    <p class="submit">
                        <input type="submit" name="edit_work_log" class="button button-primary" value="<?php echo esc_attr__('Update Work Log', 'subscription-system'); ?>">
                        <button type="button" class="button cancel-edit"><?php echo esc_html__('Cancel', 'subscription-system'); ?></button>
                    </p>
                </form>
            </div>
            
            <div id="notes-modal" class="modal" style="display: none;">
                <div class="modal-content">
                    <span class="close">&times;</span>
                    <h3><?php echo esc_html__('Full Notes', 'subscription-system'); ?></h3>
                    <div id="full-notes-content"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .subscription-admin-container {
        display: flex;
        flex-wrap: wrap;
        margin-top: 20px;
    }
    
    .subscription-admin-main {
        flex: 2;
        margin-right: 20px;
    }
    
    .subscription-admin-sidebar {
        flex: 1;
        min-width: 300px;
    }
    
    .subscription-admin-card {
        background: #fff;
        border: 1px solid #ccd0d4;
        box-shadow: 0 1px 1px rgba(0,0,0,.04);
        margin-bottom: 20px;
        padding: 15px;
    }
    
    .form-field {
        margin-bottom: 15px;
    }
    
    .form-field label {
        display: block;
        margin-bottom: 5px;
        font-weight: 600;
    }
    
    .form-field input[type="text"],
    .form-field textarea,
    .form-field select {
        width: 100%;
    }
    
    .required {
        color: #dc3232;
    }
    
    /* Modal styles */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.4);
    }
    
    .modal-content {
        background-color: #fefefe;
        margin: 10% auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
        max-width: 800px;
        border-radius: 4px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
    }
    
    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
    }
    
    #full-notes-content {
        margin-top: 15px;
        padding: 15px;
        background-color: #f9f9f9;
        border: 1px solid #e5e5e5;
        border-radius: 4px;
        max-height: 400px;
        overflow-y: auto;
    }
    
    .work-log-notes-preview {
        max-width: 300px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .view-full-notes {
        display: inline-block;
        margin-left: 5px;
        font-size: 12px;
    }
    
    /* Datepicker styling */
    .ui-datepicker {
        z-index: 9999 !important;
    }
</style>

<script>
jQuery(document).ready(function($) {
    // Initialize datepicker
    $('.datetimepicker').datetimepicker({
        dateFormat: 'yy-mm-dd',
        timeFormat: 'HH:mm',
        controlType: 'select',
        oneLine: true,
        stepMinute: 5
    });
    
    // Channel dropdown change event
    $('#channel_id, #edit_channel_id').on('change', function() {
        var channelId = $(this).val();
        var targetSelect = $(this).attr('id') === 'channel_id' ? '#work_item_id' : '#edit_work_item_id';
        
        if (channelId) {
            $(targetSelect).prop('disabled', true);
            $(targetSelect).html('<option value=""><?php echo esc_js(__('Loading...', 'subscription-system')); ?></option>');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'get_work_items_by_channel',
                    channel_id: channelId,
                    security: '<?php echo wp_create_nonce('subs_sys_admin'); ?>'
                },
                success: function(response) {
                    if (response.success && response.data) {
                        var options = '<option value=""><?php echo esc_js(__('-- Select Work Item --', 'subscription-system')); ?></option>';
                        
                        $.each(response.data, function(index, item) {
                            options += '<option value="' + item.id + '">' + item.name + '</option>';
                        });
                        
                        $(targetSelect).html(options);
                        $(targetSelect).prop('disabled', false);
                    } else {
                        $(targetSelect).html('<option value=""><?php echo esc_js(__('No work items found', 'subscription-system')); ?></option>');
                        $(targetSelect).prop('disabled', true);
                    }
                },
                error: function() {
                    $(targetSelect).html('<option value=""><?php echo esc_js(__('Error loading work items', 'subscription-system')); ?></option>');
                    $(targetSelect).prop('disabled', true);
                }
            });
        } else {
            $(targetSelect).html('<option value=""><?php echo esc_js(__('-- Select Channel First --', 'subscription-system')); ?></option>');
            $(targetSelect).prop('disabled', true);
        }
    });
    
    // Edit work log
    $('.edit-work-log').on('click', function(e) {
        e.preventDefault();
        
        var id = $(this).data('id');
        var channelId = $(this).data('channel-id');
        var workItemId = $(this).data('work-item-id');
        var importance = $(this).data('importance');
        var notes = $(this).data('notes');
        var performedAt = $(this).data('performed-at');
        
        $('#edit_work_log_id').val(id);
        $('#edit_channel_id').val(channelId).trigger('change');
        
        // Set work item after channel loads the items
        setTimeout(function() {
            $('#edit_work_item_id').val(workItemId);
        }, 500);
        
        $('#edit_importance').val(importance);
        
        // Set content to the editor
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('edit_notes')) {
            tinyMCE.get('edit_notes').setContent(notes);
        } else {
            $('#edit_notes').val(notes);
        }
        
        $('#edit_performed_at').val(performedAt);
        
        $('#edit-work-log-form').show();
        
        // Scroll to the edit form
        $('html, body').animate({
            scrollTop: $('#edit-work-log-form').offset().top - 50
        }, 500);
    });
    
    // Cancel edit
    $('.cancel-edit').on('click', function(e) {
        e.preventDefault();
        $('#edit-work-log-form').hide();
    });
    
    // View full notes
    $('.view-full-notes').on('click', function(e) {
        e.preventDefault();
        var notes = $(this).data('notes');
        $('#full-notes-content').html(notes);
        $('#notes-modal').show();
    });
    
    // Close modal
    $('.close').on('click', function() {
        $('#notes-modal').hide();
    });
    
    // Close modal when clicking outside
    $(window).on('click', function(e) {
        if ($(e.target).is('#notes-modal')) {
            $('#notes-modal').hide();
        }
    });
});
</script> 