<?php
namespace PSSG_Sync_Sheet\App\Handle;

use PSSG_Sync_Sheet\App\Core\Admin_Base;
use PSSG_Sync_Sheet\App\Service\Standalone;
use PSSG_Sync_Sheet\App\Http\Sheet;
use PSSG_Sync_Sheet\App\Service\Products;
use PSSG_Sync_Sheet\App\Service\Request_Log;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Schedule Sync Handler
 *
 * Registers and manages a WP-Cron based scheduled sync between WooCommerce
 * product data and the connected Google Sheet.
 *
 * Supported frequencies: hourly, twicedaily, daily, weekly, monthly.
 * Schedule settings are stored inside the existing `pssg_config` option to
 * keep all plugin configuration in a single option record.
 *
 * Option keys used (all stored inside pssg_config array):
 *  - schedule_sync_enabled    : '1' | ''
 *  - schedule_sync_frequency  : hourly|twicedaily|daily|weekly|monthly
 *  - schedule_sync_hour       : 0-23  (used for daily / weekly / monthly)
 *  - schedule_sync_day_week   : 1-7   (ISO day, 1=Mon … 7=Sun, used for weekly)
 *  - schedule_sync_day_month  : 1-28  (day of the month, used for monthly)
 *
 * Standalone option:
 *  - pssg_last_scheduled_sync : MySQL datetime of last successful cron execution
 *
 * @since  2.0.1.0
 * @author CodeAstrology Team <codersaiful@gmail.com>
 * @package PSSG_Sync_Sheet
 */
class Schedule_Sync_Handle extends Admin_Base
{
    use Standalone;

    /**
     * WP-Cron hook name fired by the scheduled event.
     */
    const CRON_HOOK = 'pssg_scheduled_sync';

    /**
     * Option key that stores the timestamp of the last successful run.
     */
    const LAST_SYNC_KEY = 'pssg_last_scheduled_sync';

    /**
     * Custom recurrence slugs added by this handler.
     */
    const RECURRENCE_WEEKLY  = 'pssg_weekly';
    const RECURRENCE_MONTHLY = 'pssg_monthly';

    /**
     * One-time WP-Cron hook used only for test-run scheduling.
     * Kept separate so it does not interfere with the recurring event.
     */
    const TEST_CRON_HOOK = 'pssg_test_scheduled_sync';

    /**
     * Delay in seconds before the test event fires (2 minutes).
     */
    const TEST_DELAY_SECONDS = 120;

    // -------------------------------------------------------------------------
    // Bootstrap
    // -------------------------------------------------------------------------

    /**
     * Attach all WordPress hooks.
     *
     * Called once by Admin_Loader::init().
     *
     * @return void
     */
    public function run()
    {
        // Register custom cron recurrences before WP uses them.
        add_filter( 'cron_schedules', [ $this, 'register_cron_intervals' ] );

        // Bind the cron hook to the execution method.
        add_action( self::CRON_HOOK, [ $this, 'execute_sync' ] );

        // Inject UI row(s) into the existing Settings page table.
        add_action( 'pssg_admin_section_bottom', [ $this, 'render_settings_section' ], 10, 2 );

        // Reschedule automatically whenever pssg_config is updated.
        add_action( 'update_option_' . $this->config_key, [ $this, 'reschedule_on_settings_save' ], 10, 2 );

        // On every init, ensure a scheduled event exists when it should.
        add_action( 'init', [ $this, 'maybe_schedule' ] );

        // Bind the test cron hook to the same execution method.
        add_action( self::TEST_CRON_HOOK, [ $this, 'execute_sync' ] );

        // AJAX: schedule a one-time test sync in 2 minutes.
        add_action( 'wp_ajax_pssg_schedule_test_sync', [ $this, 'ajax_schedule_test_sync' ] );
    }

    // -------------------------------------------------------------------------
    // WP-Cron helpers
    // -------------------------------------------------------------------------

    /**
     * Register weekly and monthly recurrence intervals.
     *
     * @param  array $schedules Existing cron schedules.
     * @return array
     */
    public function register_cron_intervals( $schedules )
    {
        if ( ! isset( $schedules[ self::RECURRENCE_WEEKLY ] ) ) {
            $schedules[ self::RECURRENCE_WEEKLY ] = [
                'interval' => WEEK_IN_SECONDS,
                'display'  => __( 'Once Weekly', 'product-sync-master-sheet' ),
            ];
        }

        if ( ! isset( $schedules[ self::RECURRENCE_MONTHLY ] ) ) {
            $schedules[ self::RECURRENCE_MONTHLY ] = [
                'interval' => 30 * DAY_IN_SECONDS,
                'display'  => __( 'Once Monthly (~30 days)', 'product-sync-master-sheet' ),
            ];
        }

        return $schedules;
    }

    /**
     * Schedule an event if one is not already registered and the feature is
     * enabled. Clears any stale event if the feature is disabled.
     *
     * Hooked to `init`.
     *
     * @return void
     */
    public function maybe_schedule()
    {
        $cfg = $this->get_schedule_config();

        if ( empty( $cfg['enabled'] ) || $cfg['enabled'] !== '1' ) {
            $this->clear_scheduled_event();
            return;
        }

        if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
            $this->schedule_cron_event( $cfg );
        }
    }

    /**
     * Called when the `pssg_config` option is updated via the Settings page.
     * Clears the existing scheduled event and re-creates it with the new values.
     *
     * @param  mixed $old_value Previous option value.
     * @param  mixed $new_value New option value.
     * @return void
     */
    public function reschedule_on_settings_save( $old_value, $new_value )
    {
        $this->clear_scheduled_event();

        $cfg = $this->extract_schedule_config( (array) $new_value );

        if ( ! empty( $cfg['enabled'] ) && $cfg['enabled'] === '1' ) {
            $this->schedule_cron_event( $cfg );
        }
    }

    /**
     * Register a recurring WP-Cron event using the supplied schedule config.
     *
     * @param  array $cfg Schedule configuration array.
     * @return void
     */
    protected function schedule_cron_event( array $cfg )
    {
        $recurrence = $this->get_wp_recurrence( $cfg['frequency'] ?? 'daily' );
        $timestamp  = $this->calculate_next_run( $cfg );

        wp_schedule_event( $timestamp, $recurrence, self::CRON_HOOK );
    }

    /**
     * Remove any scheduled `pssg_scheduled_sync` cron event.
     *
     * @return void
     */
    public function clear_scheduled_event()
    {
        $timestamp = wp_next_scheduled( self::CRON_HOOK );
        if ( $timestamp ) {
            wp_unschedule_event( $timestamp, self::CRON_HOOK );
        }
    }

    /**
     * Map a human-readable frequency string to a WP-Cron recurrence slug.
     *
     * @param  string $frequency One of: hourly, twicedaily, daily, weekly, monthly.
     * @return string WP-Cron recurrence slug.
     */
    protected function get_wp_recurrence( $frequency )
    {
        $map = [
            'hourly'     => 'hourly',
            'twicedaily' => 'twicedaily',
            'daily'      => 'daily',
            'weekly'     => self::RECURRENCE_WEEKLY,
            'monthly'    => self::RECURRENCE_MONTHLY,
        ];

        return $map[ $frequency ] ?? 'daily';
    }

    /**
     * Calculate the Unix timestamp for the next scheduled run based on the
     * user-configured frequency, hour-of-day, day-of-week, and day-of-month.
     *
     * All calculations respect the WordPress site timezone.
     *
     * @param  array $cfg Schedule configuration array.
     * @return int  Unix timestamp (UTC) for the next run.
     */
    protected function calculate_next_run( array $cfg )
    {
        $frequency    = $cfg['frequency']  ?? 'daily';
        $hour         = min( 23, max( 0, intval( $cfg['hour'] ?? 0 ) ) );
        $day_of_week  = min( 7,  max( 1, intval( $cfg['day_week'] ?? 1 ) ) ); // ISO: 1=Mon, 7=Sun
        $day_of_month = min( 28, max( 1, intval( $cfg['day_month'] ?? 1 ) ) );

        $tz  = wp_timezone();
        $now = new \DateTime( 'now', $tz );
        $dt  = clone $now;

        switch ( $frequency ) {
            case 'hourly':
                // Next full hour boundary.
                $dt->modify( '+1 hour' );
                $dt->setTime( (int) $dt->format( 'H' ), 0, 0 );
                break;

            case 'twicedaily':
                // Next occurrence of the configured hour or 12 hours later.
                $dt->setTime( $hour, 0, 0 );
                if ( $dt->getTimestamp() <= $now->getTimestamp() ) {
                    $dt->modify( '+12 hours' );
                    $dt->setTime( (int) $dt->format( 'H' ), 0, 0 );
                }
                break;

            case 'daily':
                $dt->setTime( $hour, 0, 0 );
                if ( $dt->getTimestamp() <= $now->getTimestamp() ) {
                    $dt->modify( '+1 day' );
                }
                break;

            case 'weekly':
                // ISO day-of-week: 1 = Monday … 7 = Sunday.
                $dt->setTime( $hour, 0, 0 );
                $diff = $day_of_week - (int) $dt->format( 'N' );
                if ( $diff < 0 || ( $diff === 0 && $dt->getTimestamp() <= $now->getTimestamp() ) ) {
                    $diff += 7;
                }
                if ( $diff > 0 ) {
                    $dt->modify( "+{$diff} days" );
                }
                break;

            case 'monthly':
                $dt->setTime( $hour, 0, 0 );
                $dt->setDate( (int) $dt->format( 'Y' ), (int) $dt->format( 'm' ), $day_of_month );
                if ( $dt->getTimestamp() <= $now->getTimestamp() ) {
                    $dt->modify( '+1 month' );
                    // Re-apply the day because "+1 month" may overflow into the next month.
                    $dt->setDate( (int) $dt->format( 'Y' ), (int) $dt->format( 'm' ), $day_of_month );
                }
                break;

            default:
                $dt->modify( '+1 hour' );
        }

        return $dt->getTimestamp();
    }

    // -------------------------------------------------------------------------
    // Test scheduling (developer / QA helper)
    // -------------------------------------------------------------------------

    /**
     * AJAX handler: schedule a one-time test sync event 2 minutes from now.
     *
     * Clears any previously queued test event first so repeated clicks are safe.
     * Does NOT touch the recurring schedule.
     *
     * Action: wp_ajax_pssg_schedule_test_sync
     *
     * @return void  Sends JSON and exits.
     */
    public function ajax_schedule_test_sync()
    {
        // Verify nonce.
        $nonce = sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) );
        if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'pssg_schedule_test_sync' ) ) {
            wp_send_json_error( [ 'message' => __( 'Security check failed.', 'product-sync-master-sheet' ) ] );
        }

        // Capability check.
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'You do not have permission to do this.', 'product-sync-master-sheet' ) ] );
        }

        // Clear any pending test event.
        $existing = wp_next_scheduled( self::TEST_CRON_HOOK );
        if ( $existing ) {
            wp_unschedule_event( $existing, self::TEST_CRON_HOOK );
        }

        // Schedule a single-fire event 2 minutes from now.
        $fire_at = time() + self::TEST_DELAY_SECONDS;
        wp_schedule_single_event( $fire_at, self::TEST_CRON_HOOK );

        wp_send_json_success( [
            'message'  => __( 'Test sync scheduled! It will run within 2 minutes on the next page load.', 'product-sync-master-sheet' ),
            'fire_at'  => $fire_at,
            'fire_at_formatted' => wp_date(
                get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
                $fire_at
            ),
        ] );
    }

    // -------------------------------------------------------------------------
    // Sync execution
    // -------------------------------------------------------------------------

    /**
     * Execute the scheduled product sync.
     *
     * Iterates through all product pages and pushes each batch to the Google
     * Sheet, replicating the same logic as the manual "Sync with Sheet" button.
     *
     * Hooked to `pssg_scheduled_sync` (WP-Cron).
     *
     * @return void
     */
    public function execute_sync()
    {
        $is_test         = current_action() === self::TEST_CRON_HOOK;
        $sync_type       = $is_test ? 'scheduled-sync-test' : 'scheduled-sync';
        $sync_type_label = $is_test
            ? __( 'Schedule Sync (Test Run)', 'product-sync-master-sheet' )
            : __( 'Schedule Sync', 'product-sync-master-sheet' );

        // -----------------------------------------------------------------
        // Open a log entry so we capture the run even on early failures.
        // -----------------------------------------------------------------
        $log_id = Request_Log::log_request( [
            'direction'        => Request_Log::DIRECTION_SCHEDULED,
            'endpoint'         => $sync_type,
            'method'           => 'CRON',
            'request_data'     => [
                'type'       => $sync_type_label,
                'trigger'    => current_action(),
                'started_at' => current_time( 'mysql' ),
            ],
            'status'           => 'processing',
            'access_key_valid' => 1,
            'ip_address'       => '127.0.0.1',
            'user_agent'       => 'WP-Cron/' . get_bloginfo( 'version' ),
        ] );

        $Sheet = new Sheet();

        if ( ! $Sheet->configured ) {
            if ( $log_id ) {
                Request_Log::update_log( $log_id, [
                    'status'        => 'error',
                    'error_message' => __( 'Sheet not configured. Complete the Setup Wizard first.', 'product-sync-master-sheet' ),
                ] );
            }
            return;
        }

        /**
         * Allow third-party code to customise the WP_Query arguments used
         * when fetching products for the scheduled sync.
         *
         * @param array $args WP_Query / WooCommerce query arguments.
         */
        $args     = apply_filters( 'pssg_update_sheet_args', [] );
        $products = new Products( $args );

        $page           = 1;
        $max_pages      = 1;
        $synced_pages   = 0;
        $total_products = 0;
        $page_errors    = [];

        do {
            $products->set_paged( $page );
            $products->update_sheet_index = true;

            $value = $products->get_sheet_row();

            if ( empty( $value ) ) {
                break;
            }

            if ( $page === 1 ) {
                $max_pages      = $products->max_num_pages ?? 1;
                $total_products = $products->found_posts   ?? 0;
            }

            $Sheet->sheet_range = $products->getSheetRang();
            $sheet_response     = $Sheet->update_online_sheet( $value );

            if ( isset( $sheet_response['status'] ) && $sheet_response['status'] === 'success' ) {
                $synced_pages++;
            } else {
                $page_errors[] = [
                    'page'  => $page,
                    'error' => $sheet_response['error'] ?? 'unknown_error',
                ];
            }

            $page++;
        } while ( $page <= $max_pages );

        $finished_at  = current_time( 'mysql' );
        $final_status = empty( $page_errors ) ? 'success' : ( $synced_pages > 0 ? 'success' : 'error' );

        $error_message = '';
        if ( ! empty( $page_errors ) ) {
            $parts = [];
            foreach ( $page_errors as $pe ) {
                $parts[] = sprintf( 'Page %d: %s', $pe['page'], $pe['error'] );
            }
            $error_message = implode( '; ', $parts );
        }

        update_option( self::LAST_SYNC_KEY, $finished_at );

        if ( $log_id ) {
            Request_Log::update_log( $log_id, [
                'status'        => $final_status,
                'error_message' => $error_message,
                'response_data' => [
                    'type'           => $sync_type_label,
                    'total_products' => $total_products,
                    'total_pages'    => $max_pages,
                    'synced_pages'   => $synced_pages,
                    'failed_pages'   => count( $page_errors ),
                    'page_errors'    => $page_errors,
                    'finished_at'    => $finished_at,
                ],
            ] );
        }

        /**
         * Fires after a scheduled sync has finished executing.
         *
         * @param Schedule_Sync_Handle $handler Current handler instance.
         */
        do_action( 'pssg_after_scheduled_sync', $this );
    }

    // -------------------------------------------------------------------------
    // Config helpers
    // -------------------------------------------------------------------------

    /**
     * Return the schedule sub-array from the currently loaded plugin config.
     *
     * @return array
     */
    protected function get_schedule_config()
    {
        return $this->extract_schedule_config( $this->configs );
    }

    /**
     * Extract schedule-related keys from a config array.
     *
     * @param  array $config Full pssg_config array.
     * @return array         Schedule sub-config array.
     */
    protected function extract_schedule_config( array $config )
    {
        return [
            'enabled'   => $config['schedule_sync_enabled']   ?? '0',
            'frequency' => $config['schedule_sync_frequency'] ?? 'daily',
            'hour'      => $config['schedule_sync_hour']      ?? '0',
            'day_week'  => $config['schedule_sync_day_week']  ?? '1',
            'day_month' => $config['schedule_sync_day_month'] ?? '1',
        ];
    }

    // -------------------------------------------------------------------------
    // Settings UI
    // -------------------------------------------------------------------------

    /**
     * Render the Schedule Sync section inside the Settings page table.
     *
     * Hooked to `pssg_admin_section_bottom`.
     *
     * @param  array  $saved_data Current pssg_config option value.
     * @param  string $page       Current settings tab/page slug.
     * @return void
     */
    public function render_settings_section( $saved_data, $page )
    {
        if ( $page !== 'settings' ) {
            return;
        }

        $cfg = $this->extract_schedule_config( (array) $saved_data );

        $enabled       = $cfg['enabled']   === '1';
        $frequency     = $cfg['frequency'] ?: 'daily';
        $hour          = intval( $cfg['hour'] );
        $day_of_week   = intval( $cfg['day_week'] );
        $day_of_month  = intval( $cfg['day_month'] );

        $last_sync = get_option( self::LAST_SYNC_KEY, '' );
        $next_sync = wp_next_scheduled( self::CRON_HOOK );

        $frequencies = [
            'hourly'     => __( 'Every Hour',           'product-sync-master-sheet' ),
            'twicedaily' => __( 'Twice Daily',          'product-sync-master-sheet' ),
            'daily'      => __( 'Every Day',            'product-sync-master-sheet' ),
            'weekly'     => __( 'Every Week',           'product-sync-master-sheet' ),
            'monthly'    => __( 'Every Month (~30 days)', 'product-sync-master-sheet' ),
        ];

        $days_of_week = [
            1 => __( 'Monday',    'product-sync-master-sheet' ),
            2 => __( 'Tuesday',   'product-sync-master-sheet' ),
            3 => __( 'Wednesday', 'product-sync-master-sheet' ),
            4 => __( 'Thursday',  'product-sync-master-sheet' ),
            5 => __( 'Friday',    'product-sync-master-sheet' ),
            6 => __( 'Saturday',  'product-sync-master-sheet' ),
            7 => __( 'Sunday',    'product-sync-master-sheet' ),
        ];
        ?>

        <?php /* ---- Section header row ---- */ ?>
        <tr class="pssg-schedule-sync-section">
            <td colspan="2">
                <div class="pssg-form-control pssg-section-header" style="border-top:1px solid #e2e4e7;padding-top:16px;margin-top:4px;">
                    <h4 style="margin:0 0 4px;font-size:14px;">
                        <?php esc_html_e( 'Schedule Sync', 'product-sync-master-sheet' ); ?>
                    </h4>
                    <p class="description" style="margin:0;">
                        <?php esc_html_e( 'Automatically sync your WooCommerce products to Google Sheet on a recurring schedule.', 'product-sync-master-sheet' ); ?>
                    </p>
                </div>
            </td>
        </tr>

        <?php /* ---- Enable / Disable ---- */ ?>
        <tr>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="schedule_sync_enabled">
                            <?php esc_html_e( 'Enable Schedule Sync', 'product-sync-master-sheet' ); ?>
                        </label>
                    </div>
                    <div class="form-field col-lg-8">
                        <div class="pssg-field-wrapper-single">
                            <input
                                type="checkbox"
                                id="schedule_sync_enabled"
                                name="schedule_sync_enabled"
                                value="1"
                                <?php checked( $enabled ); ?>
                            >
                        </div>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-form-info">
                    <p><?php esc_html_e( 'Turn on to activate the automatic scheduled sync.', 'product-sync-master-sheet' ); ?></p>
                </div>
            </td>
        </tr>

        <?php /* ---- Frequency ---- */ ?>
        <tr class="pssg-schedule-options" <?php if ( ! $enabled ) echo 'style="display:none"'; ?>>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="schedule_sync_frequency">
                            <?php esc_html_e( 'Sync Frequency', 'product-sync-master-sheet' ); ?>
                        </label>
                    </div>
                    <div class="form-field col-lg-8">
                        <div class="pssg-field-wrapper-single">
                            <select name="schedule_sync_frequency" id="schedule_sync_frequency">
                                <?php foreach ( $frequencies as $val => $label ) : ?>
                                    <option value="<?php echo esc_attr( $val ); ?>" <?php selected( $frequency, $val ); ?>>
                                        <?php echo esc_html( $label ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-form-info">
                    <p><?php esc_html_e( 'How often the automatic sync should run.', 'product-sync-master-sheet' ); ?></p>
                </div>
            </td>
        </tr>

        <?php /* ---- Hour of day (hidden for hourly) ---- */ ?>
        <tr class="pssg-schedule-options pssg-schedule-hour"
            <?php if ( ! $enabled || $frequency === 'hourly' ) echo 'style="display:none"'; ?>>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="schedule_sync_hour">
                            <?php esc_html_e( 'Sync Hour (0–23)', 'product-sync-master-sheet' ); ?>
                        </label>
                    </div>
                    <div class="form-field col-lg-8">
                        <div class="pssg-field-wrapper-single">
                            <select name="schedule_sync_hour" id="schedule_sync_hour">
                                <?php for ( $h = 0; $h <= 23; $h++ ) : ?>
                                    <option value="<?php echo esc_attr( $h ); ?>" <?php selected( $hour, $h ); ?>>
                                        <?php echo esc_html( sprintf( '%02d:00', $h ) ); ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-form-info">
                    <p><?php esc_html_e( 'Hour of the day to run the sync (site timezone).', 'product-sync-master-sheet' ); ?></p>
                </div>
            </td>
        </tr>

        <?php /* ---- Day of week (weekly only) ---- */ ?>
        <tr class="pssg-schedule-options pssg-schedule-day-week"
            <?php if ( ! $enabled || $frequency !== 'weekly' ) echo 'style="display:none"'; ?>>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="schedule_sync_day_week">
                            <?php esc_html_e( 'Day of Week', 'product-sync-master-sheet' ); ?>
                        </label>
                    </div>
                    <div class="form-field col-lg-8">
                        <div class="pssg-field-wrapper-single">
                            <select name="schedule_sync_day_week" id="schedule_sync_day_week">
                                <?php foreach ( $days_of_week as $val => $label ) : ?>
                                    <option value="<?php echo esc_attr( $val ); ?>" <?php selected( $day_of_week, $val ); ?>>
                                        <?php echo esc_html( $label ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-form-info">
                    <p><?php esc_html_e( 'Which day of the week to run the sync.', 'product-sync-master-sheet' ); ?></p>
                </div>
            </td>
        </tr>

        <?php /* ---- Day of month (monthly only) ---- */ ?>
        <tr class="pssg-schedule-options pssg-schedule-day-month"
            <?php if ( ! $enabled || $frequency !== 'monthly' ) echo 'style="display:none"'; ?>>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="schedule_sync_day_month">
                            <?php esc_html_e( 'Day of Month (1–28)', 'product-sync-master-sheet' ); ?>
                        </label>
                    </div>
                    <div class="form-field col-lg-8">
                        <div class="pssg-field-wrapper-single">
                            <select name="schedule_sync_day_month" id="schedule_sync_day_month">
                                <?php for ( $d = 1; $d <= 28; $d++ ) : ?>
                                    <option value="<?php echo esc_attr( $d ); ?>" <?php selected( $day_of_month, $d ); ?>>
                                        <?php echo esc_html( $d ); ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-form-info">
                    <p><?php esc_html_e( 'Day of the month to run the sync (max 28 to avoid month-end issues).', 'product-sync-master-sheet' ); ?></p>
                </div>
            </td>
        </tr>

        <?php /* ---- Status info ---- */ ?>
        <tr class="pssg-schedule-status" <?php if ( ! $enabled ) echo 'style="display:none"'; ?>>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label><?php esc_html_e( 'Sync Status', 'product-sync-master-sheet' ); ?></label>
                    </div>
                    <div class="form-field col-lg-8">
                        <p style="margin:0;padding:6px 0;">
                            <?php if ( $last_sync ) : ?>
                                <span style="color:#2271b1;">
                                    <?php
                                    /* translators: %s: MySQL datetime of last sync */
                                    echo esc_html( sprintf(
                                        __( 'Last synced: %s', 'product-sync-master-sheet' ),
                                        wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $last_sync ) )
                                    ) );
                                    ?>
                                </span>
                                <br>
                            <?php endif; ?>
                            <?php if ( $next_sync ) : ?>
                                <span style="color:#1d8348;">
                                    <?php
                                    /* translators: %s: formatted next sync date/time */
                                    echo esc_html( sprintf(
                                        __( 'Next sync: %s', 'product-sync-master-sheet' ),
                                        wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $next_sync )
                                    ) );
                                    ?>
                                </span>
                            <?php elseif ( $enabled ) : ?>
                                <span style="color:#856404;">
                                    <?php esc_html_e( 'No event scheduled yet. Save settings to schedule.', 'product-sync-master-sheet' ); ?>
                                </span>
                            <?php endif; ?>
                        </p>
                    </div>
                </div>
            </td>
            <td></td>
        </tr>

        <?php /* ---- Test sync button row ---- */ ?>
        <tr class="pssg-schedule-test-row">
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label><?php esc_html_e( 'Test Schedule', 'product-sync-master-sheet' ); ?></label>
                    </div>
                    <div class="form-field col-lg-8">
                        <button
                            type="button"
                            id="pssg-test-schedule-btn"
                            class="button button-secondary"
                            style="display:inline-flex;align-items:center;gap:6px;"
                        >
                            <span class="dashicons dashicons-clock" style="margin-top:3px;"></span>
                            <?php esc_html_e( 'Schedule Test Sync (runs in ~2 min)', 'product-sync-master-sheet' ); ?>
                        </button>
                        <span id="pssg-test-schedule-msg" style="margin-left:10px;font-style:italic;"></span>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-form-info">
                    <p><?php esc_html_e( 'Creates a one-time cron event that fires within 2 minutes. Use this to verify the scheduled sync works without waiting for the next real occurrence. Does not affect the active recurring schedule.', 'product-sync-master-sheet' ); ?></p>
                </div>
            </td>
        </tr>

        <?php /* ---- Inline JS: show/hide rows on toggle/frequency change ---- */ ?>
        <script>
        (function () {
            var enabledChk  = document.getElementById('schedule_sync_enabled');
            var freqSelect  = document.getElementById('schedule_sync_frequency');

            if (!enabledChk || !freqSelect) return;

            function toggleVisible() {
                var isEnabled = enabledChk.checked;
                var freq      = freqSelect.value;

                document.querySelectorAll('.pssg-schedule-options').forEach(function (el) {
                    el.style.display = isEnabled ? '' : 'none';
                });
                document.querySelectorAll('.pssg-schedule-status').forEach(function (el) {
                    el.style.display = isEnabled ? '' : 'none';
                });

                var hourRow = document.querySelector('.pssg-schedule-hour');
                if (hourRow) {
                    hourRow.style.display = (isEnabled && freq !== 'hourly') ? '' : 'none';
                }

                var weekRow = document.querySelector('.pssg-schedule-day-week');
                if (weekRow) {
                    weekRow.style.display = (isEnabled && freq === 'weekly') ? '' : 'none';
                }

                var monthRow = document.querySelector('.pssg-schedule-day-month');
                if (monthRow) {
                    monthRow.style.display = (isEnabled && freq === 'monthly') ? '' : 'none';
                }
            }

            enabledChk.addEventListener('change', toggleVisible);
            freqSelect.addEventListener('change', toggleVisible);

            // Run once on page load to apply the saved state.
            toggleVisible();

            // -----------------------------------------------------------------
            // Test-schedule button
            // -----------------------------------------------------------------
            var testBtn = document.getElementById('pssg-test-schedule-btn');
            var testMsg = document.getElementById('pssg-test-schedule-msg');

            if (testBtn && testMsg) {
                testBtn.addEventListener('click', function () {
                    testBtn.disabled = true;
                    testMsg.style.color = '';
                    testMsg.textContent = '<?php echo esc_js( __( 'Scheduling…', 'product-sync-master-sheet' ) ); ?>';

                    var data = new FormData();
                    data.append('action', 'pssg_schedule_test_sync');
                    data.append('nonce', '<?php echo esc_js( wp_create_nonce( 'pssg_schedule_test_sync' ) ); ?>');

                    fetch(ajaxurl, { method: 'POST', body: data, credentials: 'same-origin' })
                        .then(function (r) { return r.json(); })
                        .then(function (res) {
                            if (res.success) {
                                testMsg.style.color = '#1d8348';
                                testMsg.textContent = res.data.message +
                                    ' (' + res.data.fire_at_formatted + ')';
                            } else {
                                testMsg.style.color = '#c0392b';
                                testMsg.textContent = res.data.message || '<?php echo esc_js( __( 'Something went wrong.', 'product-sync-master-sheet' ) ); ?>';
                            }
                        })
                        .catch(function () {
                            testMsg.style.color = '#c0392b';
                            testMsg.textContent = '<?php echo esc_js( __( 'Request failed. Check your connection.', 'product-sync-master-sheet' ) ); ?>';
                        })
                        .finally(function () {
                            testBtn.disabled = false;
                        });
                });
            }
        }());
        </script>

        <?php
    }
}
