<?php

namespace App\Http\Livewire;

use App\Services\Log;
use Auth;
use Livewire\Component;
use Schema;

class Logs extends Component {

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

    public $bulkItems, $filterSearch, $bulkAction, $purgeActionGroup, $purgeActionDate;

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

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

    public function purgeActionConfirmed(): void {
        if ( in_array( $this->purgeActionGroup, [ 'all', 'dashboardActivity', 'apiCalls', 'failedApiCalls', 'blocklistedApiCalls' ] ) &&
             in_array( $this->purgeActionDate, [ 'all', '30', '60', '180', '365' ] ) ) {

            $group = $this->purgeActionGroup;
            $date  = $this->purgeActionDate;

            \App\Models\Log::where( function ( $q ) use ( $group, $date ) {
                if ( $this->purgeActionGroup != 'all' ) {
                    $q->where( 'group', $group );
                }

                if ( $date != 'all' ) {
                    $q->where( 'created_at', '<=', now()->subDays( $date ) );
                }
            } )->delete();

            $this->purgeActionGroup = '';
        }

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

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

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

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

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

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

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