<?php
/**
 * Dashboard View with Customizable Widget Layout
 *
 * @package Freelance_Studio
 */

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

// Get saved widget layout from user meta
$saved_layout = get_user_meta(get_current_user_id(), 'fs_dashboard_layout', true);

// Check if internal tracking is enabled
$internal_tracking_enabled = get_option('fs_internal_tracking_enabled', '0') === '1';

// Default layout configuration (widget_id => column_span)
$default_layout = array(
    'main' => array(
        array('id' => 'financial-overview', 'cols' => 2),
        array('id' => 'mini-calendar', 'cols' => 1),
        array('id' => 'week-view', 'cols' => 1),
        array('id' => 'recent-projects', 'cols' => 1),
        array('id' => 'invoices', 'cols' => 1),
        array('id' => 'tasks', 'cols' => 2),
    ),
    'sidebar' => array(
        array('id' => 'action-needed', 'cols' => 1),
        array('id' => 'timer', 'cols' => 1),
        array('id' => 'upcoming-events', 'cols' => 1),
        array('id' => 'time-goals', 'cols' => 1),
        array('id' => 'recent-sessions', 'cols' => 1),
        array('id' => 'pending-proposals', 'cols' => 1),
        array('id' => 'awaiting-signature', 'cols' => 1),
        array('id' => 'quick-actions', 'cols' => 1),
    )
);

// Add internal-tasks widget to sidebar if enabled
if ($internal_tracking_enabled) {
    // Insert after time-goals widget
    $insert_pos = 3; // After time-goals
    array_splice($default_layout['sidebar'], $insert_pos, 0, array(array('id' => 'internal-tasks', 'cols' => 1)));
}

// Use saved layout or defaults
if (empty($saved_layout) || !isset($saved_layout['main']) || !isset($saved_layout['sidebar'])) {
    $saved_layout = $default_layout;
} else {
    // All valid widget IDs
    $all_valid_widgets = array(
        'action-needed', 'financial-overview', 'mini-calendar', 'week-view', 'recent-projects', 
        'invoices', 'tasks', 'timer', 'upcoming-events', 'time-goals', 
        'recent-sessions', 'pending-proposals', 'awaiting-signature', 'quick-actions'
    );
    
    // Add internal-tasks to valid widgets if enabled
    if ($internal_tracking_enabled) {
        $all_valid_widgets[] = 'internal-tasks';
    }
    
    // Clean up saved layout: remove duplicates and invalid widgets
    $seen_widgets = array();
    $clean_main = array();
    $clean_sidebar = array();
    
    // Process main widgets - remove duplicates and invalid IDs
    foreach ($saved_layout['main'] as $widget) {
        $widget_id = is_array($widget) ? $widget['id'] : $widget;
        if (in_array($widget_id, $all_valid_widgets) && !in_array($widget_id, $seen_widgets)) {
            $seen_widgets[] = $widget_id;
            $clean_main[] = is_array($widget) ? $widget : array('id' => $widget, 'cols' => 2);
        }
    }
    
    // Process sidebar widgets - remove duplicates and invalid IDs
    foreach ($saved_layout['sidebar'] as $widget) {
        $widget_id = is_array($widget) ? $widget['id'] : $widget;
        if (in_array($widget_id, $all_valid_widgets) && !in_array($widget_id, $seen_widgets)) {
            $seen_widgets[] = $widget_id;
            $clean_sidebar[] = is_array($widget) ? $widget : array('id' => $widget, 'cols' => 1);
        }
    }
    
    // Add any missing widgets that aren't in the layout at all
    $missing_widgets = array_diff($all_valid_widgets, $seen_widgets);
    foreach ($missing_widgets as $missing_id) {
        $sidebar_widgets = array('action-needed', 'timer', 'upcoming-events', 'time-goals', 'recent-sessions', 
                                 'pending-proposals', 'awaiting-signature', 'quick-actions');
        if (in_array($missing_id, $sidebar_widgets)) {
            // Insert action-needed at the top of sidebar
            if ($missing_id === 'action-needed') {
                array_unshift($clean_sidebar, array('id' => $missing_id, 'cols' => 1));
            } else {
                $clean_sidebar[] = array('id' => $missing_id, 'cols' => 1);
            }
        } else {
            $clean_main[] = array('id' => $missing_id, 'cols' => 1);
        }
    }
    
    $saved_layout = array('main' => $clean_main, 'sidebar' => $clean_sidebar);
    
    // Save the cleaned layout back to prevent future issues
    update_user_meta(get_current_user_id(), 'fs_dashboard_layout', $saved_layout);
}

// Widget availability
$available_widgets = array(
    'action-needed' => !empty($action_items),
    'financial-overview' => true,
    'mini-calendar' => true,
    'week-view' => true,
    'recent-projects' => true,
    'invoices' => true,
    'tasks' => true,
    'timer' => true,
    'upcoming-events' => true,
    'time-goals' => ($time_goals['weekly_goal'] > 0 || $time_goals['daily_goal'] > 0),
    'recent-sessions' => !empty($recent_sessions),
    'pending-proposals' => true,
    'awaiting-signature' => true,
    'quick-actions' => true,
);

// Widget titles
$widget_titles = array(
    'action-needed' => __('Action Needed', 'freelance-studio'),
    'financial-overview' => __('Financial Overview', 'freelance-studio'),
    'mini-calendar' => __('Calendar', 'freelance-studio'),
    'week-view' => __('This Week', 'freelance-studio'),
    'recent-projects' => __('Recent Projects', 'freelance-studio'),
    'invoices' => __('Invoices', 'freelance-studio'),
    'tasks' => __('Tasks', 'freelance-studio'),
    'timer' => __('Time Tracker', 'freelance-studio'),
    'upcoming-events' => __('Upcoming Events', 'freelance-studio'),
    'time-goals' => __('Time Goals', 'freelance-studio'),
    'recent-sessions' => __('Recent Sessions', 'freelance-studio'),
    'pending-proposals' => __('Pending Proposals', 'freelance-studio'),
    'awaiting-signature' => __('Awaiting Signature', 'freelance-studio'),
    'quick-actions' => __('Quick Actions', 'freelance-studio'),
);

// Prepare data for widgets
$widget_data = compact(
    'financial_summary', 'recent_projects', 'dashboard_invoices', 'incomplete_tasks',
    'projects_dropdown', 'running_timer', 'time_goals', 'recent_sessions',
    'pending_proposals', 'unsigned_contracts', 'upcoming_events', 'calendar_data', 'week_data',
    'internal_tasks', 'action_items'
);

// Include widget renderer
include_once dirname(__FILE__) . '/widgets.php';
?>

<div class="wrap fs-wrap fs-dashboard">
    <div class="fs-dashboard-header">
        <h1><?php esc_html_e('Dashboard', 'freelance-studio'); ?></h1>
        <button type="button" class="fs-btn fs-btn-secondary fs-customize-dashboard" id="fs-toggle-customize">
            <span class="dashicons dashicons-admin-generic"></span>
            <?php esc_html_e('Customize Dashboard Layout', 'freelance-studio'); ?>
        </button>
    </div>
    
    <div class="fs-customize-notice" id="fs-customize-notice" style="display: none;">
        <span class="dashicons dashicons-info"></span>
        <?php esc_html_e('Drag widgets to reorder or move between columns. Click the expand icon to change widget width.', 'freelance-studio'); ?>
        <button type="button" class="button button-small" id="fs-reset-layout"><?php esc_html_e('Reset to Default', 'freelance-studio'); ?></button>
        <button type="button" class="button button-small button-primary" id="fs-done-customize"><?php esc_html_e('Done', 'freelance-studio'); ?></button>
    </div>
    
    <div class="fs-dashboard-grid">
        
        <!-- Main Column (2-column grid) -->
        <div class="fs-widgets-main" id="fs-main-widgets">
            <?php 
            foreach ($saved_layout['main'] as $widget):
                $widget_id = is_array($widget) ? $widget['id'] : $widget;
                $cols = is_array($widget) && isset($widget['cols']) ? $widget['cols'] : 2;
                if (!isset($available_widgets[$widget_id]) || !$available_widgets[$widget_id]) continue;
            ?>
            <div class="fs-widget fs-widget-cols-<?php echo  esc_attr( $cols ); ?>" data-widget-id="<?php echo esc_attr($widget_id); ?>" data-cols="<?php echo  esc_attr( $cols ); ?>">
                <div class="fs-widget-drag-handle">
                    <span class="dashicons dashicons-move"></span>
                    <span class="fs-widget-title"><?php echo esc_html($widget_titles[$widget_id]); ?></span>
                    <button type="button" class="fs-widget-resize" title="<?php esc_attr_e('Toggle width', 'freelance-studio'); ?>">
                        <span class="dashicons dashicons-editor-expand"></span>
                    </button>
                </div>
                <div class="fs-widget-body">
                    <?php fs_render_widget($widget_id, $widget_data); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Sidebar Column -->
        <div class="fs-widgets-sidebar" id="fs-sidebar-widgets">
            <?php 
            foreach ($saved_layout['sidebar'] as $widget):
                $widget_id = is_array($widget) ? $widget['id'] : $widget;
                $cols = 1; // Sidebar widgets are always 1 column
                if (!isset($available_widgets[$widget_id]) || !$available_widgets[$widget_id]) continue;
            ?>
            <div class="fs-widget" data-widget-id="<?php echo esc_attr($widget_id); ?>" data-cols="1">
                <div class="fs-widget-drag-handle">
                    <span class="dashicons dashicons-move"></span>
                    <span class="fs-widget-title"><?php echo esc_html($widget_titles[$widget_id]); ?></span>
                </div>
                <div class="fs-widget-body">
                    <?php fs_render_widget($widget_id, $widget_data); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
    </div>
</div>

<?php // Include Invoice Wizard Modal ?>
<?php include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/invoice-wizard-modal.php'; ?>

<?php // Include Task Modal for dashboard add task button
$task_modal_context = 'kanban';
$task_modal_projects = isset($projects_dropdown) ? $projects_dropdown : FS_Project::get_all(array('status' => array('active', 'pending')));
include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/task-modal.php';
?>

<script>
window.fsTaskModal = {
    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
    context: 'kanban',
    strings: {
        addTask: '<?php echo esc_js(__('Add Task', 'freelance-studio')); ?>',
        editTask: '<?php echo esc_js(__('Edit Task', 'freelance-studio')); ?>',
        createTask: '<?php echo esc_js(__('Add Task', 'freelance-studio')); ?>',
        updateTask: '<?php echo esc_js(__('Update Task', 'freelance-studio')); ?>',
        errorLoading: '<?php echo esc_js(__('Error loading task', 'freelance-studio')); ?>',
        errorSaving: '<?php echo esc_js(__('Error saving task', 'freelance-studio')); ?>',
        saving: '<?php echo esc_js(__('Saving...', 'freelance-studio')); ?>'
    }
};
</script>
<script>
jQuery(document).ready(function($) {
    
    // Dashboard Add Task button - open full task modal
    $('#fs-dashboard-add-task-btn').on('click', function() {
        if (typeof openTaskModal === 'function') {
            openTaskModal(null, 'pending');
        }
    });
    
    // Toggle task complete
    $(document).on('change', '.fs-toggle-task', function() {
        var $item = $(this).closest('.fs-task-item');
        var taskId = $(this).data('id');
        $item.addClass('completing');
        $.post(fs_ajax.ajax_url, {
            action: 'fs_toggle_task', nonce: fs_ajax.nonce, task_id: taskId
        }, function(r) {
            if (r.success) setTimeout(function() { $item.slideUp(300, function() { $(this).remove(); }); }, 300);
        });
    });
    
    // Inline dashboard task status change
    $(document).on('change', '.fs-dashboard-task-status', function() {
        var $select = $(this);
        var taskId = $select.data('task-id');
        var newStatus = $select.val();
        var originalStatus = $select.data('original');
        
        $select.prop('disabled', true);
        
        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_update_task_status',
                task_id: taskId,
                status: newStatus,
                nonce: fs_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    $select.data('original', newStatus);
                    $select.removeClass('task-status-' + originalStatus).addClass('task-status-' + newStatus);
                    $select.addClass('fs-status-updated');
                    setTimeout(function() { $select.removeClass('fs-status-updated'); }, 1500);
                    
                    // If completed, animate out like checkbox toggle
                    if (newStatus === 'completed') {
                        var $item = $select.closest('.fs-task-item');
                        $item.addClass('completing');
                        setTimeout(function() { $item.slideUp(300, function() { $(this).remove(); }); }, 300);
                    }
                } else {
                    alert(response.data || 'Error updating task status');
                    $select.val(originalStatus);
                }
                $select.prop('disabled', false);
            },
            error: function() {
                alert('Error updating task status');
                $select.val(originalStatus);
                $select.prop('disabled', false);
            }
        });
    });
    
    // Timer Controls - Start Timer
    $('#fs-timer-toggle').on('click', function() {
        var $btn = $(this);
        var runningTimerId = $('#fs-running-timer-id').val();
        
        $btn.prop('disabled', true);
        
        if (runningTimerId) {
            // Stop timer - include current field values
            $btn.html('<span class="dashicons dashicons-update"></span> Stopping...');
            $.post(fs_ajax.ajax_url, {
                action: 'fs_stop_timer', 
                nonce: fs_ajax.nonce, 
                entry_id: runningTimerId,
                project_id: $('#fs-timer-project').val(),
                task_id: $('#fs-timer-task').val(),
                activity: $('#fs-timer-activity').val() || 'development',
                description: $('#fs-timer-description').val()
            }, function(r) {
                if (r.success) {
                    // Notify other windows/tabs
                    try {
                        var bc = new BroadcastChannel('fs_timer_sync');
                        bc.postMessage({ type: 'timer_stopped', entry_id: runningTimerId });
                        bc.close();
                    } catch(e) {}
                    location.reload();
                }
                else {
                    alert(r.data || 'Error stopping timer');
                    $btn.prop('disabled', false).html('<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> Stop');
                }
            });
        } else {
            // Start timer
            $btn.html('<span class="dashicons dashicons-update"></span> Starting...');
            $.post(fs_ajax.ajax_url, {
                action: 'fs_start_timer', nonce: fs_ajax.nonce,
                project_id: $('#fs-timer-project').val(),
                task_id: $('#fs-timer-task').val(),
                activity: $('#fs-timer-activity').val() || 'development',
                description: $('#fs-timer-description').val()
            }, function(r) {
                if (r.success) location.reload();
                else {
                    alert(r.data || 'Error starting timer');
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-controls-play"></span> Start');
                }
            });
        }
    });
    
    // Listen for timer state changes from other windows (popup timer, other tabs)
    try {
        var fsTimerChannel = new BroadcastChannel('fs_timer_sync');
        fsTimerChannel.onmessage = function(event) {
            var type = event.data.type;
            if (type === 'timer_stopped' || type === 'timer_started' || type === 'timer_paused' || type === 'timer_resumed') {
                location.reload();
            }
        };
    } catch(e) {}
    
    // Legacy quick timer form support (fallback)
    $('#fs-quick-timer-form').on('submit', function(e) {
        e.preventDefault();
        $.post(fs_ajax.ajax_url, {
            action: 'fs_start_timer', nonce: fs_ajax.nonce,
            project_id: $('#quick-timer-project').val(),
            description: $('#quick-timer-desc').val()
        }, function(r) { if (r.success) location.reload(); });
    });
    
    function timerAction(action, btn) {
        var timerId = $('#running-timer-id, #fs-running-timer-id').val();
        if (!timerId) return;
        $(btn).prop('disabled', true);
        $.post(fs_ajax.ajax_url, {
            action: action, nonce: fs_ajax.nonce, entry_id: timerId
        }, function(r) {
            if (r.success) location.reload();
            else $(btn).prop('disabled', false);
        });
    }
    
    $('#fs-pause-timer').on('click', function() { timerAction('fs_pause_timer', this); });
    $('#fs-resume-timer').on('click', function() { timerAction('fs_resume_timer', this); });
    $('#fs-stop-timer').on('click', function() { timerAction('fs_stop_timer', this); });
    $('#fs-discard-timer').on('click', function() {
        if (confirm('Discard this time entry?')) timerAction('fs_delete_time_entry', this);
    });
    
    <?php if (!empty($running_timer)): ?>
    var timerPaused = $('#fs-timer-paused, #timer-paused').val() === '1';
    var timerStartUtc = <?php echo intval(strtotime($running_timer->start_time . ' UTC')); ?>;
    var timerPausedDuration = <?php echo intval($running_timer->paused_duration); ?>;
    if (!timerPaused) {
        var dashTimerInterval = null;
        function updateDashboardTimer() {
            var now = Math.floor(Date.now() / 1000);
            var elapsed = (now - timerStartUtc) + timerPausedDuration;
            if (elapsed < 0) elapsed = 0;
            var h = Math.floor(elapsed / 3600);
            var m = Math.floor((elapsed % 3600) / 60);
            var s = elapsed % 60;
            $('#fs-timer-display .fs-timer-hours, #timer-display .fs-timer-hours').text(String(h).padStart(2, '0'));
            $('#fs-timer-display .fs-timer-mins, #timer-display .fs-timer-mins').text(String(m).padStart(2, '0'));
            $('#fs-timer-display .fs-timer-secs, #timer-display .fs-timer-secs').text(String(s).padStart(2, '0'));
            var pct = (m * 60 + s) / 3600 * 100;
            var circ = 2 * Math.PI * 52;
            $('#timer-progress-ring').css('stroke-dashoffset', circ - (pct / 100 * circ));
        }
        updateDashboardTimer();
        dashTimerInterval = setInterval(updateDashboardTimer, 1000);
        
        // Pause/resume interval when tab visibility changes (saves energy in background)
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                if (dashTimerInterval) { clearInterval(dashTimerInterval); dashTimerInterval = null; }
            } else {
                updateDashboardTimer();
                if (!dashTimerInterval) {
                    dashTimerInterval = setInterval(updateDashboardTimer, 1000);
                }
            }
        });
    }
    <?php endif; ?>
    
    // Dashboard Customization
    var isCustomizing = false;
    
    $('#fs-toggle-customize').on('click', function() {
        isCustomizing = !isCustomizing;
        isCustomizing ? enableCustomizeMode() : disableCustomizeMode();
    });
    
    $('#fs-done-customize').on('click', function() {
        isCustomizing = false;
        disableCustomizeMode();
    });
    
    function enableCustomizeMode() {
        $('body').addClass('fs-customizing-dashboard');
        $('#fs-customize-notice').slideDown(200);
        $('#fs-toggle-customize').addClass('active');
        
        $('#fs-main-widgets, #fs-sidebar-widgets').sortable({
            items: '.fs-widget',
            handle: '.fs-widget-drag-handle',
            placeholder: 'fs-widget-placeholder',
            connectWith: '#fs-main-widgets, #fs-sidebar-widgets',
            tolerance: 'pointer',
            cursor: 'move',
            opacity: 0.8,
            revert: 150,
            start: function(e, ui) {
                ui.placeholder.addClass('fs-widget-cols-' + ui.item.data('cols'));
            },
            receive: function(e, ui) {
                // When moving to sidebar, force single column
                if ($(this).attr('id') === 'fs-sidebar-widgets') {
                    ui.item.removeClass('fs-widget-cols-2').addClass('fs-widget-cols-1').data('cols', 1);
                }
            },
            update: function(e, ui) {
                if (this === ui.item.parent()[0]) saveWidgetLayout();
            }
        });
    }
    
    function disableCustomizeMode() {
        $('body').removeClass('fs-customizing-dashboard');
        $('#fs-customize-notice').slideUp(200);
        $('#fs-toggle-customize').removeClass('active');
        if ($('#fs-main-widgets').hasClass('ui-sortable')) $('#fs-main-widgets').sortable('destroy');
        if ($('#fs-sidebar-widgets').hasClass('ui-sortable')) $('#fs-sidebar-widgets').sortable('destroy');
    }
    
    // Toggle widget width
    $(document).on('click', '.fs-widget-resize', function(e) {
        e.stopPropagation();
        var $widget = $(this).closest('.fs-widget');
        var currentCols = $widget.data('cols') || 1;
        var newCols = currentCols === 1 ? 2 : 1;
        $widget.removeClass('fs-widget-cols-1 fs-widget-cols-2')
               .addClass('fs-widget-cols-' + newCols)
               .data('cols', newCols);
        saveWidgetLayout();
    });
    
    function saveWidgetLayout() {
        var mainWidgets = [], sidebarWidgets = [];
        $('#fs-main-widgets .fs-widget').each(function() {
            mainWidgets.push({ id: $(this).data('widget-id'), cols: $(this).data('cols') || 2 });
        });
        $('#fs-sidebar-widgets .fs-widget').each(function() {
            sidebarWidgets.push({ id: $(this).data('widget-id'), cols: 1 });
        });
        $.post(fs_ajax.ajax_url, {
            action: 'fs_save_widget_layout', nonce: fs_ajax.nonce,
            layout: JSON.stringify({ main: mainWidgets, sidebar: sidebarWidgets })
        });
    }
    
    $('#fs-reset-layout').on('click', function() {
        if (confirm('Reset dashboard to default layout?')) {
            $.post(fs_ajax.ajax_url, {
                action: 'fs_reset_widget_layout', nonce: fs_ajax.nonce
            }, function() { location.reload(); });
        }
    });
    
    // Task Filter Dropdown
    $('.fs-task-filter-toggle').on('click', function(e) {
        e.stopPropagation();
        var $menu = $(this).siblings('.fs-task-filter-menu');
        $menu.toggle();
    });
    
    // Close filter dropdown when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.fs-task-filter-dropdown').length) {
            $('.fs-task-filter-menu').hide();
        }
    });
    
    // Save task filter preferences
    $('.fs-save-task-filter').on('click', function() {
        var statuses = [];
        $('.fs-task-filter-option input:checked').each(function() {
            statuses.push($(this).val());
        });
        if (statuses.length === 0) {
            alert('Please select at least one status');
            return;
        }
        $.post(fs_ajax.ajax_url, {
            action: 'fs_save_task_widget_filter',
            nonce: fs_ajax.nonce,
            statuses: statuses
        }, function(r) {
            if (r.success) location.reload();
        });
    });
    // Save task display limit
    $('#fs-task-limit-select').on('change', function() {
        var limit = $(this).val();
        $.post(fs_ajax.ajax_url, {
            action: 'fs_save_task_widget_limit',
            nonce: fs_ajax.nonce,
            limit: limit
        }, function(r) {
            if (r.success) location.reload();
        });
    });
    // Toggle imported calendar events in week widget
    $(document).on('change', '#fs-toggle-external-events', function() {
        var show = $(this).is(':checked') ? 1 : 0;
        $.post(fs_ajax.ajax_url, {
            action: 'fs_toggle_week_external_events',
            nonce: fs_ajax.nonce,
            show: show
        }, function(r) {
            if (r.success) location.reload();
        });
    });
});
</script>
