<?php
/*
Plugin Name: Sincotechs Video Chat
Description: Responsive webcam video chat with rooms, flags, mute, full-screen and license protection.
Version: 1.0.0
Author: Sincotechs
Text Domain: sincotechs-videochat
*/

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

class Sincotechs_Video_Chat {

    const OPTION_LICENSE_KEY   = 'svc_license_key';
    const OPTION_DEFAULT_COLOR = 'svc_default_text_color';
    const OPTION_BLOCKED_USERS = 'svc_blocked_users';
    const OPTION_CHAT_STATE    = 'svc_chat_state';

    public static function activate() {
        if (!get_option(self::OPTION_DEFAULT_COLOR)) {
            add_option(self::OPTION_DEFAULT_COLOR, '#333333');
        }
        if (!get_option(self::OPTION_CHAT_STATE)) {
            $initial = array(
                'rooms' => array(
                    'Lobby' => array(
                        'created_by' => 'system',
                        'created_at' => time()
                    )
                ),
                'messages' => array(
                    'Lobby' => array()
                ),
                'users' => array()
            );
            add_option(self::OPTION_CHAT_STATE, $initial);
        }
    }

    public function __construct() {
        add_shortcode('sincotechs_videochat', array($this, 'render_shortcode'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));

        add_action('admin_menu', array($this, 'admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));

        add_action('wp_ajax_svc_get_state', array($this, 'ajax_get_state'));
        add_action('wp_ajax_nopriv_svc_get_state', array($this, 'ajax_get_state'));

        add_action('wp_ajax_svc_post_message', array($this, 'ajax_post_message'));
        add_action('wp_ajax_nopriv_svc_post_message', array($this, 'ajax_post_message'));

        add_action('wp_ajax_svc_update_profile', array($this, 'ajax_update_profile'));
        add_action('wp_ajax_nopriv_svc_update_profile', array($this, 'ajax_update_profile'));

        add_action('wp_ajax_svc_create_room', array($this, 'ajax_create_room'));
        add_action('wp_ajax_nopriv_svc_create_room', array($this, 'ajax_create_room'));

        add_action('wp_ajax_svc_switch_room', array($this, 'ajax_switch_room'));
        add_action('wp_ajax_nopriv_svc_switch_room', array($this, 'ajax_switch_room'));

        add_action('wp_ajax_svc_block_user', array($this, 'ajax_block_user'));
    }

    /* -------- Helpers -------- */

    private function get_session_id() {
        // Use a cookie-based session id so reloading the page keeps the same user.
        if (isset($_COOKIE['svc_session_id']) && !empty($_COOKIE['svc_session_id'])) {
            return sanitize_text_field($_COOKIE['svc_session_id']);
        }

        $id = 'sess_' . wp_generate_password(16, false, false);
        // 30 days
        $expire = time() + 30 * 24 * 60 * 60;
        setcookie('svc_session_id', $id, $expire, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
        $_COOKIE['svc_session_id'] = $id;

        return $id;
    }

    private function license_active() {
        $key = trim(get_option(self::OPTION_LICENSE_KEY, ''));
        if (empty($key)) {
            return false;
        }

        $site_url = home_url('/');
        $response = wp_remote_post('https://sincotechs.com/wp-json/svc-license/v1/validate', array(
            'timeout' => 10,
            'body'    => array(
                'license_key' => $key,
                'site_url'    => $site_url
            )
        ));

        if (is_wp_error($response)) {
            return false;
        }

        $data = json_decode(wp_remote_retrieve_body($response), true);
        if (!is_array($data)) {
            return false;
        }

        if (!empty($data['success']) && isset($data['status']) && $data['status'] === 'active') {
            return true;
        }

        return false;
    }

    private function detect_country_code() {
        // Placeholder; JS will auto-detect. Use XX as unknown.
        return 'XX';
    }

    private function get_state() {
        $state = get_option(self::OPTION_CHAT_STATE);
        if (!$state || !is_array($state)) {
            $state = array(
                'rooms' => array(
                    'Lobby' => array(
                        'created_by' => 'system',
                        'created_at' => time()
                    )
                ),
                'messages' => array(
                    'Lobby' => array()
                ),
                'users' => array()
            );
        }
        return $state;
    }

    private function save_state($state) {
        update_option(self::OPTION_CHAT_STATE, $state);
    }

    private function get_blocked_list() {
        $raw = get_option(self::OPTION_BLOCKED_USERS, '');
        $lines = array_filter(array_map('trim', explode("\n", $raw)));
        return $lines;
    }

    /* -------- Front-end -------- */

    public function enqueue_assets() {
        if (!is_singular()) {
            return;
        }

        wp_enqueue_style(
            'svc-videochat',
            plugin_dir_url(__FILE__) . 'assets/css/videochat.css',
            array(),
            '1.0.0'
        );

        wp_enqueue_script(
            'svc-videochat',
            plugin_dir_url(__FILE__) . 'assets/js/videochat.js',
            array('jquery'),
            '1.0.0',
            true
        );

        // Socket.io client for WebRTC signaling
        wp_enqueue_script(
            'svc-socketio',
            'https://cdn.socket.io/4.7.5/socket.io.min.js',
            array(),
            '4.7.5',
            true
        );

        $current_user = wp_get_current_user();
        $session_id = $this->get_session_id();

        wp_localize_script('svc-videochat', 'SVC_SETTINGS', array(
            'ajax_url'        => admin_url('admin-ajax.php'),
            'nonce'           => wp_create_nonce('svc_nonce'),
            'session_id'      => $session_id,
            'is_admin'        => current_user_can('manage_options'),
            'user_name'       => ($current_user && $current_user->exists()) ? $current_user->display_name : 'User',
            'country_code'    => $this->detect_country_code(),
            'license_active'  => $this->license_active(),
            'default_color'   => get_option(self::OPTION_DEFAULT_COLOR, '#333333'),
            'signaling_url'   => 'https://overheid.streamlineradio.net'
        ));
    }

    public function render_shortcode($atts) {
        if (!$this->license_active()) {
            return '<div class="svc-license-warning">Video chat is not active. Please contact the site administrator.</div>';
        }

        ob_start();
        include plugin_dir_path(__FILE__) . 'templates/videochat-view.php';
        return ob_get_clean();
    }

    /* -------- Admin settings -------- */

    public function admin_menu() {
        add_menu_page(
            'Sincotechs Video Chat',
            'Sincotechs VC',
            'manage_options',
            'sincotechs-videochat',
            array($this, 'settings_page'),
            'dashicons-video-alt3'
        );
    }

    public function register_settings() {
        register_setting('svc_settings_group', self::OPTION_LICENSE_KEY);
        register_setting('svc_settings_group', self::OPTION_DEFAULT_COLOR);
        register_setting('svc_settings_group', self::OPTION_BLOCKED_USERS);
    }

    public function settings_page() {
        $license_key = get_option(self::OPTION_LICENSE_KEY);
        $license_ok  = false;
        if (!empty($license_key)) {
            $license_ok = $this->license_active();
        }
        ?>
        <div class="wrap">
            <h1>Sincotechs Video Chat Settings</h1>
            <form method="post" action="options.php">
                <?php settings_fields('svc_settings_group'); ?>
                <?php do_settings_sections('svc_settings_group'); ?>

                <table class="form-table">
                    <tr valign="top">
                        <th scope="row">License key</th>
                        <td>
                            <input type="text" name="<?php echo esc_attr(self::OPTION_LICENSE_KEY); ?>"
                                   value="<?php echo esc_attr($license_key); ?>" size="40">
                            <p class="description">
                                Enter the license key generated on sincotechs.com (Webcam License).
                            </p>
                            <?php if (empty($license_key)): ?>
                                <p><strong>Status:</strong> <span style="color:#666;">No license key set.</span></p>
                            <?php else: ?>
                                <?php if ($license_ok): ?>
                                    <p><strong>Status:</strong> <span style="color:green;">License is active.</span></p>
                                <?php else: ?>
                                    <p><strong>Status:</strong> <span style="color:red;">License is NOT active.</span></p>
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                    </tr>

                    <tr valign="top">
                        <th scope="row">Default chat text color</th>
                        <td>
                            <input type="text" name="<?php echo esc_attr(self::OPTION_DEFAULT_COLOR); ?>"
                                   value="<?php echo esc_attr(get_option(self::OPTION_DEFAULT_COLOR, '#333333')); ?>"
                                   class="regular-text">
                        </td>
                    </tr>

                    <tr valign="top">
                        <th scope="row">Blocked sessions</th>
                        <td>
                            <textarea name="<?php echo esc_attr(self::OPTION_BLOCKED_USERS); ?>"
                                      rows="5" cols="50"><?php echo esc_textarea(get_option(self::OPTION_BLOCKED_USERS, '')); ?></textarea>
                            <p class="description">One session ID per line. Use the "Block" button in the chat.</p>
                        </td>
                    </tr>
                </table>

                <?php submit_button(); ?>
            </form>
        </div>
        <?php
    }

    /* -------- AJAX -------- */

    public function ajax_get_state() {
        check_ajax_referer('svc_nonce', 'nonce');

        $session_id = sanitize_text_field($_POST['session_id']);
        $state = $this->get_state();

        // ensure user is registered
        if (!isset($state['users'][$session_id])) {
            $current_user = wp_get_current_user();
            $state['users'][$session_id] = array(
                'name'    => ($current_user && $current_user->exists()) ? $current_user->display_name : 'User',
                'country' => 'XX',
                'color'   => get_option(self::OPTION_DEFAULT_COLOR, '#333333'),
                'muted'   => false,
                'updated' => time()
            );
            $this->save_state($state);
        }

        wp_send_json_success(array('state' => $state));
    }

    public function ajax_post_message() {
        check_ajax_referer('svc_nonce', 'nonce');

        $session_id = sanitize_text_field($_POST['session_id']);
        $room       = sanitize_text_field($_POST['room']);
        $text       = wp_kses_post($_POST['text']);
        $color      = sanitize_hex_color($_POST['color']);

        $blocked = $this->get_blocked_list();
        if (in_array($session_id, $blocked)) {
            wp_send_json_error(array('message' => 'You are blocked.'));
        }

        $state = $this->get_state();
        if (!isset($state['messages'][$room])) {
            $state['messages'][$room] = array();
        }

        $user_name = isset($state['users'][$session_id]['name']) ? $state['users'][$session_id]['name'] : 'User';
        $country   = isset($state['users'][$session_id]['country']) ? $state['users'][$session_id]['country'] : 'XX';

        $state['messages'][$room][] = array(
            'session_id' => $session_id,
            'user_name'  => $user_name,
            'country'    => $country,
            'text'       => $text,
            'color'      => $color ? $color : get_option(self::OPTION_DEFAULT_COLOR, '#333333'),
            'time'       => time()
        );

        $this->save_state($state);

        wp_send_json_success(array('messages' => $state['messages'][$room]));
    }

    public function ajax_update_profile() {
        check_ajax_referer('svc_nonce', 'nonce');

        $session_id = sanitize_text_field($_POST['session_id']);
        $name       = sanitize_text_field($_POST['name']);
        $color      = sanitize_hex_color($_POST['color']);
        $country    = sanitize_text_field($_POST['country']);
        $muted      = ($_POST['muted'] === 'true');

        $state = $this->get_state();
        if (!isset($state['users'][$session_id])) {
            $state['users'][$session_id] = array();
        }

        $state['users'][$session_id]['name']    = $name ? $name : 'User';
        $state['users'][$session_id]['color']   = $color ? $color : get_option(self::OPTION_DEFAULT_COLOR, '#333333');
        $state['users'][$session_id]['country'] = $country ? $country : 'XX';
        $state['users'][$session_id]['muted']   = $muted;
        $state['users'][$session_id]['updated'] = time();

        $this->save_state($state);

        wp_send_json_success(array('user' => $state['users'][$session_id]));
    }

    public function ajax_create_room() {
        check_ajax_referer('svc_nonce', 'nonce');

        $room_name = sanitize_text_field($_POST['room_name']);
        $creator   = sanitize_text_field($_POST['creator']);

        $state = $this->get_state();
        if (!isset($state['rooms'][$room_name])) {
            $state['rooms'][$room_name] = array(
                'created_by' => $creator,
                'created_at' => time()
            );
            $state['messages'][$room_name] = array();
            $this->save_state($state);
        }

        wp_send_json_success(array('rooms' => $state['rooms']));
    }

    public function ajax_switch_room() {
        check_ajax_referer('svc_nonce', 'nonce');

        $room = sanitize_text_field($_POST['room']);
        $state = $this->get_state();
        if (!isset($state['messages'][$room])) {
            $state['messages'][$room] = array();
            $this->save_state($state);
        }

        wp_send_json_success(array(
            'messages' => $state['messages'][$room],
            'room'     => $room
        ));
    }

    public function ajax_block_user() {
        check_ajax_referer('svc_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Not allowed'));
        }

        $session_id = sanitize_text_field($_POST['session_id']);
        $blocked = $this->get_blocked_list();

        if (!in_array($session_id, $blocked)) {
            $blocked[] = $session_id;
            update_option(self::OPTION_BLOCKED_USERS, implode("\n", $blocked));
        }

        wp_send_json_success(array('blocked' => $blocked));
    }
}

// activation
function svc_videochat_activate() {
    Sincotechs_Video_Chat::activate();
}
register_activation_hook(__FILE__, 'svc_videochat_activate');

// bootstrap
new Sincotechs_Video_Chat();
