<?php
/**
 * Provide a admin settings view for the plugin
 *
 * This file is used to markup the settings page of the plugin.
 *
 * @link       https://github.com/sitestaffr/sitestaffr-plugin
 * @since      1.0.0
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/views
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
?>

<div class="wrap sitestaffr-wrap sitestaffr-settings">
    <?php
    $sitestaffr_page_title = __( 'Settings', 'sitestaffr' );
    include SITESTAFFR_PLUGIN_DIR . 'admin/partials/sitestaffr-header.php';
    ?>

    <?php
    // Get settings
    $settings = get_option( 'sitestaffr_settings', array() );
    ?>

    <?php
    // Display settings errors/messages
    // Add 'settings-updated' class to suppress duplicate WordPress automatic notices
    settings_errors( 'sitestaffr_settings', false, true );
    ?>

    <?php
    // The real save is the AJAX "Update Business Information" button — the old
    // options.php <form> shell never submitted, so it's a plain container now.
    ?>
    <div class="sitestaffr-settings-form">

        <div class="sitestaffr-settings-layout">
            <?php
            global $wp_settings_sections, $wp_settings_fields;

            $section_icons = array(
                'sitestaffr_business_section' => 'dashicons-store',
            );

            if ( isset( $wp_settings_sections['sitestaffr-settings'] ) ) :
                foreach ( (array) $wp_settings_sections['sitestaffr-settings'] as $section ) :
                    if ( ! isset( $section['id'] ) ) {
                        continue;
                    }

                    $section_id = $section['id'];
                    $icon_class = isset( $section_icons[ $section_id ] ) ? $section_icons[ $section_id ] : 'dashicons-admin-generic';
                    ?>
                    <section class="sitestaffr-settings-card sitestaffr-settings-card-<?php echo esc_attr( sanitize_html_class( $section_id ) ); ?>">
                        <header class="sitestaffr-settings-card-header">
                            <h2>
                                <span class="dashicons <?php echo esc_attr( $icon_class ); ?>" aria-hidden="true"></span>
                                <?php echo esc_html( $section['title'] ); ?>
                            </h2>
                        </header>
                        <div class="sitestaffr-settings-card-body">
                            <?php
                            if ( ! empty( $section['callback'] ) ) {
                                call_user_func( $section['callback'], $section );
                            }
                            ?>

                            <?php if ( isset( $wp_settings_fields['sitestaffr-settings'][ $section_id ] ) ) : ?>
                                <?php if ( 'sitestaffr_business_section' === $section_id ) : ?>
                                    <?php
                                    $business_fields = $wp_settings_fields['sitestaffr-settings'][ $section_id ];
                                    $hours_field   = isset( $business_fields['business_hours'] ) ? $business_fields['business_hours'] : null;
                                    $context_field = isset( $business_fields['business_context'] ) ? $business_fields['business_context'] : null;
                                    $profile_field = isset( $business_fields['business_profile'] ) ? $business_fields['business_profile'] : null;
                                    ?>
                                    <div class="sitestaffr-business-grid">
                                        <div class="sitestaffr-business-main">
                                            <?php foreach ( array( 'business_name', 'business_phone' ) as $field_key ) : ?>
                                                <?php if ( empty( $business_fields[ $field_key ] ) ) : ?>
                                                    <?php continue; ?>
                                                <?php endif; ?>
                                                <?php $field = $business_fields[ $field_key ]; ?>
                                                <div class="sitestaffr-business-row sitestaffr-business-row-<?php echo esc_attr( sanitize_html_class( $field_key ) ); ?>">
                                                    <div class="sitestaffr-business-label">
                                                        <label for="<?php echo esc_attr( $field_key ); ?>">
                                                            <?php echo wp_kses_post( $field['title'] ); ?>
                                                        </label>
                                                    </div>
                                                    <div class="sitestaffr-business-control">
                                                        <?php call_user_func( $field['callback'], $field['args'] ); ?>
                                                        <?php if ( 'business_phone' === $field_key ) : ?>
                                                            <p class="description"><?php esc_html_e( 'Shared with visitors who ask to call you. Your AI never dials it.', 'sitestaffr' ); ?></p>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>

                                            <?php if ( $hours_field ) : ?>
                                                <aside class="sitestaffr-business-hours-panel">
                                                    <h3><?php echo wp_kses_post( $hours_field['title'] ); ?></h3>
                                                    <div class="sitestaffr-business-hours-control">
                                                        <?php call_user_func( $hours_field['callback'], $hours_field['args'] ); ?>
                                                    </div>
                                                </aside>
                                            <?php endif; ?>
                                        </div>

                                        <?php if ( $context_field ) : ?>
                                            <?php
                                            $remaining_gens = method_exists( $this, 'get_remaining_description_generations' )
                                                ? max( 0, (int) $this->get_remaining_description_generations() )
                                                : 0;
                                            // Pages/CPT entries published since the profile was last written.
                                            // 0 also means "never generated" — that is a different state, not a stale one.
                                            $new_since_identity = method_exists( $this, 'count_content_published_since_identity' )
                                                ? (int) $this->count_content_published_since_identity()
                                                : 0;
                                            $staleness_cap = SiteStaffr_Admin::IDENTITY_STALENESS_COUNT_CAP;
                                            ?>
                                            <div class="sitestaffr-business-profile-col">
                                                <div class="sitestaffr-profile-col-head">
                                                    <span class="sitestaffr-profile-col-title"><?php esc_html_e( 'Business Profile', 'sitestaffr' ); ?></span>
                                                    <div class="sitestaffr-generate-card" data-remaining-generations="<?php echo esc_attr( $remaining_gens ); ?>">
                                                        <button
                                                            type="button"
                                                            id="btn-settings-generate-description"
                                                            class="button button-secondary sitestaffr-generate-btn"
                                                            aria-describedby="sitestaffr-gen-status"
                                                            <?php echo $remaining_gens <= 0 ? 'disabled' : ''; ?>
                                                        >
                                                            <span class="sitestaffr-gen-button-ripple" aria-hidden="true"></span>
                                                            <span class="dashicons dashicons-update"></span>
                                                            <?php esc_html_e( 'Generate Profile', 'sitestaffr' ); ?>
                                                        </button>
                                                        <div class="sitestaffr-gen-progress" aria-hidden="true">
                                                            <div class="sitestaffr-gen-progress-bar"></div>
                                                        </div>
                                                        <p id="sitestaffr-gen-status" class="sitestaffr-gen-status" aria-live="polite"></p>
                                                    </div>
                                                </div>
                                                <?php if ( $new_since_identity > 0 ) : ?>
                                                    <div class="sitestaffr-integration-notice is-warning" role="status">
                                                        <?php
                                                        $count_label = $new_since_identity >= $staleness_cap
                                                            ? sprintf( '%d+', $staleness_cap )
                                                            : number_format_i18n( $new_since_identity );
                                                        printf(
                                                            /* translators: %s is a page count, e.g. "3" or "20+". */
                                                            esc_html( _n(
                                                                '%s new page has been published since this profile was written. Regenerate it so your agents know what changed — or edit it yourself below.',
                                                                '%s new pages have been published since this profile was written. Regenerate it so your agents know what changed — or edit it yourself below.',
                                                                $new_since_identity,
                                                                'sitestaffr'
                                                            ) ),
                                                            esc_html( $count_label )
                                                        );
                                                        ?>
                                                    </div>
                                                <?php endif; ?>
                                                <div class="sitestaffr-profile-doc">
                                                        <div class="sitestaffr-profile-region sitestaffr-profile-region--summary">
                                                            <div class="sitestaffr-profile-region-head">
                                                                <label class="sitestaffr-profile-region-title" for="business_context"><?php esc_html_e( 'Summary', 'sitestaffr' ); ?></label>
                                                            </div>
                                                            <p class="sitestaffr-profile-region-help">
                                                                <?php esc_html_e( 'Your voice and chat agent keeps this in mind in every conversation. Keep it short — services, prices and policies come from your knowledge base.', 'sitestaffr' ); ?>
                                                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-my-agent&tab=knowledge' ) ); ?>"><?php esc_html_e( 'What your agent knows', 'sitestaffr' ); ?></a>
                                                            </p>
                                                            <?php call_user_func( $context_field['callback'], $context_field['args'] ); ?>
                                                        </div>

                                                        <?php if ( $profile_field ) : ?>
                                                            <div class="sitestaffr-profile-region sitestaffr-profile-region--body">
                                                                <div class="sitestaffr-profile-region-head">
                                                                    <label class="sitestaffr-profile-region-title" for="business_profile"><?php esc_html_e( 'Detailed Profile (Blog Agent)', 'sitestaffr' ); ?></label>
                                                                </div>
                                                                <p class="sitestaffr-profile-region-help">
                                                                    <?php esc_html_e( 'Used by the Blog Agent to plan and write posts. Your voice and chat agent does not read this — it answers from the Summary above and your knowledge base.', 'sitestaffr' ); ?>
                                                                </p>
                                                                <?php call_user_func( $profile_field['callback'], $profile_field['args'] ); ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="sitestaffr-business-guidance-modal" data-sitestaffr-guidance-modal hidden>
                                        <div class="sitestaffr-business-guidance-backdrop" data-sitestaffr-guidance-close></div>
                                        <div class="sitestaffr-business-guidance-dialog" role="dialog" aria-modal="true" aria-labelledby="sitestaffr-business-guidance-title">
                                            <button type="button" class="sitestaffr-business-guidance-close" aria-label="<?php esc_attr_e( 'Close guidance', 'sitestaffr' ); ?>" data-sitestaffr-guidance-close>&times;</button>
                                            <h3 id="sitestaffr-business-guidance-title"><?php esc_html_e( 'How to: Write a Great Business Identity', 'sitestaffr' ); ?></h3>
                                            <ul>
                                                <li><?php esc_html_e( 'Explain what your business does in 2-3 sentences: services, industries served, and what sets you apart.', 'sitestaffr' ); ?></li>
                                                <li><?php esc_html_e( 'List your key services or products by name. Detailed descriptions are handled by your Knowledge Base.', 'sitestaffr' ); ?></li>
                                                <li><?php esc_html_e( 'Include any promotions, seasonal offers, or internal knowledge the AI should know.', 'sitestaffr' ); ?></li>
                                                <li><?php esc_html_e( 'Keep it concise — this is your business\'s elevator pitch, not an encyclopedia.', 'sitestaffr' ); ?></li>
                                            </ul>
                                        </div>
                                    </div>
                                <?php elseif ( 'sitestaffr_ai_receptionist_voice_section' === $section_id ) : ?>
                                    <div class="sitestaffr-settings-voice-field">
                                        <?php foreach ( $wp_settings_fields['sitestaffr-settings'][ $section_id ] as $field ) : ?>
                                            <?php call_user_func( $field['callback'], $field['args'] ); ?>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else : ?>
                                    <table class="form-table" role="presentation">
                                        <tbody>
                                            <?php do_settings_fields( 'sitestaffr-settings', $section_id ); ?>
                                        </tbody>
                                    </table>
                                <?php endif; ?>
                            <?php endif; ?>

                            <?php if ( 'sitestaffr_business_section' === $section_id ) : ?>
                                <div class="sitestaffr-settings-save-wrap">
                                    <button type="button" id="sitestaffr-save-business-settings" class="button button-primary sitestaffr-settings-save-button">
                                        <span class="dashicons dashicons-saved" aria-hidden="true"></span>
                                        <span class="sitestaffr-save-business-text"><?php esc_html_e( 'Update Business Information', 'sitestaffr' ); ?></span>
                                    </button>
                                    <span id="sitestaffr-business-save-status" class="sitestaffr-inline-status" style="margin-left: 10px;"></span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </section>
                    <?php
                endforeach;
            endif;
            ?>

            <?php
            // ── Account & Connection — the first production-visible service-
            // connection surface (Diagnostics is dev-build-only).
            $sitestaffr_account_id      = (string) get_option( 'sitestaffr_account_id', '' );
            $sitestaffr_installation_id = (string) get_option( 'sitestaffr_installation_id', '' );
            $sitestaffr_is_registered   = ( '' !== $sitestaffr_account_id || '' !== $sitestaffr_installation_id );
            $sitestaffr_db_version      = (string) get_option( 'sitestaffr_db_version', '' );
            ?>
            <section class="sitestaffr-settings-card sitestaffr-settings-card-account">
                <header class="sitestaffr-settings-card-header">
                    <h2>
                        <span class="dashicons dashicons-admin-network" aria-hidden="true"></span>
                        <?php esc_html_e( 'Account & Connection', 'sitestaffr' ); ?>
                    </h2>
                </header>
                <div class="sitestaffr-settings-card-body">
                    <div class="sitestaffr-account-grid">
                        <div class="sitestaffr-account-field">
                            <label><?php esc_html_e( 'Registration', 'sitestaffr' ); ?></label>
                            <p>
                                <?php if ( $sitestaffr_is_registered ) : ?>
                                    <span class="sitestaffr-account-status is-registered"><?php esc_html_e( 'Registered', 'sitestaffr' ); ?></span>
                                <?php else : ?>
                                    <span class="sitestaffr-account-status is-unregistered"><?php esc_html_e( 'Not registered', 'sitestaffr' ); ?></span>
                                    <span class="description"><?php esc_html_e( 'Run the setup wizard to register this site.', 'sitestaffr' ); ?></span>
                                <?php endif; ?>
                            </p>
                        </div>

                        <?php if ( '' !== $sitestaffr_account_id ) : ?>
                        <div class="sitestaffr-account-field">
                            <label><?php esc_html_e( 'Account ID', 'sitestaffr' ); ?></label>
                            <p>
                                <code class="sitestaffr-call-sid-code sitestaffr-account-id-code" title="<?php esc_attr_e( 'Click to copy', 'sitestaffr' ); ?>"><?php echo esc_html( $sitestaffr_account_id ); ?></code>
                            </p>
                            <p class="description"><?php esc_html_e( 'Include this when contacting SiteStaffr support.', 'sitestaffr' ); ?></p>
                        </div>
                        <?php endif; ?>

                        <div class="sitestaffr-account-field">
                            <label><?php esc_html_e( 'Service Connection', 'sitestaffr' ); ?></label>
                            <p>
                                <button type="button" class="button" id="sitestaffr-test-connection">
                                    <span class="dashicons dashicons-update" aria-hidden="true"></span>
                                    <?php esc_html_e( 'Test connection', 'sitestaffr' ); ?>
                                </button>
                                <span id="sitestaffr-test-connection-status" class="sitestaffr-inline-status"></span>
                            </p>
                        </div>

                        <div class="sitestaffr-account-field">
                            <label><?php esc_html_e( 'Versions', 'sitestaffr' ); ?></label>
                            <p>
                                <?php
                                echo esc_html( sprintf(
                                    /* translators: 1: plugin version, 2: database schema version */
                                    __( 'Plugin %1$s · Database %2$s', 'sitestaffr' ),
                                    SITESTAFFR_VERSION,
                                    '' !== $sitestaffr_db_version ? $sitestaffr_db_version : SITESTAFFR_VERSION
                                ) );
                                ?>
                            </p>
                        </div>
                    </div>
                </div>
            </section>

            <?php
            // ── Integrations — connect a CRM so qualified leads flow there in real time.
            $sitestaffr_sf_return = isset( $_GET['salesforce'] ) ? sanitize_key( wp_unslash( $_GET['salesforce'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag from the OAuth redirect.
            if ( class_exists( 'SiteStaffr_Salesforce' ) ) :
                // A fresh OAuth return should reflect reality immediately, not the cache.
                if ( 'connected' === $sitestaffr_sf_return || 'error' === $sitestaffr_sf_return ) {
                    delete_transient( SiteStaffr_Salesforce::STATUS_TRANSIENT );
                }
                // Never-connected sites skip the middleware round-trip entirely — the
                // Settings page must not block on a Salesforce call it doesn't need.
                if ( get_option( SiteStaffr_Salesforce::CONNECTED_FLAG ) || 'connected' === $sitestaffr_sf_return ) {
                    $sitestaffr_sf_status = SiteStaffr_Salesforce::get_status();
                } else {
                    $sitestaffr_sf_status = array( 'connected' => false );
                }
                $sitestaffr_sf_connected = ! empty( $sitestaffr_sf_status['connected'] );
                $sitestaffr_sf_nonce     = wp_create_nonce( 'sitestaffr_ajax_nonce' );
                ?>
                <section class="sitestaffr-settings-card sitestaffr-settings-card-integrations">
                    <header class="sitestaffr-settings-card-header">
                        <h2>
                            <span class="dashicons dashicons-networking" aria-hidden="true"></span>
                            <?php esc_html_e( 'Integrations', 'sitestaffr' ); ?>
                        </h2>
                    </header>
                    <div class="sitestaffr-settings-card-body">
                        <?php if ( 'connected' === $sitestaffr_sf_return ) : ?>
                            <div class="sitestaffr-integration-notice is-success"><?php esc_html_e( 'Salesforce connected. New qualified leads will now sync automatically.', 'sitestaffr' ); ?></div>
                        <?php elseif ( 'error' === $sitestaffr_sf_return ) : ?>
                            <div class="sitestaffr-integration-notice is-error"><?php esc_html_e( 'Salesforce connection did not complete. Please try connecting again.', 'sitestaffr' ); ?></div>
                        <?php endif; ?>

                        <div class="sitestaffr-integration">
                            <div class="sitestaffr-integration-logo">
                                <img src="<?php echo esc_url( SITESTAFFR_PLUGIN_URL . 'assets/images/salesforce-logo.svg?v=' . SITESTAFFR_VERSION ); ?>" alt="<?php esc_attr_e( 'Salesforce', 'sitestaffr' ); ?>" />
                            </div>
                            <div class="sitestaffr-integration-main">
                                <div class="sitestaffr-integration-heading">
                                    <span class="sitestaffr-integration-name"><?php esc_html_e( 'Salesforce', 'sitestaffr' ); ?></span>
                                    <?php if ( $sitestaffr_sf_connected ) : ?>
                                        <span class="sitestaffr-integration-status is-connected">
                                            <span class="sitestaffr-integration-dot" aria-hidden="true"></span>
                                            <?php
                                            if ( ! empty( $sitestaffr_sf_status['org_name'] ) ) {
                                                echo esc_html( sprintf(
                                                    /* translators: %s: Salesforce org name */
                                                    __( 'Connected · %s', 'sitestaffr' ),
                                                    $sitestaffr_sf_status['org_name']
                                                ) );
                                            } else {
                                                esc_html_e( 'Connected', 'sitestaffr' );
                                            }
                                            ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <p class="sitestaffr-integration-desc">
                                    <?php esc_html_e( 'Send every qualified lead to your Salesforce as a Lead record in real time — contact, recap, and a link to the full conversation.', 'sitestaffr' ); ?>
                                </p>
                                <?php if ( isset( $sitestaffr_sf_status['edition_ok'] ) && false === $sitestaffr_sf_status['edition_ok'] ) : ?>
                                    <p class="description sitestaffr-sf-edition-warning"><?php esc_html_e( "Your Salesforce edition doesn't include REST API access, which this integration requires (Enterprise/Unlimited, or Professional with the API add-on).", 'sitestaffr' ); ?></p>
                                <?php endif; ?>
                            </div>
                            <div class="sitestaffr-integration-action">
                                <?php if ( $sitestaffr_sf_connected ) : ?>
                                    <button type="button" class="button" id="sitestaffr-sf-disconnect"><?php esc_html_e( 'Disconnect', 'sitestaffr' ); ?></button>
                                <?php else : ?>
                                    <button type="button" class="button button-primary" id="sitestaffr-sf-connect"><?php esc_html_e( 'Connect Salesforce', 'sitestaffr' ); ?></button>
                                <?php endif; ?>
                                <span id="sitestaffr-sf-status" class="sitestaffr-inline-status"></span>
                            </div>
                        </div>
                        <?php if ( ! $sitestaffr_sf_connected ) : ?>
                            <p class="sitestaffr-integration-hint">
                                <span class="dashicons dashicons-info-outline" aria-hidden="true"></span>
                                <?php esc_html_e( 'When you connect, Salesforce shows a standard security notice for third-party apps — that\'s expected. Just click Allow to finish.', 'sitestaffr' ); ?>
                            </p>
                        <?php endif; ?>
                    </div>
                </section>
                <script>
                ( function () {
                    var nonce = '<?php echo esc_js( $sitestaffr_sf_nonce ); ?>';
                    var statusEl = document.getElementById( 'sitestaffr-sf-status' );
                    var connectBtn = document.getElementById( 'sitestaffr-sf-connect' );
                    var disconnectBtn = document.getElementById( 'sitestaffr-sf-disconnect' );
                    var connectingLabel = '<?php echo esc_js( __( 'Connecting…', 'sitestaffr' ) ); ?>';
                    var disconnectingLabel = '<?php echo esc_js( __( 'Disconnecting…', 'sitestaffr' ) ); ?>';
                    function post( action, busyLabel, onDone ) {
                        if ( statusEl ) { statusEl.textContent = busyLabel; }
                        var body = new URLSearchParams();
                        body.append( 'action', action );
                        body.append( 'nonce', nonce );
                        fetch( ajaxurl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body } )
                            .then( function ( r ) { return r.json(); } )
                            .then( onDone )
                            .catch( function () { if ( statusEl ) { statusEl.textContent = '<?php echo esc_js( __( 'Something went wrong. Please try again.', 'sitestaffr' ) ); ?>'; } } );
                    }
                    if ( connectBtn ) {
                        connectBtn.addEventListener( 'click', function () {
                            post( 'sitestaffr_sf_connect', connectingLabel, function ( res ) {
                                if ( res && res.success && res.data && res.data.authorize_url ) {
                                    window.location = res.data.authorize_url;
                                } else if ( statusEl ) {
                                    statusEl.textContent = ( res && res.data && res.data.message ) || '<?php echo esc_js( __( 'Could not start the connection.', 'sitestaffr' ) ); ?>';
                                }
                            } );
                        } );
                    }
                    if ( disconnectBtn ) {
                        disconnectBtn.addEventListener( 'click', function () {
                            if ( ! window.confirm( '<?php echo esc_js( __( 'Disconnect Salesforce? New leads will stop syncing there.', 'sitestaffr' ) ); ?>' ) ) { return; }
                            post( 'sitestaffr_sf_disconnect', disconnectingLabel, function ( res ) {
                                if ( res && res.success ) { window.location.reload(); }
                                else if ( statusEl ) { statusEl.textContent = ( res && res.data && res.data.message ) || '<?php echo esc_js( __( 'Could not disconnect.', 'sitestaffr' ) ); ?>'; }
                            } );
                        } );
                    }
                } )();
                </script>
            <?php endif; ?>
        </div>

    </div>

    <!-- Settings page JS enqueued via class-sitestaffr-admin.php (sitestaffr-settings-page.js) -->
    <!-- Email Notification Settings moved to My AI Agent → Voice & Behavior (each agent owns its notifications). -->

</div>
<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
