<?php
/**
 * Workflow Management Page
 */

defined('ABSPATH') || exit;



// WordPress functions are always available in proper WordPress environment

// Ensure settings are loaded
if (!isset($settings)) {
    if (class_exists('KDSAMREF_Admin')) {
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
    } else {
        $settings = array();
    }
}

// Ensure admin object is available for JavaScript
if (!isset($admin) && class_exists('KDSAMREF_Admin')) {
    $admin = new KDSAMREF_Admin();
}

// Helper function to get status display data
function get_status_display_data($status_slug, $settings) {
    $display_data = array(
        'label' => $status_slug,
        'color' => '#007cba',
        'is_custom' => false
    );
    
    // 1. Check custom statuses from settings (highest priority)
    $custom_statuses = $settings['custom_statuses'] ?? array();
    if (isset($custom_statuses[$status_slug])) {
        $display_data['label'] = $custom_statuses[$status_slug]['label'];
        $display_data['color'] = $custom_statuses[$status_slug]['color'] ?? '#007cba';
        $display_data['is_custom'] = true;
        return $display_data;
    }
    
    // 2. Check Orderable Pro custom statuses
    $orderable_helper_class = 'Orderable_Custom_Order_Status_Pro_Helper';
    if (class_exists($orderable_helper_class)) {
        try {
            if (method_exists($orderable_helper_class, 'get_custom_order_statuses')) {
                $orderable_custom_statuses = call_user_func(array($orderable_helper_class, 'get_custom_order_statuses'));
                if (!empty($orderable_custom_statuses)) {
                    foreach ($orderable_custom_statuses as $status) {
                        if (is_object($status) && isset($status->post_name) && $status->post_name === $status_slug) {
                            $display_data['label'] = $status->post_title;
                            $display_data['color'] = $status->data['color'] ?? '#007cba';
                            $display_data['is_custom'] = true;
                            return $display_data;
                        }
                    }
                }
            }
        } catch (Exception $e) {
            // Silent fail
        }
    }
    
    // 3. Check WooCommerce default statuses
    $wc_statuses = wc_get_order_statuses();
    if (isset($wc_statuses[$status_slug])) {
        $display_data['label'] = $wc_statuses[$status_slug];
        return $display_data;
    }
    if (isset($wc_statuses['wc-' . $status_slug])) {
        $display_data['label'] = $wc_statuses['wc-' . $status_slug];
        return $display_data;
    }
    
    // 4. Fallback: capitalize the slug
    $display_data['label'] = ucfirst(str_replace('-', ' ', $status_slug));
    return $display_data;
}
?>

<!-- CSS and JS are loaded via WordPress hooks -->

<div class="wrap kdsamref-workflow-page">
    <div class="kdsamref-workflow-container">
        <!-- Header -->
        <div class="kdsamref-page-header">
            <div class="kdsamref-header-content">
                <h1><?php esc_html_e('Workflow Management', 'kds-report-for-orderable'); ?></h1>
                <p><?php esc_html_e('Define the order of your order statuses to create a custom workflow', 'kds-report-for-orderable'); ?></p>
            </div>
        </div>

        <div class="kdsamref-workflow-content">
            <!-- Workflow Steps -->
            <div class="kdsamref-workflow-section">
                <div class="kdsamref-section-header">
                    <div class="kdsamref-header-left">
                        <h3><?php esc_html_e('Workflow Steps', 'kds-report-for-orderable'); ?></h3>
                        <span class="kdsamref-section-description"><?php esc_html_e('Drag and drop to reorder steps. First step is always "Processing" and last step is always "Completed".', 'kds-report-for-orderable'); ?></span>
                    </div>
                    <div class="kdsamref-header-right">
                        <button type="button" onclick="addWorkflowStep()" class="kdsamref-add-step-btn">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <line x1="12" y1="5" x2="12" y2="19"></line>
                                <line x1="5" y1="12" x2="19" y2="12"></line>
                            </svg>
                            <?php esc_html_e('Add Step', 'kds-report-for-orderable'); ?>
                        </button>
                    </div>
                </div>
                
                <form method="post" action="<?php echo esc_url(sanitize_url($_SERVER['REQUEST_URI'] ?? '')); ?>" class="kdsamref-workflow-form">
                    <?php wp_nonce_field('kdsamref_workflow', '_wpnonce'); ?>
                    
                    <div class="kdsamref-workflow-steps" id="kdsamref-workflow-steps">
                        <?php 
                        $workflow_steps = $settings['workflow_steps'] ?? array('processing', 'completed');
                        // Normalize any stored values starting with wc-
                        $workflow_steps = array_map(function($s){ return (strpos($s, 'wc-') === 0) ? substr($s, 3) : $s; }, $workflow_steps);
                        
                        // Ensure first step is always 'processing' and last step is always 'completed'
                        if (empty($workflow_steps) || $workflow_steps[0] !== 'processing') {
                            $workflow_steps = array_merge(['processing'], array_filter($workflow_steps, function($step) { return $step !== 'processing' && $step !== 'completed'; }));
                        }
                        if (end($workflow_steps) !== 'completed') {
                            $workflow_steps = array_merge(array_filter($workflow_steps, function($step) { return $step !== 'completed'; }), ['completed']);
                        }
                        
                        foreach ($workflow_steps as $index => $step): 
                            $step_data = get_status_display_data($step, $settings);
                        ?>
                            <div class="kdsamref-workflow-step" data-step="<?php echo esc_attr($index); ?>">
                                <?php if ($index > 0 && $index < count($workflow_steps) - 1): ?>
                                    <div class="kdsamref-step-drag-handle">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <circle cx="8" cy="8" r="1"></circle>
                                            <circle cx="16" cy="8" r="1"></circle>
                                            <circle cx="8" cy="16" r="1"></circle>
                                            <circle cx="16" cy="16" r="1"></circle>
                                        </svg>
                                    </div>
                                <?php endif; ?>
                                <div class="kdsamref-step-number"><?php echo esc_html($index + 1); ?></div>
                                <div class="kdsamref-step-content">
                                    <?php if ($index === 0): ?>
                                        <!-- First step: Always processing -->
                                        <div class="kdsamref-step-select-wrapper">
                                            <div class="kdsamref-step-display">
                                                <div class="kdsamref-step-status-info">
                                                    <div class="kdsamref-step-status-name" style="--status-color: <?php echo esc_attr($step_data['color']); ?>">
                                                        <?php echo esc_html($step_data['label']); ?>
                                                    </div>
                                                    <div class="kdsamref-step-status-slug"><?php echo esc_html($step); ?></div>
                                                </div>
                                                <div class="kdsamref-step-color-indicator" style="--status-color: <?php echo esc_attr($step_data['color']); ?>"></div>
                                            </div>
                                            <div class="kdsamref-step-badge kdsamref-step-badge-processing"><?php esc_html_e('Fixed', 'kds-report-for-orderable'); ?></div>
                                        </div>
                                        <input type="hidden" name="kdsamref_settings[workflow_steps][]" value="processing" />
                                    <?php elseif ($index === count($workflow_steps) - 1): ?>
                                        <!-- Last step: Always completed -->
                                        <div class="kdsamref-step-select-wrapper">
                                            <div class="kdsamref-step-display">
                                                <div class="kdsamref-step-status-info">
                                                    <div class="kdsamref-step-status-name" style="--status-color: <?php echo esc_attr($step_data['color']); ?>">
                                                        <?php echo esc_html($step_data['label']); ?>
                                                    </div>
                                                    <div class="kdsamref-step-status-slug"><?php echo esc_html($step); ?></div>
                                                </div>
                                                <div class="kdsamref-step-color-indicator" style="--status-color: <?php echo esc_attr($step_data['color']); ?>"></div>
                                            </div>
                                            <div class="kdsamref-step-badge kdsamref-step-badge-completed"><?php esc_html_e('Fixed', 'kds-report-for-orderable'); ?></div>
                                        </div>
                                        <input type="hidden" name="kdsamref_settings[workflow_steps][]" value="completed" />
                                    <?php else: ?>
                                        <!-- Middle steps: User can select -->
                                        <div class="kdsamref-step-select-wrapper">
                                            <select name="kdsamref_settings[workflow_steps][]" class="kdsamref-step-select" onchange="updateStepDisplayFromSelect(this)">
                                                <option value=""><?php esc_html_e('Select a status...', 'kds-report-for-orderable'); ?></option>
                                                <?php 
                                                // Collect all available statuses without duplicates
                                                $all_statuses = array();
                                                $added_statuses = array();
                                                
                                                // 1. Add WooCommerce order statuses
                                                $wc_statuses = wc_get_order_statuses();
                                                foreach ($wc_statuses as $status_slug => $status_name) {
                                                    $clean_slug = (strpos($status_slug, 'wc-') === 0) ? substr($status_slug, 3) : $status_slug;
                                                    if (!in_array($clean_slug, $added_statuses)) {
                                                        $all_statuses[$clean_slug] = $status_name;
                                                        $added_statuses[] = $clean_slug;
                                                    }
                                                }
                                                
                                                // 2. Add custom statuses from settings
                                                $custom_statuses = $settings['custom_statuses'] ?? array();
                                                foreach ($custom_statuses as $slug => $status_data) {
                                                    if (!in_array($slug, $added_statuses)) {
                                                        $all_statuses[$slug] = $status_data['label'];
                                                        $added_statuses[] = $slug;
                                                    }
                                                }
                                                
                                                // 3. Add Orderable Pro custom statuses
                                                $orderable_helper_class = 'Orderable_Custom_Order_Status_Pro_Helper';
                                                if (class_exists($orderable_helper_class)) {
                                                    try {
                                                        if (method_exists($orderable_helper_class, 'get_custom_order_statuses')) {
                                                            $orderable_custom_statuses = call_user_func(array($orderable_helper_class, 'get_custom_order_statuses'));
                                                            if (!empty($orderable_custom_statuses)) {
                                                                foreach ($orderable_custom_statuses as $status) {
                                                                    if (is_object($status) && isset($status->post_name) && isset($status->post_title)) {
                                                                        $status_slug = $status->post_name;
                                                                        $status_title = $status->post_title;
                                                                        
                                                                        // Skip if already added
                                                                        if (!in_array($status_slug, $added_statuses)) {
                                                                            $all_statuses[$status_slug] = $status_title;
                                                                            $added_statuses[] = $status_slug;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception $e) {
                                                        // Silent fail
                                                    }
                                                }
                                                
                                                // Display all collected statuses
                                                foreach ($all_statuses as $status_slug => $status_name): 
                                                    $status_data = get_status_display_data($status_slug, $settings);
                                                ?>
                                                    <option value="<?php echo esc_attr($status_slug); ?>" <?php selected($step, $status_slug); ?> data-color="<?php echo esc_attr($status_data['color']); ?>">
                                                        <?php echo esc_html($status_data['label']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <button type="button" class="kdsamref-step-remove-btn" onclick="removeWorkflowStep(this)" <?php echo ($index === 0 || $index === count($workflow_steps) - 1) ? 'disabled' : ''; ?>>
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <line x1="18" y1="6" x2="6" y2="18"></line>
                                        <line x1="6" y1="6" x2="18" y2="18"></line>
                                    </svg>
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="kdsamref-workflow-actions">
                        <button type="submit" name="submit" class="kdsamref-save-btn">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                                <polyline points="17,21 17,13 7,13 7,21"></polyline>
                                <polyline points="7,3 7,8 15,8"></polyline>
                            </svg>
                            <?php esc_html_e('Save Workflow', 'kds-report-for-orderable'); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<?php 
// Use WordPress bundled Sortable if available, otherwise load from assets
if (wp_script_is('jquery-ui-sortable', 'registered')) {
    wp_enqueue_script('jquery-ui-sortable');
} else {
    // Fallback: Use simple drag and drop without external library
    echo '<!-- Using simple drag and drop instead of external library -->';
}
?>
