<?php

namespace HelpGent\App\Utils;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\Models\Attachment;
use HelpGent\App\Models\MessageForward;
use HelpGent\App\Repositories\AttachmentRepository;
use HelpGent\App\Repositories\FormRepository;
use HelpGent\WpMVC\Database\Query\Builder;
use stdClass;

class Repository {
    public static function user_select_query( Builder $query ):Builder {
        return $query->select( 'helpgent_users.id', 'helpgent_users.name', 'helpgent_users.email' );
    }

    public static function attachment_query():Builder {
        return static::attachment_select_query( Attachment::query() );
    }

    public static function attachment_select_query( Builder $query ):Builder {
        return $query->select( 'id, title, mime_type, file_size, file_id, storage' );
    }

    public static function delete_attachment( int $file_id ) {
        /**
         * @var AttachmentRepository $attachment_repository
         */
        $attachment_repository = helpgent_singleton( AttachmentRepository::class );
        $file                  = $attachment_repository->get_by_id( $file_id );
    
        if ( $file ) {
            $attachment_repository->delete_file( $file->title, $file->file_id, $file->storage );
            $attachment_repository->delete( $file->id );
        }
    }

    public static function bind_form_featured_image( stdClass $form ):stdClass {
        $content = json_decode( $form->content, true );
        if ( isset( $content['elements'][0]['attributes']['media']['type'] ) && 'image' === $content['elements'][0]['attributes']['media']['type'] ) {
            $form->featured_image = $content['elements'][0]['attributes']['media']['url'];
            return $form;
        }
        /**
         * @var FormRepository $form_repository
         */
        $form_repository = helpgent_singleton( FormRepository::class );
        $form->color     = $form_repository->get_meta( $form->id, 'color' )->meta_value ?? null;
        return $form;
    }

    public static function bind_form_media_settings( stdClass $form ):stdClass {
        $content = json_decode( $form->content, true );
        $global  = isset( $content['global'] ) && is_array( $content['global'] ) ? $content['global'] : [];
        $media   = isset( $global['media'] ) && is_array( $global['media'] ) ? $global['media'] : [];

        $max_upload_size      = ! empty( $global['bubble_media_max_upload_size'] ) ? $global['bubble_media_max_upload_size'] : ( $media['max_upload_size']['value'] ?? 300 );
        $max_upload_size_unit = ! empty( $global['bubble_media_max_upload_unit'] ) ? $global['bubble_media_max_upload_unit'] : ( $media['max_upload_size']['unit'] ?? 'mb' );
        $max_video_duration   = ! empty( $global['bubble_media_max_video_duration'] ) ? $global['bubble_media_max_video_duration'] : ( $media['max_video_duration']['value'] ?? 2 );
        $max_voice_duration   = ! empty( $global['bubble_media_max_voice_duration'] ) ? $global['bubble_media_max_voice_duration'] : ( $media['max_voice_duration']['value'] ?? 2 );
        $video_resolution     = ! empty( $global['bubble_media_video_resolution'] ) ? $global['bubble_media_video_resolution'] : ( $media['video_resolution']['value'] ?? 720 );

        $form->media_settings = [
            'max_upload_size'      => intval( $max_upload_size ),
            'max_upload_size_unit' => $max_upload_size_unit,
            'max_video_duration'   => floatval( $max_video_duration ),
            'max_voice_duration'   => floatval( $max_voice_duration ),
            'video_resolution'     => floatval( $video_resolution ),
        ];

        return $form;
    }

    public static function form_has_element( string $element_key, stdClass $form ): bool {
        $content = json_decode( $form->content, true );

        return in_array( $element_key, array_column( $content['elements'], 'element_type' ) );
    }

    public static function form_has_only_element( string $element_key, stdClass $form ): bool {
        $content = json_decode( $form->content, true );

        foreach ( array_column( $content['elements'], 'element_type' ) as $element_type ) {
            if ( ! in_array( $element_type, [ $element_key, 'welcome', 'end' ] ) ) {
                return false;
            }
        }

        return true;
    }

    public static function get_files_by_ids( array $ids ): array {
        if ( empty( $ids ) ) {
            return [];
        }

        /**
         * @var AttachmentRepository $attachment_repository
         */
        $attachment_repository = helpgent_singleton( AttachmentRepository::class );

        return $attachment_repository->get_files_by_ids( $ids );
    }

    public static function bind_file_url( stdClass $file ):stdClass {
        /**
         * @var AttachmentRepository $attachment_repository
         */
        $attachment_repository = helpgent_singleton( AttachmentRepository::class );
        $file->url             = $attachment_repository->get_file_url( $file->title, $file->file_id, $file->storage );
        return $file;
    }

    public static function clean_file( stdClass $file ):stdClass {
        unset( $file->storage );
        unset( $file->file_id );
        return $file;
    }

    public static function get_fields_labels( array $fields ) {
        $labels = [];
        foreach ( $fields as $key => $field ) {
            $field_key = $field['name'] ?? $field['type'] ?? $key;

            if ( ! is_string( $field_key ) || '' === $field_key ) {
                continue;
            }

            if ( 'number' === $field_key ) {
                $field_key = 'mobile_number';
            }

            $labels[ $field_key ] = $field['label'] ?? $field_key;
        }
        return $labels;
    }

    public static function delete_unused_forward_messages() {
        return MessageForward::query( 'forward' )->left_join( 'helpgent_messages', "forward.id", "=", "helpgent_messages.forward_id" )
        ->where_null( "helpgent_messages.forward_id" )->delete();
    }
}
