<?php
if (!defined('ABSPATH'))
exit; // Exit if accessed directly
class DevsAccounting_Setting{
    public function __construct()
    {
        add_action('rest_api_init', [$this, 'setting_api_endpoint']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_paypal_sdk']);
    }

    // Define your custom endpoint
    public function setting_api_endpoint() {
        register_rest_route('devs-accounting/v1', '/add-setting', array(
            'methods' => 'POST',
            'callback' => [$this, 'save_setting_data'],
            'permission_callback' => [$this, 'verify_settings_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/settings', array(
            'methods' => 'get', 
            'callback' => [$this, 'get_settings'],
            'permission_callback' => function () {
                return true;
            },
        ));
        
        register_rest_route('devs-accounting/v1', '/get-setting/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'get_single_setting'],
            'permission_callback' => function () {
                return true;
            },
        ));
        
        register_rest_route('devs-accounting/v1', '/delete-setting/(?P<id>\d+)', array(
            'methods' => 'get', 
            'callback' => [$this, 'delete_single_setting'],
            'permission_callback' => [$this, 'verify_settings_nonce'],
        ));
        
    }

    function verify_settings_nonce($request) {
        $nonce = $request->get_header('X-WP-Nonce');
        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('rest_forbidden', esc_html__('Invalid nonce.', 'devs-accounting'), array('status' => 403));
        }
        return true;
    }

    public function get_settings() {
        // Retrieve the option value from the database
        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings, true);
        
        // Add the home URL to settings
        $settings['home_url'] = home_url();
        
        // Add folder_name to the settings
        $settings['folder_name'] = DEVSACCOUNTING_PLUGIN_FOLDER_NAME;
        
        // Check if the settings exist and return them
        if ($settings !== false) {
            return rest_ensure_response($settings);
        } else {
            // If settings not found, return an empty response or handle the error accordingly
            return rest_ensure_response(array());
        }
    }
    
       
    
	public function get_single_setting($request) 
	{
		global $wpdb;

		$table_name = esc_sql($wpdb->prefix . 'dac_settings');

		$item_id = isset($request['id']) ? intval($request['id']) : 0;
		if (!$item_id) {
			return new WP_Error(
				'invalid_id', 
				esc_html__('Invalid ID.', 'devs-accounting'), 
				['status' => 400]
			);
		}

		$sql = $wpdb->prepare(
			"SELECT * FROM {$table_name} WHERE ID = %d",
			$item_id
		);

		$setting = $wpdb->get_row( $sql ); 

		if ($setting) {
			return rest_ensure_response($setting);
		} else {
			return new WP_Error(
				'task_not_found',
				esc_html__('Task not found', 'devs-accounting'),
				['status' => 404]
			);
		}
	}


    public function delete_single_setting($request) {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_settings';

        $cat_id = isset($request['id']) ? intval($request['id']) : 0;

        // Validate item ID
        if ($cat_id <= 0) {
            return new WP_Error( 'invalid_item_id', esc_html__( 'Invalid item ID', 'devs-accounting' ), array( 'status' => 400 ) );
        }
         // Check if the item exists
         $existing_setting = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE ID = %d",
                $cat_id
            )
        );

        if (!$existing_setting) {
            return new WP_Error( 'item_not_found', esc_html__( 'Item not found', 'devs-accounting' ), array( 'status' => 404 ) );
        }

        // Get current time
        $current_time = gmdate('Y-m-d H:i:s'); // 'mysql' format returns time in MySQL datetime format

        // Soft delete the item by updating its status
        $result = $wpdb->update(
            $table_name,
            array( 
                'deleted_at' => $current_time,
                ),
            array( 'id' => $cat_id ),
        );

        // Check if update was successful
        if ($result === false) {
            return new WP_Error( 'soft_delete_failed', esc_html__( 'Failed to soft delete item', 'devs-accounting' ), array( 'status' => 500 ) );
        }

        // Return success response
        return rest_ensure_response( array( 'message' => esc_html__('Item soft deleted successfully', 'devs-accounting') ) );
    }


    public function save_setting_data($request) {
        $params = json_decode($request->get_body(), true);
        $newData = isset($params['arrayData']) ? $params['arrayData'] : [];
    
        if (empty($newData) || !is_array($newData)) {
            return new WP_REST_Response(['message' => esc_html__('Array data is required and must be a valid array.', 'devs-accounting')], 400);
        }
    
        $option_name = 'devsaccounting_settings';
    
        $existing_option = get_option($option_name);
        $existing_data = !empty($existing_option) ? json_decode($existing_option, true) : [];
    
        if (!is_array($existing_data)) {
            $existing_data = [];
        }

        $merged_data = array_merge($existing_data, $newData);

        if ($existing_data !== $merged_data) {
            $updated = update_option($option_name, wp_json_encode($merged_data));
            $message = $updated ? esc_html__('Setting updated successfully!', 'devs-accounting') : esc_html__('Failed to update setting.', 'devs-accounting');
        } else {
            $message = esc_html__('No changes made.', 'devs-accounting');
        }
    
        return new WP_REST_Response([
            'message' => $message,
            'data' => $merged_data,
        ], 200);
    }

    public function enqueue_paypal_sdk() {
        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings, true);
    
        if (!isset($settings['paypal_client_id']) || empty($settings['paypal_client_id'])) {
            return;
        }
    
        // Enqueue the PayPal SDK
        wp_enqueue_script(
            'paypal-sdk',
            "https://www.paypal.com/sdk/js?client-id={$settings['paypal_client_id']}&components=buttons",
            array(),
            null,
            true
        );
    }

    public function save_setting_data_for_license($license_key) {
        $settings = get_option('devsaccounting_settings');
        $settings = $settings ? json_decode($settings, true) : [];
        $settings['devsaccounting_necessary_cookies'] = $license_key;
        $this->save_setting_data(['arrayData' => $settings]);
    }
    

}

$settings = new DevsAccounting_Setting();