<?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\Service\Products;
use PSSG_Sync_Sheet\App\Http\Sheet;

/**
 * Sales Handle
 *
 * Adds a "Sales" (total_sales) column to the Google Sheet sync.
 * The column is disabled by default and can be enabled from Settings.
 * When an order status changes to processing/completed, the affected
 * products are re-synced so the sales count stays up-to-date in the sheet.
 *
 * @since 2.0.1.4
 * @author CodeAstrology Team <codersaiful@gmail.com>
 * @package PSSG_Sync_Sheet
 */
class Sales_Handle extends Admin_Base
{
    use Standalone;

    public function __construct()
    {
        parent::__construct();

        // Add Sales column to the products columns list (conditional on setting)
        add_filter( 'pssg_products_columns', [ $this, 'handle_products_columns' ] );

        // Render the toggle row in the Settings page
        add_action( 'pssg_admin_section_bottom', [ $this, 'render_settings' ], 10, 2 );

        // When an order reaches processing or completed status, sync sales count to sheet
        if ( $this->is_sales_column_enabled() ) {
            add_action( 'woocommerce_order_status_changed', [ $this, 'on_order_status_changed' ], 10, 3 );
        }
    }

    /**
     * Check whether the Sales column is enabled in settings.
     *
     * @return bool
     */
    public function is_sales_column_enabled()
    {
        $on_off = $this->configs['on_off_total_sales'] ?? 'off';
        return ( $on_off === 'on' );
    }

    /**
     * Conditionally add the "Sales" column to the sheet columns list.
     *
     * @param array $columns
     * @return array
     */
    public function handle_products_columns( $columns )
    {
        if ( ! $this->is_sales_column_enabled() ) {
            return $columns;
        }

        if ( isset( $columns['total_sales'] ) ) {
            return $columns;
        }

        $columns = $this->array_insert_after(
            $columns,
            [
                'total_sales' => [
                    'type'  => 'cf',
                    'title' => __( 'Sales_Count', 'product-sync-master-sheet' ),
                ],
            ],
            '_sale_price'
        );

        return $columns;
    }

    /**
     * Triggered when an order status changes.
     * If the new status is processing, completed, or on-hold, sync the ordered products
     * so the sales count is updated in Google Sheet.
     *
     * @param int    $order_id
     * @param string $old_status
     * @param string $new_status
     * @return void
     */
    public function on_order_status_changed( $order_id, $old_status, $new_status )
    {
        // if ( ! in_array( $new_status, [ 'processing', 'completed', 'on-hold' ], true ) ) {
        //     return;
        // }

        $order = wc_get_order( $order_id );
        if ( ! $order ) {
            return;
        }

        $product_ids = [];
        foreach ( $order->get_items() as $item ) {
            /** @var \WC_Order_Item_Product $item */
            $product_id = $item->get_product_id();
            $variation_id = $item->get_variation_id();

            if ( $variation_id ) {
                $product_ids[ $variation_id ] = $variation_id;
            }
            if ( $product_id ) {
                $product_ids[ $product_id ] = $product_id;
            }
        }

        if ( empty( $product_ids ) ) {
            return;
        }

        // Store the IDs for deferred sync (same mechanism used by stock updates)
        $temp_key = 'pssg_temp_stock_ids';
        $existing = get_option( $temp_key, [] );
        foreach ( $product_ids as $pid ) {
            $existing[ $pid ] = $pid;
        }
        update_option( $temp_key, $existing );

        // Schedule the deferred sync event (fires 2 seconds later)
        wp_schedule_single_event(
            time() + 2,
            'order_event_trigger_hook',
            [ 'product_id' ]
        );
    }

    /**
     * Render the Settings toggle row for the Sales column.
     *
     * @param array  $saved_data
     * @param string $page_name
     * @return void
     */
    public function render_settings( $saved_data, $page_name )
    {
        if ( $page_name !== 'settings' ) {
            return;
        }

        $on_off       = $saved_data['on_off_total_sales'] ?? 'off';
        $checked      = ( $on_off === 'on' ) ? 'checked' : '';
        ?>
        <tr>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="on_off_total_sales">
                            <?php echo esc_html__( 'No of Sales', 'product-sync-master-sheet' ); ?>
                        </label>
                    </div>
                    <div class="form-field col-lg-8">
                        <label class="switch">
                            <input name="on_off_total_sales" type="checkbox" id="on_off_total_sales" <?php echo esc_attr( $checked ); ?>>
                            <div class="slider round">
                                <span class="on">ON</span><span class="off">OFF</span>
                            </div>
                        </label>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-form-info">
                    <p><?php echo esc_html__( 'Enable/Disable Sales count column in Google Sheet. When enabled, a "Sales" column will be added showing the total number of units sold per product.', 'product-sync-master-sheet' ); ?></p>
                </div>
            </td>
        </tr>
        <?php
    }
}
