<?php

namespace HelpGent\App\Providers;

defined( "ABSPATH" ) || exit;

use HelpGent\WpMVC\Contracts\Provider;
use HelpGent\App\Models\ChatMessage;

class AttachmentPermissionProvider implements Provider {
    public function boot(): void {
        add_filter( 'helpgent_remove_response_attachment_permission', [ $this, 'maybe_remove_response_attachment_permission' ], 20, 3 );
    }

    public function maybe_remove_response_attachment_permission( bool $remove, int $response_id, int $attachment_id ): bool {
        /**
         * Remove attachment read permission if attachment do not exist in this response chat message
         */
        $message = ChatMessage::query( "chat" )->select( 1 )->where( 'response_id', $response_id )
            ->where(
                function( $query ) use( $attachment_id ) {
                    $query->where( 'chat.attachment_id', $attachment_id );
                }
            )
            ->first();

        if ( empty( $message ) ) {
            return true;
        } 

        return $remove;
    }
}

