<?php
/**
 * Class LSC_Shortcodes
 *
 * [live_support_chatter_login]     – Chatter login form.
 * [live_support_chatter_dashboard] – Chatter management dashboard.
 */
class LSC_Shortcodes {

    public function __construct() {
        add_shortcode( 'live_support_chatter_login',     [ $this, 'render_login' ] );
        add_shortcode( 'live_support_chatter_dashboard', [ $this, 'render_dashboard' ] );

        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_assets' ] );

        // template_redirect fires before output but after WP is fully loaded.
        add_action( 'template_redirect', [ $this, 'handle_login' ],  5 );
        add_action( 'template_redirect', [ $this, 'handle_logout' ], 5 );
    }

    /* ------------------------------------------------------------------
     * Assets
     * ------------------------------------------------------------------ */

    public function enqueue_assets() {
        global $post;
        if ( ! $post ) {
            return;
        }

        $is_login     = has_shortcode( $post->post_content, 'live_support_chatter_login' );
        $is_dashboard = has_shortcode( $post->post_content, 'live_support_chatter_dashboard' );

        if ( $is_login || $is_dashboard ) {
            wp_enqueue_style( 'lsc-chatter', LSC_PLUGIN_URL . 'assets/css/chatter.css', [], LSC_VERSION );
        }

        if ( $is_dashboard ) {
            $login_page = (int) get_option( 'lsc_chatter_login_page', 0 );
            wp_enqueue_script( 'lsc-chatter', LSC_PLUGIN_URL . 'assets/js/chatter.js', [ 'jquery' ], LSC_VERSION, true );
            wp_localize_script( 'lsc-chatter', 'lscChatter', [
                'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
                'nonce'    => wp_create_nonce( 'lsc_chatter_nonce' ),
                'soundUrl' => LSC_PLUGIN_URL . 'assets/sounds/notification.mp3',
                'loginUrl' => $login_page ? get_permalink( $login_page ) : wp_login_url(),
                'i18n'     => [
                    'noChats'      => __( 'No active chats yet.', 'live-support-chat' ),
                    'selectChat'   => __( 'Select a chat from the list to start replying.', 'live-support-chat' ),
                    'close'        => __( 'Close chat', 'live-support-chat' ),
                    'send'         => __( 'Send', 'live-support-chat' ),
                    'placeholder'  => __( 'Type your reply…', 'live-support-chat' ),
                    'newMessage'   => __( 'New message!', 'live-support-chat' ),
                    'visitor'      => __( 'Visitor', 'live-support-chat' ),
                    'you'          => __( 'You', 'live-support-chat' ),
                    'confirmClose' => __( 'Close this chat session?', 'live-support-chat' ),
                ],
            ] );
        }
    }

    /* ------------------------------------------------------------------
     * [live_support_chatter_login] shortcode
     * ------------------------------------------------------------------ */

    public function render_login( $atts ) {
        // Already logged in as chatter/admin → bounce to dashboard.
        if ( is_user_logged_in() ) {
            $user = wp_get_current_user();
            if ( in_array( 'chatter', (array) $user->roles, true ) || current_user_can( 'administrator' ) ) {
                $dp = (int) get_option( 'lsc_chatter_dashboard_page', 0 );
                if ( $dp ) {
                    wp_safe_redirect( get_permalink( $dp ) );
                    exit;
                }
            }
        }

        $error = '';
        if ( isset( $_GET['login_error'] ) ) {
            switch ( sanitize_key( $_GET['login_error'] ) ) {
                case 'invalid':
                    $error = __( 'Invalid username or password.', 'live-support-chat' );
                    break;
                case 'no_permission':
                    $error = __( 'You do not have permission to access the chat panel.', 'live-support-chat' );
                    break;
                default:
                    $error = __( 'Login failed. Please try again.', 'live-support-chat' );
            }
        }

        ob_start();
        include LSC_PLUGIN_DIR . 'templates/login-form.php';
        return ob_get_clean();
    }

    /* ------------------------------------------------------------------
     * Login handler – runs on template_redirect before any output
     *
     * Uses get_user_by() + wp_check_password() directly so that
     * third-party plugins hooking into the 'authenticate' filter
     * cannot block our custom login form.
     * ------------------------------------------------------------------ */

    public function handle_login() {
        // Only process our form submission.
        if ( ! isset( $_POST['lsc_login_submit'] ) ) {
            return;
        }

        // CSRF protection.
        $raw_nonce = isset( $_POST['lsc_login_nonce'] )
            ? sanitize_text_field( wp_unslash( $_POST['lsc_login_nonce'] ) )
            : '';

        if ( ! wp_verify_nonce( $raw_nonce, 'lsc_login' ) ) {
            wp_die( esc_html__( 'Security check failed. Please go back and try again.', 'live-support-chat' ) );
        }

        // Accept both new field names (lsc_username/lsc_password) AND the
        // old generic names (username/password) so cached pages still work.
        $username = '';
        $password = '';

        if ( ! empty( $_POST['lsc_username'] ) ) {
            $username = sanitize_text_field( wp_unslash( $_POST['lsc_username'] ) );
        } elseif ( ! empty( $_POST['username'] ) ) {
            $username = sanitize_text_field( wp_unslash( $_POST['username'] ) );
        }

        if ( isset( $_POST['lsc_password'] ) && '' !== $_POST['lsc_password'] ) {
            $password = wp_unslash( $_POST['lsc_password'] );
        } elseif ( isset( $_POST['password'] ) && '' !== $_POST['password'] ) {
            $password = wp_unslash( $_POST['password'] );
        }

        // Build the error redirect URL (always points back to the login page).
        $login_page_id = (int) get_option( 'lsc_chatter_login_page', 0 );
        $error_url     = $login_page_id ? get_permalink( $login_page_id ) : home_url( '/' );

        // Guard: both fields must be filled.
        if ( empty( $username ) || empty( $password ) ) {
            wp_safe_redirect( add_query_arg( 'login_error', 'invalid', $error_url ) );
            exit;
        }

        // ── Step 1: look up the user (accepts username OR e-mail) ──────
        $user_obj = get_user_by( 'login', $username );
        if ( ! $user_obj ) {
            $user_obj = get_user_by( 'email', $username );
        }

        // ── Step 2: verify the password hash ──────────────────────────
        if ( ! $user_obj || ! wp_check_password( $password, $user_obj->user_pass, $user_obj->ID ) ) {
            wp_safe_redirect( add_query_arg( 'login_error', 'invalid', $error_url ) );
            exit;
        }

        // ── Step 3: role check ────────────────────────────────────────
        $is_chatter = in_array( 'chatter', (array) $user_obj->roles, true );
        $is_admin   = user_can( $user_obj, 'administrator' );

        if ( ! $is_chatter && ! $is_admin ) {
            wp_safe_redirect( add_query_arg( 'login_error', 'no_permission', $error_url ) );
            exit;
        }

        // ── Step 4: per-user can_chat toggle (chatters only) ──────────
        if ( $is_chatter && ! $is_admin ) {
            $can_chat = get_user_meta( $user_obj->ID, 'lsc_can_chat', true );
            if ( empty( $can_chat ) ) {
                wp_safe_redirect( add_query_arg( 'login_error', 'no_permission', $error_url ) );
                exit;
            }
        }

        // ── Step 5: create the session ────────────────────────────────
        wp_set_current_user( $user_obj->ID );
        wp_set_auth_cookie( $user_obj->ID, false, is_ssl() );

        // Fire the wp_login action so other plugins (audit logs, etc.) are notified.
        do_action( 'wp_login', $user_obj->user_login, $user_obj );

        // ── Step 6: redirect to the chatter dashboard ─────────────────
        $dashboard_page_id = (int) get_option( 'lsc_chatter_dashboard_page', 0 );
        $redirect          = $dashboard_page_id ? get_permalink( $dashboard_page_id ) : home_url( '/' );

        wp_safe_redirect( $redirect );
        exit;
    }

    /* ------------------------------------------------------------------
     * Logout handler
     * ------------------------------------------------------------------ */

    public function handle_logout() {
        if ( ! isset( $_GET['lsc_logout'] ) ) {
            return;
        }

        $nonce = isset( $_GET['lsc_logout_nonce'] )
            ? sanitize_text_field( wp_unslash( $_GET['lsc_logout_nonce'] ) )
            : '';

        if ( ! wp_verify_nonce( $nonce, 'lsc_logout' ) ) {
            return;
        }

        wp_logout();

        $login_page = (int) get_option( 'lsc_chatter_login_page', 0 );
        wp_safe_redirect( $login_page ? get_permalink( $login_page ) : wp_login_url() );
        exit;
    }

    /* ------------------------------------------------------------------
     * [live_support_chatter_dashboard] shortcode
     * ------------------------------------------------------------------ */

    public function render_dashboard( $atts ) {
        if ( ! is_user_logged_in() ) {
            $login_page = (int) get_option( 'lsc_chatter_login_page', 0 );
            $login_url  = $login_page ? get_permalink( $login_page ) : wp_login_url( get_permalink() );
            return '<p>' . sprintf(
                wp_kses(
                    __( 'Please <a href="%s">log in</a> to access the chat panel.', 'live-support-chat' ),
                    [ 'a' => [ 'href' => [] ] ]
                ),
                esc_url( $login_url )
            ) . '</p>';
        }

        $user = wp_get_current_user();
        if ( ! in_array( 'chatter', (array) $user->roles, true ) && ! current_user_can( 'administrator' ) ) {
            return '<p>' . esc_html__( 'You do not have permission to view this page.', 'live-support-chat' ) . '</p>';
        }

        ob_start();
        include LSC_PLUGIN_DIR . 'templates/chatter-dashboard.php';
        return ob_get_clean();
    }
}
