<?php
/**
 * Name: Dashboard Columns Settings
 * Description: Choose dashboard layout columns between one, two, three, or four column arrangements to customize widget placement and improve dashboard organization and visibility
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Ultra-Wide Monitor Setup",
 *     "description": "Switch to 4-column dashboard layout on 32-inch monitors to utilize horizontal space and see all widgets without scrolling."
 *   },
 *   {
 *     "title": "Single-Column Focus",
 *     "description": "Force 1-column layout for content writers who only need to see their writing dashboard widget in a distraction-free view."
 *   },
 *   {
 *     "title": "Tablet Admin Access",
 *     "description": "Optimize dashboard to 2 columns for team members managing sites via iPad while away from desk."
 *   }
 * ]
 * Added: 2025-09-02
 * Tags: dashboard, columns, layout, screen-options, ui
 * WhereToFind: {
 *   "location": "Dashboard",
 *   "url": "",
 *   "instructions": "Select column count in module settings. Dashboard widgets automatically arrange in your chosen layout (1-4 columns).",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardDashboardColumnsSettings {
    
    public function __construct() {
        add_filter('screen_layout_columns', [$this, 'add_column_options'], 10, 2);
        add_action('admin_head-index.php', [$this, 'force_column_setting']);
        
        // Register with data registry
        $this->register_with_data_registry();
    }
    
    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_dashboard-columns-settings_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }
    
    /**
     * Render settings panel
     * 
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $columns = isset($settings['columns']) ? intval($settings['columns']) : 2;
        ?>
        <input type="hidden" name="module" value="dashboard-columns-settings">

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label" for="setting_columns"><?php esc_html_e('Number of Columns', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Choose dashboard layout columns. Widgets will automatically arrange in your selected column layout.', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_columns" id="setting_columns" class="sb-sp-select">
                <option value="1" <?php selected($columns, 1); ?>><?php esc_html_e('1 Column', 'wpswitchboard'); ?></option>
                <option value="2" <?php selected($columns, 2); ?>><?php esc_html_e('2 Columns', 'wpswitchboard'); ?></option>
                <option value="3" <?php selected($columns, 3); ?>><?php esc_html_e('3 Columns', 'wpswitchboard'); ?></option>
                <option value="4" <?php selected($columns, 4); ?>><?php esc_html_e('4 Columns', 'wpswitchboard'); ?></option>
            </select>
        </div>
        <?php
    }
    
    public function add_column_options($columns, $screen) {
        if ($screen === 'dashboard') {
            $columns['dashboard'] = 4;
        }
        return $columns;
    }
    
    public function force_column_setting() {
        $settings = get_option('switchboard_dashboard-columns-settings_settings', []);
        $column_count = isset($settings['columns']) ? intval($settings['columns']) : 2;

        // Prevent division by zero
        $column_count = max(1, min(4, $column_count));

        $width_percent = (100 / $column_count);

        ?>
        <style>
            /* Set width for visible columns */
            #dashboard-widgets .postbox-container {
                width: <?php echo esc_attr($width_percent); ?>% !important;
            }

            /* Hide columns beyond the selected count */
            <?php if ($column_count < 4): ?>
            #dashboard-widgets .postbox-container:nth-child(n+<?php echo esc_attr($column_count + 1); ?>) {
                display: none !important;
            }
            <?php endif; ?>
        </style>
        <?php

        // Move inline script to wp_add_inline_script
        wp_add_inline_script('jquery', "
            jQuery(document).ready(function($) {
                // Set column count in screen options
                $('#screen-meta-links').find('.screen-layout').remove();

                // Initialize sortable for all dashboard columns (including 3rd and 4th)
                // WordPress core only initializes sortable for default columns
                // We need to manually init for additional columns
                if ($('.meta-box-sortables').length) {
                    $('.meta-box-sortables').sortable({
                        connectWith: '.meta-box-sortables',
                        handle: '.hndle, .postbox-header',
                        cursor: 'move',
                        delay: 150,
                        distance: 2,
                        tolerance: 'pointer',
                        forcePlaceholderSize: true,
                        helper: 'clone',
                        opacity: 0.65,
                        placeholder: 'sortable-placeholder',
                        start: function(e, ui) {
                            ui.placeholder.height(ui.item.height());
                        },
                        stop: function() {
                            // Save the new widget positions
                            if (typeof postboxes !== 'undefined') {
                                postboxes.save_order(pagenow);
                            }
                        }
                    });
                }
            });
        ");
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardDashboardColumnsSettings();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
