<?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 Carbon\Carbon;
use App\Models\Proposal;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ProposalsExport;
use Rappasoft\LaravelLivewireTables\Views\Filters\DateFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\DateRangeFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\SelectFilter;
use Illuminate\Database\Eloquent\Builder;

class ProposalsTable extends DataTableComponent
{
	//protected $model = FinanceBillDetails::class;
	
	public bool $columnSelect = true;
	
	public bool $rememberColumnSelection = false;
	
	public function configure(): void
    {

        $this->setPrimaryKey('ProposalID');
		//->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->setThAttributes(function (Column $column) {
            if ($column->getTitle() === 'Draft') {
                return [
                    'class' => 'actions-full-width',
                ];
            }

            return [];
        });
		  
		$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("Proposal#", "ProposalID")
                ->sortable()
				->searchable()
				->collapseOnMobile(),
			Column::make("Particulars", "Particulars")
                ->sortable()
				->searchable()
				->format(function( $Particulars ) {
                    //return strip_tags(substr($Amendment,0,30)).'...'; // strip tags to avoid breaking any html
					return strip_tags(substr_replace($Particulars, "...", 40));
                }),
				//->collapseOnMobile(),
			Column::make("Unit Of Measure", "UnitOfMeasure")
                ->sortable()
				->searchable()
				->collapseOnMobile(),
			Column::make("Amount", "Amount")
                ->sortable()
				->searchable(),
				//->collapseOnMobile(),
			Column::make("Remarks", "Remarks")
                ->sortable()
				->searchable()
				->deselected()
				->collapseOnMobile(),
            Column::make("Created On", "CreatedAt")
                ->sortable()
				->format(fn($row) => Carbon::parse($row)->format('d/m/Y h:i A'))
				->collapseOnMobile(),
			Column::make("Status")
				->label(
					function ($row, Column $column) {
						$propstatus=Proposal::where('ProposalID',$row->ProposalID)->pluck('Status')->first();
						$status='';
						if($propstatus==0){
							$status='<span class="badge rounded-pill bg-label-warning">Pending</span>';
						}
						if($propstatus==1){
							$status='<span class="badge rounded-pill bg-label-success">Passed</span>';
						}
						if($propstatus==2){
							$status='<span class="badge rounded-pill bg-label-danger">Annuled</span>';
						}
						return $status;
					}
					)->html()
				->collapseOnMobile(),
			Column::make('Actions')
			->label(
				function ($row, Column $column) {
					$ProposalDetails=Proposal::where('ProposalID',$row->ProposalID)->first();
					$ProposalStatus=$ProposalDetails->Status;
					$view='';
					if(auth()->user()->can('view-proposals')){
					$view = '<span class="" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="View Proposal" role="button" alt="View Proposal" title="" wire:click="$dispatch(\'viewProposal\',{ \'id\':'.$row->ProposalID.'})"><i class="bx bx-book bxs-sm me-sm-1 txt-kco-green"></i></span>';
					}
					$edit='';
					if(auth()->user()->can('update-proposals')){
					if($ProposalStatus==0){
					$edit = '<span class="" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Edit Proposal" alt="Edit Proposal" title="" role="button" wire:click="$dispatch(\'editProposal\',{ \'id\':'.$row->ProposalID.'})"><i class="bx bx-edit-alt bx-sm me-sm-1 txt-kco-green"></i></span>';
					}
					}
					$suggestamendment='';
					if(auth()->user()->can('create-proposalamendments')){
					if($ProposalStatus==0){
					$suggestamendment = '<span class="" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Suggest Amendment" role="button" alt="Suggest Amendment" title="" wire:click="$dispatch(\'openProposalAmendmentModal\',{ \'id\':'.$row->ProposalID.'})"><i class="bx bx-comment-add bx-sm me-sm-1 txt-kco-green"></i></span>';
					}
					}
					$viewamendments='';
					if(auth()->user()->can('view-proposalamendments')){
					$viewamendments = '<a class="" href="../../proposals/'.$row->ProposalID.'/suggestedamendments" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="View Suggested Amendments" role="button" alt="View Suggested Amendments" title=""><i class="bx bx-comment-detail bx-sm me-sm-1 txt-kco-green"></i></a>';
					}
					$delete='';
					if(auth()->user()->can('delete-proposals')){
					if($ProposalStatus==0){
					$delete = '<span class="" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Delete" alt="Delete" title="" role="button" wire:click="$dispatch(\'confirmDelete\',{ \'id\':'.$row->ProposalID.' ,\'targetEvent\':\'proposal-deleted\'})"><i class="bx bx-trash bx-sm me-sm-1 text-danger"></i></span>';
					}
					}
					return $view.'&nbsp;'.$edit.'&nbsp;'.$suggestamendment.'&nbsp;'.$viewamendments.'&nbsp;'.$delete;
				}
			)->html()
			//->deselected()
			->collapseOnMobile(),
				
        ];
    }
	
	public function builder(): Builder
    {

        $proposals=Proposal::query();
						
		return $proposals;
    }
	
	public function filters(): array
	{
		return [
			SelectFilter::make('Status')
				->options([
					'' => 'All',
					'0' => 'Pending',
					'1' => 'Approved',
					'2' => 'Rejected',
				])
				->filter(function(Builder $builder, string $value) {
				if ($value === '0') {
					$builder->where('proposals.Status', 0);
				} elseif ($value === '1') {
					$builder->where('proposals.Status', 1);
				} elseif ($value === '2') {
					$builder->where('proposals.Status', 2);
				}

				}),
			];
	}
	
	public function bulkActions(): array
	{
    return [
        'excel' => 'Export to Excel',
		'csv' => 'Export to CSV',
    ];
	}
 
	public function excel()
	{
    $proposals = $this->getSelected();
	$recordcount=count($proposals);
	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 ProposalsExport($proposals), 'proposals_export_'.$dt.'.xlsx');
	}
	
	public function csv()
	{
    $proposals = $this->getSelected();
	$recordcount=count($proposals);
	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 ProposalsExport($proposals), 'proposals_export_'.$dt.'.csv');
	}
		
}
