<?php

namespace App\Http\Livewire;

use App\Models\ApiKey;
use App\Models\Generator;
use App\Services\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use LaravelIdea\Helper\App\Models\_IH_ApiKey_C;
use Livewire\Component;
use Schema;

class ApiKeys extends Component {

	public $filterSearch, $bulkActionStatus, $deleteId, $canGetAvailableLicenseKeysCount, $canAssignAndActivateLicenseKey, $updateId, $apiKey, $ipAddress, $description, $status, $canVerify, $canActivate, $canDeactivate, $canGetLicenseKeyDetails, $canAccessDownloadables, $canAssignLicenseKey, $canSendTelemetryData, $canGetTelemetryData, $canCreateLicenseKeys, $canCreateLicenseKeyMeta, $canCreateProducts, $canCreateProductMeta, $canUpdateLicenseKeys, $canUpdateLicenseKeyMeta, $canUpdateProducts, $canUpdateProductMeta, $canDeleteLicenseKeys, $canDeleteLicenseKeyMeta, $canDeleteProducts, $canDeleteProductMeta, $canGetAllProducts, $canGetLicenseKeys, $canGetAllGenerators, $canGenerate, $bulkAction, $bulkItems, $bulkActionConfirm;

	protected $listeners = [ 'bulkAction', 'bulkActionConfirmed', 'filterItems' ];

	protected function getCreateRules(): array {
		return [
			'apiKey'    => 'required',
			'ipAddress' => 'sometimes|ip',
		];
	}

	protected function getUpdateRules(): array {
		return [
			'apiKey'    => 'required',
			'ipAddress' => 'sometimes|ip',
		];
	}

	public function createItemUpdated( $propertyName ): void {
		$this->validateOnly( $propertyName, $this->getCreateRules() );
	}

	public function updateItemUpdated( $propertyName ): void {
		$this->validateOnly( $propertyName, $this->getUpdateRules() );
	}

	public function createItem(): void {
		$this->validate( $this->getCreateRules() );

		$apiKey = new ApiKey();
		$this->assignItemFields( $apiKey );
		Log::add( '110', Auth::id(), request()->ip() );

		$this->dispatchBrowserEvent( 'close-create-modal' );
	}

	public function updateItem(): void {
		$this->validate( $this->getUpdateRules() );

		$apiKey = ApiKey::find( $this->updateId );

		if ( $apiKey ) {
			$this->assignItemFields( $apiKey );

			Log::add( '108', Auth::id(), request()->ip() );
		}

		$this->dispatchBrowserEvent( 'close-update-modal' );
	}

	public function deleteItem(): void {
		ApiKey::where( 'id', $this->deleteId )->delete();

		Log::add( '109', Auth::id(), request()->ip() );

		$this->dispatchBrowserEvent( 'close-delete-modal' );
	}

	public function openCreateModal(): void {
		$this->resetInputs();

		$this->dispatchBrowserEvent( 'open-create-modal' );
	}

	public function openUpdateModal( $id ): void {
		$apiKey                                = ApiKey::find( $id );
		$this->updateId                        = $apiKey->id;
		$this->apiKey                          = $apiKey->api_key;
		$this->ipAddress                       = $apiKey->ip_address;
		$this->description                     = $apiKey->description;
		$this->status                          = (bool) $apiKey->is_active;
		$this->canVerify                       = (bool) $apiKey->can_verify;
		$this->canActivate                     = (bool) $apiKey->can_activate;
		$this->canDeactivate                   = (bool) $apiKey->can_deactivate;
		$this->canGetLicenseKeyDetails         = (bool) $apiKey->can_get_license_key_details;
		$this->canAccessDownloadables          = (bool) $apiKey->can_access_downloadables;
		$this->canAssignLicenseKey             = (bool) $apiKey->can_assign_license_key;
		$this->canSendTelemetryData            = (bool) $apiKey->can_send_telemetry_data;
		$this->canGetTelemetryData             = (bool) $apiKey->can_get_telemetry_data;
		$this->canCreateLicenseKeys            = (bool) $apiKey->can_create_license_key;
		$this->canCreateLicenseKeyMeta         = (bool) $apiKey->can_create_license_key_meta;
		$this->canCreateProducts               = (bool) $apiKey->can_create_product;
		$this->canCreateProductMeta            = (bool) $apiKey->can_create_product_meta;
		$this->canUpdateLicenseKeys            = (bool) $apiKey->can_update_license_key;
		$this->canUpdateLicenseKeyMeta         = (bool) $apiKey->can_update_license_key_meta;
		$this->canUpdateProducts               = (bool) $apiKey->can_update_product;
		$this->canUpdateProductMeta            = (bool) $apiKey->can_update_product_meta;
		$this->canDeleteLicenseKeys            = (bool) $apiKey->can_delete_license_key;
		$this->canDeleteLicenseKeyMeta         = (bool) $apiKey->can_delete_license_key_meta;
		$this->canDeleteProducts               = (bool) $apiKey->can_delete_product;
		$this->canDeleteProductMeta            = (bool) $apiKey->can_delete_product_meta;
		$this->canGetAllProducts               = (bool) $apiKey->can_get_all_products;
		$this->canGetLicenseKeys               = (bool) $apiKey->can_get_license_keys;
		$this->canGetAllGenerators             = (bool) $apiKey->can_get_all_generators;
		$this->canGenerate                     = (bool) $apiKey->can_generate;
		$this->canAssignAndActivateLicenseKey  = (bool) $apiKey->can_assign_and_activate_license_key;
		$this->canGetAvailableLicenseKeysCount = (bool) $apiKey->can_get_available_license_keys_count;

		$this->dispatchBrowserEvent( 'open-update-modal' );
	}

	public function resetInputs(): void {
		$this->apiKey                          = Str::uuid()->toString();
		$this->updateId                        = 0;
		$this->ipAddress                       = '';
		$this->description                     = '';
		$this->status                          = false;
		$this->canVerify                       = false;
		$this->canActivate                     = false;
		$this->canDeactivate                   = false;
		$this->canGetLicenseKeyDetails         = false;
		$this->canAccessDownloadables          = false;
		$this->canAssignLicenseKey             = false;
		$this->canSendTelemetryData            = false;
		$this->canGetTelemetryData             = false;
		$this->canCreateLicenseKeys            = false;
		$this->canCreateLicenseKeyMeta         = false;
		$this->canCreateProducts               = false;
		$this->canCreateProductMeta            = false;
		$this->canUpdateLicenseKeys            = false;
		$this->canUpdateLicenseKeyMeta         = false;
		$this->canUpdateProducts               = false;
		$this->canUpdateProductMeta            = false;
		$this->canDeleteLicenseKeys            = false;
		$this->canDeleteLicenseKeyMeta         = false;
		$this->canDeleteProducts               = false;
		$this->canDeleteProductMeta            = false;
		$this->canGetAllProducts               = false;
		$this->canGetLicenseKeys               = false;
		$this->canGetAllGenerators             = false;
		$this->canGenerate                     = false;
		$this->canAssignAndActivateLicenseKey  = false;
		$this->canGetAvailableLicenseKeysCount = false;

		$this->resetValidation();
	}

	public function bulkAction(): void {
		$this->dispatchBrowserEvent( 'open-confirm-bulk-action' );
	}

	public function bulkActionConfirmed(): void {
		if ( $this->bulkAction == 'delete' ) {
			ApiKey::whereIn( 'id', $this->bulkItems )->delete();

			Log::add( '107', Auth::id(), request()->ip(), [ 'activation-ids' => $this->bulkItems ] );

			$this->bulkAction = '';
			$this->bulkItems  = [];
		}

		if ( $this->bulkAction == 'change-status' && in_array( $this->bulkActionStatus, [ 'active', 'inactive' ] ) ) {
			ApiKey::whereIn( 'id', $this->bulkItems )->update( [ 'is_active' => $this->bulkActionStatus == 'active' ] );

			Log::add( '161', Auth::id(), request()->ip(), [ 'activation-ids' => $this->bulkItems ] );

			$this->bulkAction       = '';
			$this->bulkActionStatus = '';
			$this->bulkItems        = [];
		}

		$this->dispatchBrowserEvent( 'close-confirm-bulk-action' );
		$this->dispatchBrowserEvent( 'reset-bulk-input' );
	}

	public function filterItems(): void {
		$this->dispatchBrowserEvent( 'filter-done' );
	}

	public function render() {
		return view( 'livewire.api-keys.manage', [
			'items' => ApiKey::where( function ( $q ) {
				if ( $this->filterSearch != '' ) {
					foreach ( Schema::getColumnListing( 'api_keys' ) as $column ) {
						$q->orWhere( $column, 'like', '%' . $this->filterSearch . '%' );
					}
				}
			} )->orderBy( 'id', 'DESC' )->paginate( getOption( 'ui', 'itemsPerTable', 10 ) )
		] );
	}

	/**
	 * @param ApiKey $apiKey
	 *
	 * @return void
	 */
	public function assignItemFields( ApiKey $apiKey ): void {
		$apiKey->api_key                              = $this->apiKey;
		$apiKey->ip_address                           = $this->ipAddress;
		$apiKey->description                          = $this->description;
		$apiKey->is_active                            = $this->status;
		$apiKey->can_verify                           = $this->canVerify;
		$apiKey->can_activate                         = $this->canActivate;
		$apiKey->can_deactivate                       = $this->canDeactivate;
		$apiKey->can_get_license_key_details          = $this->canGetLicenseKeyDetails;
		$apiKey->can_access_downloadables             = $this->canAccessDownloadables;
		$apiKey->can_assign_license_key               = $this->canAssignLicenseKey;
		$apiKey->can_send_telemetry_data              = $this->canSendTelemetryData;
		$apiKey->can_get_telemetry_data               = $this->canGetTelemetryData;
		$apiKey->can_create_license_key               = $this->canCreateLicenseKeys;
		$apiKey->can_create_license_key_meta          = $this->canCreateLicenseKeyMeta;
		$apiKey->can_create_product                   = $this->canCreateProducts;
		$apiKey->can_create_product_meta              = $this->canCreateProductMeta;
		$apiKey->can_update_license_key               = $this->canUpdateLicenseKeys;
		$apiKey->can_update_license_key_meta          = $this->canUpdateLicenseKeyMeta;
		$apiKey->can_update_product                   = $this->canUpdateProducts;
		$apiKey->can_update_product_meta              = $this->canUpdateProductMeta;
		$apiKey->can_delete_license_key               = $this->canDeleteLicenseKeys;
		$apiKey->can_delete_license_key_meta          = $this->canDeleteLicenseKeyMeta;
		$apiKey->can_delete_product                   = $this->canDeleteProducts;
		$apiKey->can_delete_product_meta              = $this->canDeleteProductMeta;
		$apiKey->can_get_all_products                 = $this->canGetAllProducts;
		$apiKey->can_get_license_keys                 = $this->canGetLicenseKeys;
		$apiKey->can_get_all_generators               = $this->canGetAllGenerators;
		$apiKey->can_generate                         = $this->canGenerate;
		$apiKey->can_assign_and_activate_license_key  = $this->canAssignAndActivateLicenseKey;
		$apiKey->can_get_available_license_keys_count = $this->canGetAvailableLicenseKeysCount;

		$apiKey->save();
	}
}
