<?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;

class Description_Handle extends Admin_Base
{
    use Standalone;

    public function __construct()
    {
        parent::__construct();
        add_action( 'pssg_admin_section_bottom', [$this, 'render_settings'], 10, 2 );

        // Update Description & Short Description from Sheet/Quick Edit
        add_action( 'pssg_product_update_request', [$this, 'update_product'] );

        // Auto Wrap Description & Short Description
        // add_action( 'pssg_push_to_sheet_on_success', [$this, 'apply_auto_wrap'], 10, 2 );

        //Add at column list for product table and Google Sheet
        add_filter( 'pssg_products_columns', [$this, 'handle_products_columns'] );

    }

    public static $is_wrapping = false;

    public function apply_auto_wrap() //$data_response, $pushed_data
    {
        // if premumium version is not active, do not apply auto wrap
        if ( !pssg_is_premium() ) return;
        if ( self::$is_wrapping ) return;

        $auto_wrap = $this->configs['on_off_auto_wrap'] ?? 'off';
        $wrap_strategy = ( $auto_wrap == 'on' ) ? 'WRAP' : 'CLIP';

        $sheet = Sheet::init();
        $spreadsheet_id = $sheet->spreadsheet_id;
        $API_KEY = $sheet->API_KEY;

        if ( empty( $spreadsheet_id ) || empty( $API_KEY ) ) return;

        $products = new Products();
        $active_cols = $products->get_active_columns();
        $col_keys = array_keys( $active_cols );

        $requests = [];
        $sheet_details = $sheet->get_current_sheet_name();
        $sheetId = $sheet_details['gid'] ?? 0;

        foreach ( ['description', 'short_description'] as $key ) {
            $index = array_search( $key, $col_keys );
            if ( $index !== false ) {
                $requests[] = [
                    'repeatCell' => [
                        'range' => [
                            'sheetId' => (int)$sheetId,
                            'startColumnIndex' => $index,
                            'endColumnIndex' => $index + 1,
                        ],
                        'cell' => [
                            'userEnteredFormat' => [
                                'wrapStrategy' => $wrap_strategy
                            ]
                        ],
                        'fields' => 'userEnteredFormat.wrapStrategy'
                    ]
                ];
            }
        }

        if ( $auto_wrap == 'off' ) {
            // Force reset row height to default when wrap is OFF
            $requests[] = [
                'updateDimensionProperties' => [
                    'range' => [
                        'sheetId' => (int)$sheetId,
                        'dimension' => 'ROWS',
                        'startIndex' => 1,
                        'endIndex' => 5000
                    ],
                    'properties' => [
                        'pixelSize' => 21
                    ],
                    'fields' => 'pixelSize'
                ]
            ];
        } else {
            // Auto resize for rows when WRAP is ON to ensure content visibility
            $requests[] = [
                'autoResizeDimensions' => [
                    'dimensions' => [
                        'sheetId' => (int)$sheetId,
                        'dimension' => 'ROWS',
                        'startIndex' => 1,
                        'endIndex' => 5000
                    ]
                ]
            ];
        }

        if ( ! empty( $requests ) ) {
            $data = [ 'requests' => $requests ];
            $api_url = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheet_id:batchUpdate?key=$API_KEY";
            
            self::$is_wrapping = true;
            $sheet->push_to_sheet( $api_url, $data, 'POST' );
            self::$is_wrapping = false;
        }
    }

    /**
     * Update product description and short description
     *
     * @param array $requested_data
     * @return void
     */
    public function update_product($requested_data)
    {
        $product_id = $requested_data['product_id'] ?? 0;
        if (empty($product_id) || !is_numeric($product_id))
            return;

        $param_value = $requested_data['param_value'] ?? [];

        $has_description = isset($param_value['Description']);
        $has_short_desc = isset($param_value['Short_Description']);

        if (!$has_description && !$has_short_desc)
            return;

        $product = wc_get_product($product_id);
        if (!$product)
            return;

        $update = false;

        if ($has_description) {
            $product->set_description($param_value['Description']);
            $update = true;
        }

        if ($has_short_desc && $product->get_type() !== 'variation') {
            $product->set_short_description($param_value['Short_Description']);
            $update = true;
        }

        if ($update) {
            $product->save();
        }
    }

    /**
     * Handle products columns
     * Add new column for Description and Short Description if enabled in settings
     * 
     *
     * @param array $columns
     * @return array
     */
    public function handle_products_columns( $columns ) {

        $on_off_desc = $this->configs['on_off_description'] ?? 'off';
        $on_off_short_desc = $this->configs['on_off_short_description'] ?? 'off';

        if ( $on_off_desc == 'on' && !isset( $columns['_description'] ) ) {
            $columns = $this->array_insert_after(
                $columns,
                [
                    'description'     => [
                        'type'  => 'normal',
                        'title' => __( 'Description', 'product-sync-master-sheet' )
                    ],
                ],
                'title'
            );
        }

        if ( $on_off_short_desc == 'on' && !isset( $columns['_short_description'] ) ) {
            $columns = $this->array_insert_after(
                $columns,
                [
                    'short_description'     => [
                        'type'  => 'normal',
                        'title' => __( 'Short_Description', 'product-sync-master-sheet' )
                    ],
                ],
                'title'
            );
        }
        
        return $columns;
    }

    public function render_settings($saved_data, $page_name)
    {
        if( $page_name !== 'settings' ) return;

        $on_off_desc = $saved_data['on_off_description'] ?? 'off';
        $checked_desc = $on_off_desc == 'on' ? 'checked' : '';

        $on_off_short_desc = $saved_data['on_off_short_description'] ?? 'off';
        $checked_short_desc = $on_off_short_desc == 'on' ? 'checked' : '';

        $on_off_auto_wrap = $saved_data['on_off_auto_wrap'] ?? 'off';
        $checked_auto_wrap = $on_off_auto_wrap == 'on' ? 'checked' : '';
        ?>
        <tr>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="on_off_description"> <?php echo esc_html__( 'Description', 'product-sync-master-sheet' ); ?></label>
                    </div>
                    <div class="form-field col-lg-8">
                        <label class="switch">
                            <input name="on_off_description" type="checkbox" id="on_off_description" <?php echo esc_attr( $checked_desc ); ?>>
                            <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 Product Description column in Google Sheet.', 'product-sync-master-sheet' ); ?></p>
                </div> 
            </td>
        </tr>

        <tr>
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="on_off_short_description"> <?php echo esc_html__( 'Short Description', 'product-sync-master-sheet' ); ?></label>
                    </div>
                    <div class="form-field col-lg-8">
                        <label class="switch">
                            <input name="on_off_short_description" type="checkbox" id="on_off_short_description" <?php echo esc_attr( $checked_short_desc ); ?>>
                            <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 Product Short Description column in Google Sheet.', 'product-sync-master-sheet' ); ?></p>
                </div> 
            </td>
        </tr>

        <tr class="<?php echo esc_attr( pssg_is_premium() ? '' : 'pssg-premium-row' ); ?>">
            <td>
                <div class="pssg-form-control">
                    <div class="form-label col-lg-4">
                        <label for="on_off_auto_wrap"> <?php echo esc_html__( 'Auto Wrap Content', 'product-sync-master-sheet' ); ?></label>
                    </div>
                    <div class="form-field col-lg-8">
                        <label class="switch">
                            <input name="on_off_auto_wrap" type="checkbox" id="on_off_auto_wrap" <?php echo esc_attr( $checked_auto_wrap ); ?>>
                            <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__( 'Automatically wrap text for Description and Short Description columns.', 'product-sync-master-sheet' ); ?></p>
                </div> 
            </td>
        </tr>
        <?php
    }
}
