<?php

namespace HelpGent\App\Providers;

defined( "ABSPATH" ) || exit;

use HelpGent\App\DTO\UserDTO;
use HelpGent\WpMVC\Contracts\Provider;
use HelpGent\App\Repositories\FormRepository;
use stdClass;

class FormAccessLockProvider implements Provider {
    public function boot() {
        add_filter( 'helpgent_is_user_allowed_response_chat_message', [ $this, 'chat_permission_check' ], 10, 4 );
        add_filter( 'heartbeat_received', [ $this, 'check_form_access_lock' ], 10, 2 );
    }

    public function chat_permission_check( bool $is_user_allowed, stdClass $response, ?UserDTO $user, string $context ) {
        if ( apply_filters( 'helpgent_skip_chat_access_lock_permission_check', false ) ) {
            return $is_user_allowed;
        }
        
        if ( ! $user || 'index_items' === $context ) {
            return $is_user_allowed;
        }

        /**
         * @var FormRepository $form_repository
         */
        $form_repository = helpgent_singleton( FormRepository::class );

        $status = $form_repository->check_has_any_access_lock( $user->get_registered_id(), wp_get_session_token() );

        if ( $status['is_locked'] ) {
            return false;
        }

        return $is_user_allowed;
    }

    public function check_form_access_lock( array $response, array $data ) {
        if ( ! current_user_can( 'manage_options' ) || empty( $data['helpgent_check_form_access_lock_status'] ) ) {
            return $response;
        }

        /**
         * @var FormRepository $form_repository
         */
        $form_repository       = helpgent_singleton( FormRepository::class );
        $current_user_id       = get_current_user_id();
        $current_session_token = wp_get_session_token();
        $form_id               = $data['helpgent_check_form_access_lock_status'];
        $status                = $form_repository->check_has_any_access_lock( $current_user_id, $current_session_token );

        if ( isset( $status['locked_by_session_token'] ) ) {
            unset( $status['locked_by_session_token'] );
        }
        
        if ( isset( $status['locked_by_user_id'] ) ) {
            $locked_by_user = get_user_by( 'id', $status['locked_by_user_id'] );

            $status['locked_by_user_name'] = false !== $locked_by_user ? $locked_by_user->display_name : false;
        }

        if ( ! $status['is_locked'] ) {
            $form_repository->set_access_lock( $form_id, $current_user_id, $current_session_token );
        }

        $response['helpgent_form_access_lock_status'] = $status;

        return $response;
    }
}