<?php

namespace App\Livewire;

use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Rappasoft\LaravelLivewireTables\Views\Columns\ButtonGroupColumn;
use Rappasoft\LaravelLivewireTables\Views\Columns\LinkColumn;
use App\Models\Category;
use App\Models\Department;
use Carbon\Carbon;
use App\Models\Category as CategoryModel;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\CategoriesExport;

class CategoriesTable extends DataTableComponent
{
	protected $model = Category::class;
	
	protected $listeners=[];
	
	public bool $columnSelect = true;
	
	public bool $rememberColumnSelection = false;
	
	public function configure(): void
    {
	
        $this->setPrimaryKey('CategoryID');
		//->setPaginationMethod('simple');
		
		$this->setBulkActionsEnabled();
		
		/*$this->setTableAttributes([
			'default' => false,
			'class' => 'table table-striped',
		  ]);*/

		$this->setEmptyMessage('No data available in table');
		
		$this->setSortingPillsStatus(true);
		
		$this->setSortingPillsItemAttributes([
			'class' => 'badge rounded-pill btn-kco-green d-inline-flex align-items-center', // Add these classes to the sorting pills item
			'default-colors' => false, // Do not output the default colors
			'default-styling' => false // Output the default styling
			]);
		
		  $this->setBulkActionsButtonAttributes([
			'class' => 'btn btn-kco-green dropdown-toggle',
			'default-colors' => false,
			'default-styling' => false,
			]);
			
		$this->setLoadingPlaceholderStatus(false);
		
		$this->setLoadingPlaceholderContent('Loading..');
		
		$this->setLoadingPlaceHolderRowAttributes([
        'class' => 'bg-light',
        'default' => true,
		]);
		
		$this->setLoadingPlaceHolderIconAttributes([
        'class' => 'lds-hourglass',
        'default' => false,
		]);
		
		$this->setTableWrapperAttributes([
			'default' => true,
			'class' => 'full-width-no-padding',
		  ]);
		  
		/*$this->setSearchFieldAttributes([
			'class' => 'block w-full form-control',
		]);*/
		
		$this->setperPageAccepted([10,20,50,100,500,1000,-1]);
		
		$this->setDefaultSort('CreatedAt','desc');
    }
	
	public function columns(): array
    {
        return [
            Column::make("Id", "CategoryID")
			//->excludeFromColumnSelect() //hide from column select
			//->deselectedIf(!Auth::user())
			//->selectedIf(Auth::user())
				->hideIf(true) //hidden
                ->sortable(),
            Column::make("Category", "CategoryName")
                ->sortable()
				->searchable(),
			Column::make("Department", "department.DepartmentName")
                ->sortable()
				->searchable(),
			Column::make("Description", "Description")
                ->sortable()
				->searchable()
				->collapseOnMobile(),
            Column::make("Created On", "CreatedAt")
                ->sortable()
				->format(fn($row) => Carbon::parse($row)->format('d/m/Y h:i A')),
            Column::make("Updated On", "UpdatedAt")
                ->sortable()
				->format(fn($row) => Carbon::parse($row)->format('d/m/Y h:i A'))
				->deselected()
				->collapseOnMobile(), //deselected by default
			Column::make('Actions')
			->label(
				function ($row, Column $column) {
					$edit='';
					if(auth()->user()->can('update-revenuecategories')){
					$edit = '<span class="" data-bs-toggle="tooltip" data-bs-placement="top" alt="Edit" data-bs-original-title="Edit" role="button" wire:click="$dispatch(\'editCategory\',{ \'id\':'.$row->CategoryID.'})"><i class="bx bx-edit-alt bx-sm me-sm-1 txt-kco-green"></i></span>';
					}
					$delete='';
					if(auth()->user()->can('delete-revenuecategories')){
					$delete = '<span class="" data-bs-toggle="tooltip" data-bs-placement="top" alt="Delete" data-bs-original-title="Delete" role="button" wire:click="$dispatch(\'confirmDelete\',{ \'id\':'.$row->CategoryID.' ,\'targetEvent\':\'category-deleted\'})"><i class="bx bx-trash bx-sm me-sm-1 text-danger"></i></span>';
					}
					return $edit.'&nbsp;'.$delete;
				}
			)->html(),
				
        ];
    }
	
	public function bulkActions(): array
	{
    return [
        'excel' => 'Export to Excel',
		'csv' => 'Export to CSV',
    ];
	}
 
	public function excel()
	{
    $categories = $this->getSelected();
	$recordcount=count($categories);
	if($recordcount==0){
		$this->dispatch('alert', [
				'type' => 'error',
				'message' => "Select at least one record to export!",
			]);
			return;
	}
    $this->clearSelected();
	$dt=date('d_m_Y_H_i_a');
    return Excel::download(new CategoriesExport($categories), 'categories_export_'.$dt.'.xlsx');
	}
	
	public function csv()
	{
    $categories = $this->getSelected();
	$recordcount=count($categories);
	if($recordcount==0){
		$this->dispatch('alert', [
				'type' => 'error',
				'message' => "Select at least one record to export!",
			]);
			return;
	}
    $this->clearSelected();
	$dt=date('d_m_Y_H_i_a');
    return Excel::download(new CategoriesExport($categories), 'categories_export_'.$dt.'.csv');
	}
	
}
