<?php

namespace HelpGent\Database\Migrations\V224;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\Models\User as UserModel;
use HelpGent\App\Models\HelpGentUser as HelpGentUserModel;
use HelpGent\App\Models\GuestMeta as GuestMetaModel;
use HelpGent\App\Models\Response as ResponseModel;
use HelpGent\App\Models\Message as MessageModel;
use HelpGent\Database\Migrations\Query;

class UserDependedTableMigration {
    // Migration Tables
    public static $migrated_data_table = 'helpgent_v2_2_4_migrated_data';

    public static function migrate_responses(): bool {
        $results = ResponseModel::query( 'response' )
            ->left_join( self::$migrated_data_table, self::$migrated_data_table . '.response_id', '=', 'response.id' )
            ->where_null( self::$migrated_data_table . '.response_id' )
            ->pagination( 1 );

        if ( empty( $results ) ) {
            return false;
        }

        foreach ( $results as $item ) {
            if ( ! isset( $item->is_guest ) ) {
                Query::insert_data( self::$migrated_data_table, [ 'response_id' => $item->id ] );
                continue;
            }

            ResponseModel::query()->where( 'id', $item->id )->update(
                [
                    'created_by' => self::get_or_create_helpgent_user_id( $item->created_by, $item->is_guest ),
                ] 
            );

            Query::insert_data( self::$migrated_data_table, [ 'response_id' => $item->id ] );
        }
        
        return true;
    }

    public static function migrate_messages(): bool {
        $results = MessageModel::query( 'message' )
            ->left_join( self::$migrated_data_table, self::$migrated_data_table . '.message_id', '=', 'message.id' )
            ->where_null( self::$migrated_data_table . '.message_id' )
            ->pagination( 1 );

        if ( empty( $results ) ) {
            return false;
        }

        foreach ( $results as $item ) {
            if ( ! isset( $item->is_guest ) ) {
                Query::insert_data( self::$migrated_data_table, [ 'response_id' => $item->id ] );
                continue;
            }
            
            MessageModel::query()->where( 'id', $item->id )->update(
                [
                    'created_by' => self::get_or_create_helpgent_user_id( $item->created_by, $item->is_guest ),
                ] 
            );

            Query::insert_data( self::$migrated_data_table, [ 'message_id' => $item->id ] );
        }
        
        return true;
    }

    public static function get_or_create_helpgent_user_id( ?int $user_id, bool $is_guest = false ): ?int {
        if ( null === $user_id || 0 === $user_id ) {
            return null;
        }

        if ( $is_guest ) {
            return self::get_helpgent_user_by_guest_user( $user_id );
        }

        return self::get_or_create_helpgent_user_id_by_wp_user( $user_id );
    }

    public static function get_helpgent_user_by_guest_user( $user_id ): int {
        $user_meta_ref = GuestMetaModel::query()->where( 'user_id', $user_id )->where( 'meta_key', 'new_user_id' )->first();
        return empty( $user_meta_ref ) ? 0 : $user_meta_ref->meta_value;
    }

    public static function get_or_create_helpgent_user_id_by_wp_user( int $wp_user_id ): int {
        $helpgent_user = HelpGentUserModel::query()->where( 'registered_id', $wp_user_id )->first();

        if ( $helpgent_user ) {
            return $helpgent_user->id;
        } 

        $wp_user = UserModel::query()->where( 'ID', $wp_user_id )->first();

        if ( empty( $wp_user ) ) {
            return 0;
        }
        
        $helpgent_user_id = HelpGentUserModel::query()->insert_get_id(
            [
                'registered_id' => $wp_user_id,
                'email'         => $wp_user->user_email,
                'name'          => $wp_user->display_name,
                'avatar_id'     => get_user_meta( $wp_user_id, 'helpgent_avatar', true ),
                'about'         => get_user_meta( $wp_user_id, 'helpgent_about', true ),
                'number'        => get_user_meta( $wp_user_id, 'helpgent_user_number', true ),
                'company'       => get_user_meta( $wp_user_id, 'helpgent_user_company', true ),
                'timezone'      => get_user_meta( $wp_user_id, 'helpgent_timezone', true ),
            ]
        );

        return empty( $helpgent_user_id ) ? 0 : $helpgent_user_id;
    }

    public static function clean_up(): void {
        // Drop Deprecated Table Columns
        Query::drop_table_columns(
            [
                'helpgent_responses' => [ 'is_guest' ],
                'helpgent_messages'  => [ 'is_guest' ],
            ] 
        );

        // Remove Migration Helper Tables
        Query::remove_tables( [ self::$migrated_data_table ] );
    }

    public static function create_migration_helper_tables(): void {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();

        if ( ! function_exists( 'dbDelta' ) ) {
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        }

        $migrated_data_table = self::$migrated_data_table;

        $sql = "CREATE TABLE {$wpdb->prefix}{$migrated_data_table} (
                `response_id` BIGINT UNSIGNED NOT NULL DEFAULT 0,
                `message_id` BIGINT UNSIGNED NOT NULL DEFAULT 0
            ) {$charset_collate};
        ";

        dbDelta( $sql );
    }
}
