<?php

namespace App\Livewire\FormBuilder;

use App\Models\Form;
use App\Models\FormBuilder;
use App\Models\User;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class ContentTable extends Component
{
    use WithPagination;

    #[Url(history:true)]
    public $search = '';

    #[Url(history:true)]
    public $admin = '';

    #[Url(history:true)]
    public $sortBy = 'created_at';

    #[Url(history:true)]
    public $sortDir = 'DESC';

    #[Url()]
    public $perPage = 10;

    public $formId = 2;

    public $redirectId = '';

    public function updatedSearch(){
        $this->resetPage();
    }

    public function delete(Form $form){
        $form->delete();
    }

    public function setSortBy($sortByField){

        if($this->sortBy === $sortByField){
            $this->sortDir = ($this->sortDir == "ASC") ? 'DESC' : "ASC";
            return;
        }

        $this->sortBy = $sortByField;
        $this->sortDir = 'DESC';
    }

    public function render()
    {
        $form = FormBuilder::find($this->formId); 
        $name_label = $form->name_label ?? '';
        $searchArray = array();

        // $searchField= 'form_content';
        if (!empty($name_label)) {
            foreach ($name_label as $key => $value) {
                $searchArray[] = ['form_content->'.$key.'', 'like', '%'.$this->search.'%'];
            }
        }
        $searchArray[] =['forms.created_at', 'like', '%'.$this->search.'%'];

        $tables = Form::where('form_id','=',$this->formId)
                    ->search($searchArray)
                    ->leftJoin('users', 'users.id', '=', 'forms.user_id')
                    ->select('forms.*', 'users.name')
                    ->orderBy($this->sortBy,$this->sortDir)
                    ->paginate($this->perPage);
                
                // ->when($this->admin !== '',function($query){
                //     $query->where('is_admin',$this->admin);
                // })
        return view('livewire.form-builder.content-table',
            [
                'tables' => $tables,
                'name_label' => $name_label,
                'form' => $form
            ]
        );
    }
}
