<?php
/**
 * Class LSC_Admin_Chats
 * Renders the chats management admin page.
 */
class LSC_Admin_Chats {

    public function __construct() {
        add_action( 'admin_post_lsc_admin_close_chat', [ $this, 'handle_close_chat'    ] );
        add_action( 'admin_post_lsc_delete_session',   [ $this, 'handle_delete_session' ] );
        add_action( 'admin_post_lsc_clear_sessions',   [ $this, 'handle_clear_sessions' ] );
    }

    /**
     * Render the chats page.
     */
    public static function page_chats() {
        $status_filter = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : 'open';
        $chats         = LSC_DB::get_chats( [ 'status' => $status_filter ] );
        require_once LSC_PLUGIN_DIR . 'admin/views/view-chats.php';
    }

    /**
     * Handle close chat action.
     */
    public function handle_close_chat() {
        check_admin_referer( 'lsc_close_chat' );

        if ( ! current_user_can( 'lsc_manage_chat' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'live-support-chat' ) );
        }

        $chat_id = isset( $_POST['chat_id'] ) ? (int) $_POST['chat_id'] : 0;
        if ( $chat_id ) {
            LSC_DB::update_chat_status( $chat_id, 'closed' );
        }

        wp_safe_redirect( add_query_arg( [ 'page' => 'lsc-chats' ], admin_url( 'admin.php' ) ) );
        exit;
    }

    /**
     * Handle delete single session.
     */
    public function handle_delete_session() {
        check_admin_referer( 'lsc_delete_session' );

        if ( ! current_user_can( 'lsc_manage_chat' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'live-support-chat' ) );
        }

        $session_id  = isset( $_POST['session_id'] )    ? (int) $_POST['session_id']    : 0;
        $filter_user = isset( $_POST['redirect_user'] ) ? (int) $_POST['redirect_user'] : 0;

        if ( $session_id ) {
            LSC_Sessions::delete_session( $session_id );
        }

        $redirect = add_query_arg(
            array_filter( [ 'page' => 'lsc-sessions', 'deleted' => 1, 'lsc_user' => $filter_user ?: null ] ),
            admin_url( 'admin.php' )
        );
        wp_safe_redirect( $redirect );
        exit;
    }

    /**
     * Handle clear entire session log.
     */
    public function handle_clear_sessions() {
        check_admin_referer( 'lsc_clear_sessions' );

        if ( ! current_user_can( 'lsc_manage_chat' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'live-support-chat' ) );
        }

        LSC_Sessions::clear_all();

        wp_safe_redirect( add_query_arg( [ 'page' => 'lsc-sessions', 'cleared' => 1 ], admin_url( 'admin.php' ) ) );
        exit;
    }
}
