<?php

namespace App\Pages\Himsapi;

use App\Models\Client;
use Livewire\Component;
use App\Models\Collection;
use App\Models\ClientToken;
use Livewire\Attributes\On;
use App\Traits\WithSweetAlert;
use App\Models\ClientCollection;
use App\Models\ClientCollectionParameter;

class ApiSetup extends Component
{
    use WithSweetAlert;
    public $id;
    public $client_id;
    public $Client;
    public $expire_at;
    public $token;
    public $access_limit;
    public $value;
    public $is_all_station;
    public $client_collection_id;
    public $total_selected_station = 0;
    public $is_ftp;
    public $ftp_host;
    public $ftp_user;
    public $ftp_pass;
    public $ftp_port;
    public $ftp_dir;
    public $collection_parameters = [];
    public $parameter_value = [];

    #[On('OnOff')]
    public function OnOff($data = [])
    {
        if(isset($data['id'])) {
            $ClientCollection = ClientCollection::where('client_id', $this->client_id)->where('collection_id', $data['id'])->firstOrNew();
            $ClientCollection->client_id = $this->client_id;
            $ClientCollection->collection_id = $data['id'];
            $ClientCollection->status = $data['status'];
            $ClientCollection->save();

            if($ClientCollection->status == 1) {
                $this->alert('success', 'Client api successfully on');
            } else {
                $this->alert('success', 'Client api successfully off');
            }
        }

        $this->dispatch('refreshDatatable');
    }


    public function validationAttributes()
    {
        $validation = [];
        foreach($this->collection_parameters as $key => $value) {
            $validation['parameter_value.' . $value->id] = $value->label ?? '';
        }

        return $validation;
    }

    #[On('configModal')]
    public function configModal($data = [])
    {
        $this->dispatch('typeahead_reset');
        $this->reset('collection_parameters', 'parameter_value', 'is_ftp', 'ftp_host', 'ftp_user', 'ftp_pass', 'ftp_port', 'ftp_dir');

        if(isset($data['id'])) {
            $ClientCollection = ClientCollection::query()
            ->with(['CollectionParameter' => function ($query) {
                $query->with(['ClientCollectionParameter' => function ($query) {
                    $query->where('client_id', $this->client_id);
                }]);
                return $query->active();
            }])
            ->where('collection_id', $data['id'])
            ->where('client_id', $this->client_id)
            ->first();

            $this->collection_parameters = collect($ClientCollection->CollectionParameter)->sortBy('sort');

            foreach($this->collection_parameters as $key => $value) {

                $this->parameter_value[$value->id] = $value->ClientCollectionParameter->value ?? $value->default_value;
            }
            $this->is_ftp = $ClientCollection->Collection->is_ftp;
            $this->ftp_host = $ClientCollection->ftp_host;
            $this->ftp_user = $ClientCollection->ftp_user;
            $this->ftp_pass = $ClientCollection->ftp_pass;
            $this->ftp_port = $ClientCollection->ftp_port;
            $this->ftp_dir = $ClientCollection->ftp_dir;
            $this->is_all_station = $ClientCollection->is_all_station ? true : null;
            $this->client_collection_id = $ClientCollection->id;
        }
        $this->dispatch('modalOpen', 'configModal');
    }
    #[On('accessStationModal')]
    public function accessStationModal($data = [])
    {

        $this->dispatch('modalOpen', 'accessStationModal');
    }

    public function clientParameterStore()
    {

        $validation = [];
        foreach($this->collection_parameters as $key => $value) {
            $validation['parameter_value.' . $value->id] = $value->is_required ? 'required' : '';
        }

        if($this->is_ftp) {
            $validation = array_merge($validation, [
                'ftp_host' => 'required',
                'ftp_user' => 'required',
                'ftp_pass' => 'required',
                'ftp_port' => 'required',
                'ftp_dir' => 'required',
            ]);
        }

        $this->validate($validation);

        foreach($this->collection_parameters as $key => $value) {
            $ClientCollectionParameter = ClientCollectionParameter::where('client_id', $this->client_id)->where('collection_parameter_id', $value->id)->firstOrNew();
            $ClientCollectionParameter->client_id = $this->client_id;
            $ClientCollectionParameter->collection_parameter_id = $value->id;
            $ClientCollectionParameter->collection_id = $value->collection_id;
            $ClientCollectionParameter->value = $this->parameter_value[$value->id];
            $ClientCollectionParameter->save();
        }

        $ClientCollection = ClientCollection::where('client_id', $this->client_id)->where('collection_id', $value->collection_id)->first();
        $ClientCollection->ftp_host = $this->is_ftp ? $this->ftp_host : null;
        $ClientCollection->ftp_user = $this->is_ftp ? $this->ftp_user : null;
        $ClientCollection->ftp_pass = $this->is_ftp ? $this->ftp_pass : null;
        $ClientCollection->ftp_port = $this->is_ftp ? $this->ftp_port : null;
        $ClientCollection->ftp_dir = $this->is_ftp ? $this->ftp_dir : null;
        $ClientCollection->is_all_station = $this->is_all_station ? true : null;
        $ClientCollection->save();

        $this->alert('success', 'Client api parameter successfully updated');

    }

    public function mount($id)
    {
        $this->client_id = $id;
        $this->Client = Client::find($id);
        $this->expire_at = $this->Client->ClientToken->expire_at;
        $this->token = $this->Client->ClientToken->token;

    }
    public function generateToken()
    {
        $ApiToken = ClientToken::where('client_id', $this->client_id)->firstOrNew(['client_id' => $this->client_id]);
        $ApiToken->client_id = $this->client_id;
        $ApiToken->token = bin2hex(random_bytes(16));
        $ApiToken->start_at = $ApiToken->start_at ?? now();
        $ApiToken->save();

        $this->token = $ApiToken->token;
        $this->alert('success', 'Client api token generated successfully');

    }
    public function updatedExpireAt($value)
    {
        $ApiToken = ClientToken::where('client_id', $this->id)->first();

        $ApiToken->expire_at = $value;
        $ApiToken->save();

        $this->alert('success', 'Client api token expire date updated successfully');
    }
    public function render()
    {
        return view('pages.himsapi.api-setup');
    }
}
