<?php
/*
Plugin Name: Sookie CMP
Plugin URI: https://app.sookie.eu/articles/sookie-installation-wordpress
Description: GDPR/CCPA compliant cookie consent banner with Google Consent Mode v2 support.
Version: 1.0.0
Author: Jay Singh
Author URI: https://app.sookie.eu
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: sookie-cmp
Domain Path: /languages
*/

if (!defined('ABSPATH')) {
    exit;
}

class Sookie_CMP_Plugin {

    const OPTION_KEY = 'sookie_cmp_settings';
    const SCRIPT_SRC = 'https://app.sookie.eu/api/cookie-consent';

    public function __construct() {

        // Admin
        add_action('admin_menu', [$this, 'add_menu_page']);
        add_action('admin_init', [$this, 'register_settings']);

        // Frontend script
        add_action('wp_enqueue_scripts', [$this, 'enqueue_script']);
        add_filter('script_loader_tag', [$this, 'add_sookie_attribute'], 10, 3);

        // Plugin settings link
        add_filter(
            'plugin_action_links_' . plugin_basename(__FILE__),
            [$this, 'add_settings_link']
        );
    }

    /* -------------------------------------------------
     * Admin Menu
     * ------------------------------------------------- */

    public function add_menu_page() {
        add_menu_page(
            esc_html__('Sookie CMP', 'sookie-cmp'),
            esc_html__('Sookie CMP', 'sookie-cmp'),
            'manage_options',
            'sookie-cmp',
            [$this, 'render_settings_page'],
            'dashicons-shield-alt',
            60
        );
    }

    public function add_settings_link($links) {
        $url = admin_url('admin.php?page=sookie-cmp');
        $settings_link = '<a href="' . esc_url($url) . '">' . esc_html__('Settings', 'sookie-cmp') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    /* -------------------------------------------------
     * Settings
     * ------------------------------------------------- */

    public function register_settings() {

        register_setting(
            'sookie_cmp_group',
            self::OPTION_KEY,
            [$this, 'sanitize_settings']
        );

        add_settings_section(
            'sookie_cmp_main',
            esc_html__('Sookie CMP Settings', 'sookie-cmp'),
            function () {
                echo '<p>' . esc_html__('Enter your Sookie Domain Group ID.', 'sookie-cmp') . '</p>';
            },
            'sookie-cmp'
        );

        add_settings_field(
            'sookie_id',
            esc_html__('Domain Group ID', 'sookie-cmp'),
            [$this, 'field_sookie_id'],
            'sookie-cmp',
            'sookie_cmp_main'
        );

        add_settings_field(
            'placement',
            esc_html__('Placement', 'sookie-cmp'),
            [$this, 'field_placement'],
            'sookie-cmp',
            'sookie_cmp_main'
        );

        add_settings_field(
            'frontend_only',
            esc_html__('Frontend only', 'sookie-cmp'),
            [$this, 'field_frontend_only'],
            'sookie-cmp',
            'sookie_cmp_main'
        );
    }

    public function sanitize_settings($input) {

        $out = [];

        $out['sookie_id'] = isset($input['sookie_id'])
            ? sanitize_text_field(trim($input['sookie_id']))
            : '';

        $out['placement'] = (isset($input['placement']) && in_array($input['placement'], ['head', 'footer'], true))
            ? $input['placement']
            : 'head';

        $out['frontend_only'] = !empty($input['frontend_only']) ? 1 : 0;

        return $out;
    }

    private function get_settings() {

        $defaults = [
            'sookie_id'   => '',
            'placement'   => 'head',
            'frontend_only' => 1,
        ];

        $settings = get_option(self::OPTION_KEY, []);

        return wp_parse_args($settings, $defaults);
    }

    /* -------------------------------------------------
     * Field Renderers
     * ------------------------------------------------- */

    public function field_sookie_id() {
        $s = $this->get_settings();

        printf(
            '<input type="text" name="%1$s[sookie_id]" value="%2$s" class="regular-text" />',
            esc_attr(self::OPTION_KEY),
            esc_attr($s['sookie_id'])
        );
    }

    public function field_placement() {
        $s = $this->get_settings();
        ?>
        <select name="<?php echo esc_attr(self::OPTION_KEY); ?>[placement]">
            <option value="head" <?php selected($s['placement'], 'head'); ?>>
                <?php echo esc_html__('Head (recommended)', 'sookie-cmp'); ?>
            </option>
            <option value="footer" <?php selected($s['placement'], 'footer'); ?>>
                <?php echo esc_html__('Footer', 'sookie-cmp'); ?>
            </option>
        </select>
        <?php
    }

    public function field_frontend_only() {
        $s = $this->get_settings();

        printf(
            '<label><input type="checkbox" name="%1$s[frontend_only]" value="1" %2$s /> %3$s</label>',
            esc_attr(self::OPTION_KEY),
            checked(1, (int) $s['frontend_only'], false),
            esc_html__('Only load on public pages', 'sookie-cmp')
        );
    }

    /* -------------------------------------------------
     * Settings Page
     * ------------------------------------------------- */

    public function render_settings_page() {

        if (!current_user_can('manage_options')) {
            return;
        }

        ?>
        <div class="wrap">
            <h1><?php echo esc_html__('Sookie CMP', 'sookie-cmp'); ?></h1>

            <form method="post" action="options.php">
                <?php
                settings_fields('sookie_cmp_group');
                do_settings_sections('sookie-cmp');
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }

    /* -------------------------------------------------
     * Script Loading
     * ------------------------------------------------- */

    private function should_load() {

        $s = $this->get_settings();

        if (empty($s['sookie_id'])) {
            return false;
        }

        if (
            $s['frontend_only'] &&
            (is_admin() || wp_doing_ajax() || is_feed() || is_trackback())
        ) {
            return false;
        }

        return true;
    }

    public function enqueue_script() {

        if (!$this->should_load()) {
            return;
        }

        $s = $this->get_settings();

        wp_register_script(
            'sookie-cmp-script',
            esc_url(self::SCRIPT_SRC),
            [],
            null,
            $s['placement'] === 'footer'
        );

        wp_enqueue_script('sookie-cmp-script');
    }

    public function add_sookie_attribute($tag, $handle, $src) {

        if ('sookie-cmp-script' !== $handle) {
            return $tag;
        }

        $s = $this->get_settings();

        if (empty($s['sookie_id'])) {
            return $tag;
        }

        return sprintf(
            '<script src="%1$s" sookie-id="%2$s"></script>',
            esc_url($src),
            esc_attr($s['sookie_id'])
        );
    }
}

new Sookie_CMP_Plugin();
