<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @package    Surftrust
 * @subpackage Surftrust/public
 */
class Surftrust_Public
{

    private $plugin_name;
    private $version;

    public function __construct($plugin_name, $version)
    {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Register the stylesheets and scripts for the public-facing side of the site.
     */
    public function enqueue_scripts()
    {
        wp_enqueue_style(
            'dashicons'
        );
        wp_enqueue_style(
            $this->plugin_name,
            plugin_dir_url(__FILE__) . 'css/surftrust-public.css',
            array(),
            $this->version,
            'all'
        );

        wp_enqueue_script(
            $this->plugin_name,
            plugin_dir_url(__FILE__) . '../build/public.js',
            array(),
            $this->version,
            true
        );

        global $wpdb;
        $table_name = $wpdb->prefix . 'surftrust_settings';
        $results = $wpdb->get_results("SELECT setting_name, setting_value FROM $table_name");

        $all_settings = [];
        foreach ($results as $row) {
            $decoded_value = json_decode($row->setting_value, true);
            // If the value is an array, merge it into the main settings array.
            if (is_array($decoded_value)) {
                $all_settings = array_merge($all_settings, $decoded_value);
            }
        }
        $current_id = 0;
        if (is_front_page()) {
            $current_id = (int) get_option('page_on_front');
        } elseif (function_exists('is_shop') && is_shop()) {
            $current_id = (int) get_option('woocommerce_shop_page_id');
        } elseif (is_singular()) {
            $current_id = get_the_ID();
        }

        wp_localize_script(
            $this->plugin_name,
            'surftrust_globals',
            array(
                'customize' => $all_settings ?: [],
                'api_url'  => untrailingslashit(rest_url('surftrust/v1')),
                'plugin_url' => plugin_dir_url(dirname(__FILE__)),
                'current_page_id' => $current_id,
            )
        );
    }
}
