<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class BLM_Settings {

    public static function add_menu() {
        add_management_page(
            'Business Listing',
            'Business Listing',
            'manage_options',
            'blm-settings',
            array( __CLASS__, 'render_page' )
        );
    }

    public static function render_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Handle save
        if ( isset( $_POST['blm_save_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['blm_save_nonce'] ) ), 'blm_save_settings' ) ) {
            self::save_settings();
        }

        // Handle connect
        if ( isset( $_POST['blm_connect_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['blm_connect_nonce'] ) ), 'blm_connect' ) ) {
            $api_key = isset( $_POST['blm_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['blm_api_key'] ) ) : '';
            if ( ! empty( $api_key ) ) {
                BLM_Connection::connect( $api_key );
            }
        }

        // Handle disconnect
        if ( isset( $_POST['blm_disconnect_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['blm_disconnect_nonce'] ) ), 'blm_disconnect' ) ) {
            BLM_Connection::disconnect();
        }

        $data        = get_option( 'blm_business_data', array() );
        $connected   = BLM_Connection::is_connected();
        $types       = BLM_Business_Types::get_types();
        $categories  = BLM_Business_Types::get_categories();
        $grouped     = BLM_Business_Types::get_types_grouped_by_category();
        $current_type = isset( $data['business_type'] ) ? $data['business_type'] : 'local_business';
        $current_category = isset( $types[ $current_type ]['category'] ) ? $types[ $current_type ]['category'] : 'General';

        $days = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );

        $social_fields = array(
            'facebook'  => 'Facebook URL',
            'twitter'   => 'X (Twitter) URL',
            'instagram' => 'Instagram URL',
            'linkedin'  => 'LinkedIn URL',
            'youtube'   => 'YouTube URL',
            'yelp'      => 'Yelp URL',
        );

        ?>
        <div class="wrap blm-settings-wrap">
            <h1>Business Listing</h1>

            <!-- Instructions Panel -->
            <div class="blm-instructions-panel">
                <button type="button" class="blm-instructions-toggle" id="blm-instructions-toggle">
                    <span class="dashicons dashicons-info"></span>
                    Shortcodes &amp; Widgets
                    <span class="dashicons dashicons-arrow-down-alt2 blm-toggle-icon"></span>
                </button>
                <div class="blm-instructions-content" id="blm-instructions-content" style="display: none;">
                    <h3>Business Hours Widget</h3>
                    <p>Go to <strong>Appearance &rarr; Widgets</strong> and add the "Business Hours" widget to any sidebar or widget area.</p>

                    <h3>Business Hours Shortcode</h3>
                    <p>Use the <code>[business_hours]</code> shortcode to display your business hours anywhere in your content.</p>

                    <h4>Shortcode Options</h4>
                    <table class="blm-shortcode-table">
                        <thead>
                            <tr>
                                <th>Attribute</th>
                                <th>Values</th>
                                <th>Default</th>
                                <th>Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><code>show_closed</code></td>
                                <td><code>yes</code> / <code>no</code></td>
                                <td><code>yes</code></td>
                                <td>Show or hide days when you're closed</td>
                            </tr>
                            <tr>
                                <td><code>highlight_today</code></td>
                                <td><code>yes</code> / <code>no</code></td>
                                <td><code>yes</code></td>
                                <td>Highlight the current day</td>
                            </tr>
                            <tr>
                                <td><code>time_format</code></td>
                                <td><code>12</code> / <code>24</code></td>
                                <td><code>12</code></td>
                                <td>12-hour (9:00 AM) or 24-hour (09:00) format</td>
                            </tr>
                            <tr>
                                <td><code>class</code></td>
                                <td>CSS class name</td>
                                <td><em>none</em></td>
                                <td>Add custom CSS class for styling</td>
                            </tr>
                        </tbody>
                    </table>

                    <h4>Examples</h4>
                    <div class="blm-code-examples">
                        <p><strong>Basic usage:</strong></p>
                        <code>[business_hours]</code>

                        <p><strong>Hide closed days:</strong></p>
                        <code>[business_hours show_closed="no"]</code>

                        <p><strong>24-hour format without highlighting today:</strong></p>
                        <code>[business_hours time_format="24" highlight_today="no"]</code>

                        <p><strong>Card-style layout:</strong></p>
                        <code>[business_hours class="blm-hours-card"]</code>

                        <p><strong>Compact layout:</strong></p>
                        <code>[business_hours class="blm-hours-compact"]</code>
                    </div>

                    <h4>Built-in Style Classes</h4>
                    <ul>
                        <li><code>blm-hours-card</code> &mdash; Adds a bordered card with shadow</li>
                        <li><code>blm-hours-compact</code> &mdash; Reduces padding for tighter layouts</li>
                    </ul>
                </div>
            </div>

            <!-- Connection Status Banner -->
            <div class="blm-connection-banner <?php echo $connected ? 'blm-connected' : 'blm-disconnected'; ?>">
                <?php if ( $connected ) : ?>
                    <span class="blm-status-indicator"></span>
                    <strong>Connected to WHMCS</strong>
                    <span class="blm-last-updated">Last updated: <?php echo esc_html( BLM_Connection::get_last_updated() ); ?></span>
                    <form method="post" class="blm-connection-form" style="display:inline;">
                        <?php wp_nonce_field( 'blm_disconnect', 'blm_disconnect_nonce' ); ?>
                        <button type="submit" class="button blm-disconnect-btn">Disconnect</button>
                    </form>
                    <p class="description" style="margin-top: 8px;">
                        <strong>Note:</strong> Changes saved here can be pulled into WHMCS using the "Pull from Site" button in the WHMCS admin or client area.
                    </p>
                <?php else : ?>
                    <span class="blm-status-indicator"></span>
                    <strong>Not Connected</strong>
                    <form method="post" class="blm-connection-form" style="display:inline;">
                        <?php wp_nonce_field( 'blm_connect', 'blm_connect_nonce' ); ?>
                        <input type="text" name="blm_api_key" placeholder="Enter API Key" class="blm-api-key-input" />
                        <button type="submit" class="button button-primary">Connect</button>
                    </form>
                <?php endif; ?>
            </div>

            <!-- Settings Form -->
            <form method="post" id="blm-settings-form">
                <?php wp_nonce_field( 'blm_save_settings', 'blm_save_nonce' ); ?>

                <!-- Base Fields -->
                <div class="blm-section">
                    <h2>Business Information</h2>
                    <table class="form-table">
                        <tr>
                            <th>
                                <label for="blm_business_name">Business Name</label>
                                <span class="blm-tooltip" data-tip="The official name of your business as it appears on legal documents and signage. This will be displayed in search results and maps.">?</span>
                            </th>
                            <td><input type="text" id="blm_business_name" name="blm[business_name]" value="<?php echo esc_attr( isset( $data['business_name'] ) ? $data['business_name'] : '' ); ?>" class="regular-text blm-field"  /></td>
                        </tr>
                        <tr>
                            <th>
                                <label for="blm_business_category">Business Category</label>
                                <span class="blm-tooltip" data-tip="Select the general industry or category that best describes your business. This helps filter the available business types.">?</span>
                            </th>
                            <td>
                                <select id="blm_business_category" class="blm-field" >
                                    <?php foreach ( $categories as $cat ) : ?>
                                        <option value="<?php echo esc_attr( $cat ); ?>" <?php selected( $current_category, $cat ); ?>><?php echo esc_html( $cat ); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th>
                                <label for="blm_business_type">Business Type</label>
                                <span class="blm-tooltip" data-tip="Choose the specific Schema.org type that best matches your business. This determines how search engines categorize and display your business information.">?</span>
                            </th>
                            <td>
                                <select id="blm_business_type" name="blm[business_type]" class="blm-field" >
                                    <?php foreach ( $grouped[ $current_category ] as $key => $type ) : ?>
                                        <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $current_type, $key ); ?>><?php echo esc_html( $type['label'] ); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <script>
                                    var blmTypesGrouped = <?php echo wp_json_encode( $grouped ); ?>;
                                </script>
                            </td>
                        </tr>
                        <tr>
                            <th>
                                <label for="blm_description">Business Description</label>
                                <span class="blm-tooltip" data-tip="A brief summary of your business, products, or services. Keep it concise (1-2 paragraphs) and include relevant keywords naturally.">?</span>
                            </th>
                            <td><textarea id="blm_description" name="blm[description]" rows="4" class="large-text blm-field" ><?php echo esc_textarea( isset( $data['description'] ) ? $data['description'] : '' ); ?></textarea></td>
                        </tr>
                    </table>

                    <h3>Address <span class="blm-tooltip" data-tip="Enter your business's physical location. This address will appear in search results, maps, and helps customers find you.">?</span></h3>
                    <div class="blm-field-grid">
                        <div class="blm-field-group">
                            <label for="blm_address">Street Address</label>
                            <input type="text" id="blm_address" name="blm[address]" value="<?php echo esc_attr( isset( $data['address'] ) ? $data['address'] : '' ); ?>" class="regular-text blm-field"  />
                        </div>
                        <div class="blm-field-group">
                            <label for="blm_city">City</label>
                            <input type="text" id="blm_city" name="blm[city]" value="<?php echo esc_attr( isset( $data['city'] ) ? $data['city'] : '' ); ?>" class="regular-text blm-field"  />
                        </div>
                        <div class="blm-field-group">
                            <label for="blm_state">State / Province</label>
                            <input type="text" id="blm_state" name="blm[state]" value="<?php echo esc_attr( isset( $data['state'] ) ? $data['state'] : '' ); ?>" class="regular-text blm-field" list="blm-states-list" placeholder="e.g., CA"  />
                            <datalist id="blm-states-list">
                                <?php
                                $us_states = array( 'AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY' );
                                foreach ( $us_states as $st ) :
                                ?>
                                    <option value="<?php echo esc_attr( $st ); ?>">
                                <?php endforeach; ?>
                            </datalist>
                        </div>
                        <div class="blm-field-group">
                            <label for="blm_postal_code">Postal Code</label>
                            <input type="text" id="blm_postal_code" name="blm[postal_code]" value="<?php echo esc_attr( isset( $data['postal_code'] ) ? $data['postal_code'] : '' ); ?>" class="regular-text blm-field" placeholder="e.g., 90210"  />
                        </div>
                        <div class="blm-field-group">
                            <label for="blm_country">Country</label>
                            <?php
                            $country_val = isset( $data['country'] ) ? $data['country'] : 'United States';
                            $countries = array(
                                'United States', 'Canada', 'United Kingdom', 'Australia',
                                'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Austria', 'Azerbaijan',
                                'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi',
                                'Cabo Verde', 'Cambodia', 'Cameroon', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Costa Rica', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic',
                                'Democratic Republic of the Congo', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic',
                                'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia',
                                'Fiji', 'Finland', 'France',
                                'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana',
                                'Haiti', 'Honduras', 'Hungary',
                                'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Ivory Coast',
                                'Jamaica', 'Japan', 'Jordan',
                                'Kazakhstan', 'Kenya', 'Kiribati', 'Kuwait', 'Kyrgyzstan',
                                'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg',
                                'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Myanmar',
                                'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'North Korea', 'North Macedonia', 'Norway',
                                'Oman',
                                'Pakistan', 'Palau', 'Palestine', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal',
                                'Qatar',
                                'Romania', 'Russia', 'Rwanda',
                                'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Korea', 'South Sudan', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria',
                                'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu',
                                'Uganda', 'Ukraine', 'United Arab Emirates', 'Uruguay', 'Uzbekistan',
                                'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam',
                                'Yemen',
                                'Zambia', 'Zimbabwe',
                            );
                            ?>
                            <select id="blm_country" name="blm[country]" class="regular-text blm-field" >
                                <?php foreach ( $countries as $c ) : ?>
                                    <option value="<?php echo esc_attr( $c ); ?>" <?php selected( $country_val, $c ); ?>><?php echo esc_html( $c ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <h3>Contact</h3>
                    <table class="form-table">
                        <tr>
                            <th>
                                <label for="blm_phone">Phone</label>
                                <span class="blm-tooltip" data-tip="Your primary business phone number. Include area code. This number will be clickable on mobile devices.">?</span>
                            </th>
                            <td><input type="tel" id="blm_phone" name="blm[phone]" value="<?php echo esc_attr( isset( $data['phone'] ) ? $data['phone'] : '' ); ?>" class="regular-text blm-field" placeholder="(555) 123-4567"  /></td>
                        </tr>
                        <tr>
                            <th>
                                <label for="blm_email">Email</label>
                                <span class="blm-tooltip" data-tip="Your primary business contact email address. Use a professional email that you check regularly.">?</span>
                            </th>
                            <td><input type="email" id="blm_email" name="blm[email]" value="<?php echo esc_attr( isset( $data['email'] ) ? $data['email'] : '' ); ?>" class="regular-text blm-field"  /></td>
                        </tr>
                        <tr>
                            <th>
                                <label for="blm_website">Website</label>
                                <span class="blm-tooltip" data-tip="Your business website URL. Include the full address starting with https:// for secure sites.">?</span>
                            </th>
                            <td><input type="url" id="blm_website" name="blm[website]" value="<?php echo esc_attr( isset( $data['website'] ) ? $data['website'] : '' ); ?>" class="regular-text blm-field"  /></td>
                        </tr>
                        <tr>
                            <th>
                                <label for="blm_logo">Logo URL</label>
                                <span class="blm-tooltip" data-tip="URL to your business logo image. Recommended: square image, minimum 112x112 pixels. PNG or JPG format.">?</span>
                            </th>
                            <td>
                                <input type="text" id="blm_logo" name="blm[logo]" value="<?php echo esc_attr( isset( $data['logo'] ) ? $data['logo'] : '' ); ?>" class="regular-text blm-field"  />
                                <?php if ( ! $connected ) : ?>
                                    <button type="button" class="button blm-upload-logo" id="blm-upload-logo-btn">Upload</button>
                                <?php endif; ?>
                                <?php if ( ! empty( $data['logo'] ) ) : ?>
                                    <div class="blm-logo-preview"><img src="<?php echo esc_url( $data['logo'] ); ?>" alt="Logo preview" style="max-height:60px;margin-top:8px;" /></div>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th>
                                <label for="blm_price_range">Price Range</label>
                                <span class="blm-tooltip" data-tip="Indicates the general price level of your products or services. Helps customers understand what to expect.">?</span>
                            </th>
                            <td>
                                <select id="blm_price_range" name="blm[price_range]" class="blm-field" >
                                    <option value="">-- Select --</option>
                                    <option value="$" <?php selected( isset( $data['price_range'] ) ? $data['price_range'] : '', '$' ); ?>>$ (Budget)</option>
                                    <option value="$$" <?php selected( isset( $data['price_range'] ) ? $data['price_range'] : '', '$$' ); ?>>$$ (Moderate)</option>
                                    <option value="$$$" <?php selected( isset( $data['price_range'] ) ? $data['price_range'] : '', '$$$' ); ?>>$$$ (Upscale)</option>
                                    <option value="$$$$" <?php selected( isset( $data['price_range'] ) ? $data['price_range'] : '', '$$$$' ); ?>>$$$$ (Fine Dining / Luxury)</option>
                                </select>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- Hours of Operation -->
                <div class="blm-section">
                    <h2>Hours of Operation <span class="blm-tooltip" data-tip="Set your regular business hours. Check the days you're open and specify opening/closing times. Use 'Open 24/7' if you never close.">?</span></h2>
                    <div class="blm-hours-toggle">
                        <label>
                            <input type="checkbox" id="blm_open_247" name="blm[open_247]" value="1" <?php checked( ! empty( $data['open_247'] ) ); ?>  />
                            Open 24/7
                        </label>
                    </div>
                    <div class="blm-hours-table" id="blm-hours-table">
                        <?php foreach ( $days as $day ) :
                            $day_data = isset( $data['hours'][ $day ] ) ? $data['hours'][ $day ] : array();
                            $is_open  = isset( $day_data['open'] ) ? $day_data['open'] : '';
                            $open_time  = isset( $day_data['open_time'] ) ? $day_data['open_time'] : '09:00';
                            $close_time = isset( $day_data['close_time'] ) ? $day_data['close_time'] : '17:00';
                        ?>
                        <div class="blm-hours-row">
                            <label class="blm-day-label"><?php echo esc_html( ucfirst( $day ) ); ?></label>
                            <label class="blm-day-toggle">
                                <input type="checkbox" class="blm-day-open" name="blm[hours][<?php echo esc_attr( $day ); ?>][open]" value="1" <?php checked( $is_open, '1' ); ?>  />
                                Open
                            </label>
                            <span class="blm-time-fields">
                                <input type="time" name="blm[hours][<?php echo esc_attr( $day ); ?>][open_time]" value="<?php echo esc_attr( $open_time ); ?>" class="blm-field"  />
                                <span class="blm-time-sep">to</span>
                                <input type="time" name="blm[hours][<?php echo esc_attr( $day ); ?>][close_time]" value="<?php echo esc_attr( $close_time ); ?>" class="blm-field"  />
                            </span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Social Profiles -->
                <div class="blm-section">
                    <h2>Social Profiles <span class="blm-tooltip" data-tip="Link your official social media profiles. These help establish your online presence and appear in search knowledge panels.">?</span></h2>
                    <table class="form-table">
                        <?php foreach ( $social_fields as $social_key => $social_label ) : ?>
                        <tr>
                            <th><label for="blm_social_<?php echo esc_attr( $social_key ); ?>"><?php echo esc_html( $social_label ); ?></label></th>
                            <td><input type="url" id="blm_social_<?php echo esc_attr( $social_key ); ?>" name="blm[social][<?php echo esc_attr( $social_key ); ?>]" value="<?php echo esc_attr( isset( $data['social'][ $social_key ] ) ? $data['social'][ $social_key ] : '' ); ?>" class="regular-text blm-field"  /></td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>

                <!-- Type-Specific Fields -->
                <?php foreach ( $types as $type_key => $type_info ) :
                    if ( empty( $type_info['additional_fields'] ) ) {
                        continue;
                    }
                ?>
                <div class="blm-section blm-type-fields" data-type="<?php echo esc_attr( $type_key ); ?>" style="<?php echo ( $type_key !== $current_type ) ? 'display:none;' : ''; ?>">
                    <h2><?php echo esc_html( $type_info['label'] ); ?> Settings</h2>
                    <table class="form-table">
                        <?php foreach ( $type_info['additional_fields'] as $field ) :
                            $field_value = isset( $data['type_fields'][ $field['key'] ] ) ? $data['type_fields'][ $field['key'] ] : '';
                        ?>
                        <tr>
                            <th>
                                <label for="blm_tf_<?php echo esc_attr( $field['key'] ); ?>"><?php echo esc_html( $field['label'] ); ?></label>
                                <?php if ( ! empty( $field['help'] ) ) : ?>
                                    <span class="blm-tooltip" data-tip="<?php echo esc_attr( $field['help'] ); ?>">?</span>
                                <?php endif; ?>
                            </th>
                            <td>
                                <?php if ( 'textarea' === $field['type'] ) : ?>
                                    <textarea id="blm_tf_<?php echo esc_attr( $field['key'] ); ?>" name="blm[type_fields][<?php echo esc_attr( $field['key'] ); ?>]" rows="3" class="large-text blm-field" ><?php echo esc_textarea( $field_value ); ?></textarea>
                                <?php elseif ( 'select' === $field['type'] ) : ?>
                                    <select id="blm_tf_<?php echo esc_attr( $field['key'] ); ?>" name="blm[type_fields][<?php echo esc_attr( $field['key'] ); ?>]" class="blm-field" >
                                        <option value="">-- Select --</option>
                                        <?php foreach ( $field['options'] as $opt ) : ?>
                                            <option value="<?php echo esc_attr( $opt ); ?>" <?php selected( $field_value, $opt ); ?>><?php echo esc_html( $opt ); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php elseif ( 'checkbox' === $field['type'] ) : ?>
                                    <label>
                                        <input type="checkbox" id="blm_tf_<?php echo esc_attr( $field['key'] ); ?>" name="blm[type_fields][<?php echo esc_attr( $field['key'] ); ?>]" value="1" <?php checked( $field_value, '1' ); ?> class="blm-field"  />
                                        Yes
                                    </label>
                                <?php elseif ( 'checkboxes' === $field['type'] ) : ?>
                                    <fieldset>
                                        <?php
                                        $selected_values = is_array( $field_value ) ? $field_value : array();
                                        foreach ( $field['options'] as $opt ) : ?>
                                            <label style="display:inline-block;margin-right:12px;">
                                                <input type="checkbox" name="blm[type_fields][<?php echo esc_attr( $field['key'] ); ?>][]" value="<?php echo esc_attr( $opt ); ?>" <?php checked( in_array( $opt, $selected_values, true ) ); ?> class="blm-field"  />
                                                <?php echo esc_html( $opt ); ?>
                                            </label>
                                        <?php endforeach; ?>
                                    </fieldset>
                                <?php else : ?>
                                    <input type="text" id="blm_tf_<?php echo esc_attr( $field['key'] ); ?>" name="blm[type_fields][<?php echo esc_attr( $field['key'] ); ?>]" value="<?php echo esc_attr( $field_value ); ?>" class="regular-text blm-field"  />
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
                <?php endforeach; ?>

                <!-- Schema Preview -->
                <div class="blm-section">
                    <h2>
                        <button type="button" class="blm-toggle-preview" id="blm-toggle-preview">Schema Preview <span class="dashicons dashicons-arrow-down-alt2"></span></button>
                    </h2>
                    <div class="blm-schema-preview" id="blm-schema-preview" style="display:none;">
                        <pre id="blm-schema-output"></pre>
                    </div>
                </div>

                <?php if ( $connected ) : ?>
                    <div class="blm-save-warning" style="background: #fff3cd; border: 1px solid #ffc107; padding: 12px; margin-bottom: 16px; border-radius: 4px;">
                        <strong>Connected to WHMCS:</strong> Changes saved here will be stored locally. Use "Pull from Site" in WHMCS to sync these changes to your WHMCS account.
                    </div>
                <?php endif; ?>
                <?php submit_button( 'Save Settings' ); ?>
            </form>
        </div>
        <?php
    }

    private static function save_settings() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Nonce already verified in render_page() before calling this method.
        $input = isset( $_POST['blm'] ) ? wp_unslash( $_POST['blm'] ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $data  = array();

        // Base fields
        $data['business_name'] = sanitize_text_field( isset( $input['business_name'] ) ? $input['business_name'] : '' );
        $data['business_type'] = sanitize_key( isset( $input['business_type'] ) ? $input['business_type'] : 'local_business' );
        $data['description']   = sanitize_textarea_field( isset( $input['description'] ) ? $input['description'] : '' );
        $data['address']       = sanitize_text_field( isset( $input['address'] ) ? $input['address'] : '' );
        $data['city']          = sanitize_text_field( isset( $input['city'] ) ? $input['city'] : '' );
        $data['state']         = sanitize_text_field( isset( $input['state'] ) ? $input['state'] : '' );
        $data['postal_code']   = sanitize_text_field( isset( $input['postal_code'] ) ? $input['postal_code'] : '' );
        $data['country']       = sanitize_text_field( isset( $input['country'] ) ? $input['country'] : '' );
        $data['phone']         = sanitize_text_field( isset( $input['phone'] ) ? $input['phone'] : '' );
        $data['email']         = sanitize_email( isset( $input['email'] ) ? $input['email'] : '' );
        $data['website']       = esc_url_raw( isset( $input['website'] ) ? $input['website'] : '' );
        $data['logo']          = esc_url_raw( isset( $input['logo'] ) ? $input['logo'] : '' );
        $data['price_range']   = sanitize_text_field( isset( $input['price_range'] ) ? $input['price_range'] : '' );

        // Hours
        $data['open_247'] = ! empty( $input['open_247'] ) ? '1' : '';
        $data['hours']    = array();
        $days = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );
        foreach ( $days as $day ) {
            $data['hours'][ $day ] = array(
                'open'       => isset( $input['hours'][ $day ]['open'] ) ? '1' : '',
                'open_time'  => sanitize_text_field( isset( $input['hours'][ $day ]['open_time'] ) ? $input['hours'][ $day ]['open_time'] : '09:00' ),
                'close_time' => sanitize_text_field( isset( $input['hours'][ $day ]['close_time'] ) ? $input['hours'][ $day ]['close_time'] : '17:00' ),
            );
        }

        // Social
        $data['social'] = array();
        $social_keys = array( 'facebook', 'twitter', 'instagram', 'linkedin', 'youtube', 'yelp' );
        foreach ( $social_keys as $sk ) {
            $data['social'][ $sk ] = esc_url_raw( isset( $input['social'][ $sk ] ) ? $input['social'][ $sk ] : '' );
        }

        // Type-specific fields
        $data['type_fields'] = array();
        $type_fields = BLM_Business_Types::get_type_fields( $data['business_type'] );
        foreach ( $type_fields as $field ) {
            $raw = isset( $input['type_fields'][ $field['key'] ] ) ? $input['type_fields'][ $field['key'] ] : '';
            if ( 'textarea' === $field['type'] ) {
                $data['type_fields'][ $field['key'] ] = sanitize_textarea_field( $raw );
            } elseif ( 'checkboxes' === $field['type'] ) {
                $data['type_fields'][ $field['key'] ] = is_array( $raw ) ? array_map( 'sanitize_text_field', $raw ) : array();
            } else {
                $data['type_fields'][ $field['key'] ] = sanitize_text_field( $raw );
            }
        }

        update_option( 'blm_business_data', $data );
        update_option( 'blm_last_updated', current_time( 'mysql' ) );

        add_settings_error( 'blm_messages', 'blm_saved', 'Settings saved.', 'updated' );
    }
}
