<?php

namespace App\DataTables;

use App\Models\User;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use App\Models\Admin;

class UsersDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {


        return datatables()
            ->eloquent($query)
            ->addColumn('settings', function ($row) {
                return '<a onclick="settings_popup(this)" data-url="'. url('user/member-data') .'" data-id="' . $row->user_id . '" >
                    <button class=" btn btn-success btn-sm" title="Settings Modal" type="button">
                        <i class="bx bxs-edit"></i>Settings
                    </button>
                </a>';
            })
            ->addColumn('action', function ($row) {
                $disabled =  ($row->CustomerID == "0" && auth()->user()->getUser()->is_admin == 'false') ? 'style="pointer-events: none;"' : '';
                $user = "User";
                $actions = '';

                if ($row->is_delete === 'false') {
                    $actions .= '
                        <a 
                            data-toggle="modal" 
                            data-target="#deletePopup" 
                            data-url="' . route('users.destroy', ['user_id' => $row->user_id, 'type' => 'block']) . '"  
                            data-id="' . $row->user_id . '" 
                            data-user="' . $user . '"
                            onclick="deletePopup(this)"  ' . $disabled . '>
                            <button  class="btn btn-danger btn-sm" data-toggle="tooltip" data-placement="right" title="Block">
                                <i class="fas fa-lock" aria-hidden="true"></i> Block
                            </button>
                        </a> ';
                } else {
                    $actions .= '
                        <a 
                            data-toggle="modal" 
                            data-target="#deletePopup" 
                            data-url="' . route('users.destroy', ['user_id' => $row->user_id, 'type' => 'unblock']) . '"  
                            data-id="' . $row->user_id . '" 
                            data-user="' . $user . '"
                            onclick="deletePopup(this)" ' . $disabled . '>
                            <button class="btn btn-secondary btn-sm" data-toggle="tooltip" data-placement="right" title="Unblock">
                                <i class="fas fa-unlock" aria-hidden="true"></i> Unblock
                            </button>
                        </a> ';
                }
                return $actions;
            })
            ->addColumn('email_update', function ($row) {
                $disabled = ($row->CustomerID == "0" && auth()->user()->getUser()->is_admin == 'false') ? 'style="pointer-events: none;"' : '';

                if (!empty($row->primary_email)  && !empty($row->sender_email)) {
                    $classBtn =  'btn btn-success';
                } else {
                    $classBtn =  'btn btn-secondary';
                }
                // $btn = '<a class="btn btn-primary btn-sm" onclick="emailupdate(this)" sender_name="' .$row->sender_name . '" sender_email="' . $row->sender_email . '" cc_email="' . $row->cc_email . '" bcc_email="' . $row->bcc_email . '" id="'. $row->user_id .'"><i class="fa fa-edit"></i></a><br>';
                return '<a ' . $disabled . ' target="_blank" href="' . route('users.edit_email') . '?CustomerID=' . $row->CustomerID . '" >
                            <button class="' . $classBtn . ' btn-sm" title="Configure Email" type="button" style="color: #f8f9fa;">
                                <i class="bx bxs-edit"></i>Edit Email
                            </button>
                        </a>';
            })
            ->editColumn('is_admin', function ($row) {
                $disabled = ($row->CustomerID == "0" && auth()->user()->getUser()->is_admin == 'false') ? 'style="pointer-events: none;"' : '';
                if ($row->is_admin == "true") {
                    $selected = "checked";
                } else {
                    $selected = "";
                }
                $btn  = '<input ' . $disabled . ' type="checkbox" class="btn bg-gradient-success btn-sm"  ' . $selected . ' data-CustomerID="' . $row->CustomerID . '" data-user_id="' . $row->user_id . '" onclick="updateIsAdmin(this)" value="' . $row->is_admin . '" >';
                return $btn;
            })
            ->addColumn('CustomerName', function ($row) {
                if ($row->is_admin == "true") {
                    // $adminLabel = "(ADMIN)";
                    $adminLabel = '<label style="background-color: lightgreen; font-weight: bold;">ADMIN</label>';
                } else {
                    $adminLabel = "";
                }
                $label  = $row->CustomerName.' '.$adminLabel;
                return '<a href="javascript:void(0);" onclick="settings_popup(this)" data-url="'. url('user/member-data') .'" data-id="' . $row->user_id . '" >'.$label .'</a> ';
                //return $label;
            })
            ->addColumn('EmailWithEdit', function ($row) {
                $label  = $row->Email;
                return $label .'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <button style="padding:1px 5px;" type="button" data-toggle="modal" class="updateUserEmail btn btn-primary btn-sm" data-customer-id="'.$row->CustomerID.'" data-user-email="' . $row->Email . '" data-target="#updateUserEmailModal"><i class="fas fa-pencil-alt"></i></button>';
                //return $label;
            })
            ->addColumn('PhoneWithEdit', function ($row) {
                $label  = $row->Phone;
                return $label .'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <button style="padding:1px 5px;" type="button" data-toggle="modal" class="updateUserPhone btn btn-primary btn-sm" data-customer-id="'.$row->CustomerID.'" data-user-phone="' . $row->Phone . '" data-target="#updateUserPhoneModal"><i class="fas fa-pencil-alt"></i></button>';
                //return $label;
            })
            ->addColumn('change_password',function($row){
                return '<a  target="_blank" onclick="change_password(this)" data-id="' . $row->user_id . '" >
                <button class=" btn btn-primary btn-sm" title="Configure Email" type="button" style="color: #f8f9fa;">
                    <i class="bx bxs-edit"></i>Change Password
                </button>
            </a>';
            })
            ->addColumn('permissions', function ($row) {
                $user = "User";
                $disabled = ($row->CustomerID == "0" && auth()->user()->getUser()->is_admin == 'false') ? 'style="pointer-events: none;"' : '';
                return '<a target="_blank" href="' . route('users.permissionsview') . '?CustomerID=' . $row->CustomerID . '" ' . $disabled . '>
                            <button class="btn btn-primary btn-sm" title="Permissions" type="button" style="color: #f8f9fa;">
                                <i class="bx bxs-edit" aria-hidden="true" ></i>Permission Settings 
                            </button>
                        </a>';
            })
            ->addColumn('access', function ($row) {
                $result = Admin::where('user_id', '=', $row->user_id)->first();
                $disabled = ($row->CustomerID == "0" && auth()->user()->getUser()->is_admin == 'false') ? 'style="pointer-events: none;"' : '';
                if ($result) {
                    return '<a 
                            data-toggle="modal" 
                            data-target="#addremoveAdmin" 
                            data-url="' . route('users.addremoveAdmin', ['user_id' => $row->user_id, 'type' => 'remove']) . '"  
                            data-id="' . $row->user_id . '" 
                            onclick="addremoveAdmin(this)" ' . $disabled . '>
                            <button class="btn btn-block btn-success btn-sm"  type="button" style="color: #f8f9fa;" onclick="addremoveAdmin(this)"> Disable  </button>
                            </a>';
                } else {
                    return '<a 
                            data-toggle="modal" 
                            data-target="#addremoveAdmin" 
                            data-url="' . route('users.addremoveAdmin', ['user_id' => $row->user_id, 'type' => 'add']) . '"  
                            data-id="' . $row->user_id . '" 
                            onclick="addremoveAdmin(this)" ' . $disabled . '>
                            <button class="btn btn-block btn-secondary btn-sm" type="button" style="color: #f8f9fa;" > Enable </button>
                            </a>';
                }
            })

            ->rawColumns(['CustomerName','settings','action', 'is_admin', 'status', 'email_update', 'permissions','PhoneWithEdit','EmailWithEdit', 'replace', 'location', 'access','change_password']);
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\Models\User $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(User $model)
    {
        $search = !empty(request('search')) ? request('search')['value'] :  "";

        // return $model->newQuery();
        return $model->fetchAllUsers2($search);
        // return $this->applyScopes($data);
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
            ->setTableId('users-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom('Bfrtip')
            ->orderBy(1)
            ->buttons(
                Button::make('create'),
                Button::make('export'),
                Button::make('print'),
                Button::make('reset'),
                Button::make('reload')
            )->parameters([
                'rowCallback' => 'function(row, data, index) {
                            if (data.is_delete === "true") {
                                $(row).css("background-color", "#c3c3c3"); // 
                            }
                            if (data.CustomerID == "0") {
                                $(row).css("background-color", "#dfdfdf"); // 
                            }
                        }',
            ]);
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {

        return [
            Column::make('CustomerID')->title('User ID')->searchable(false),
            Column::computed('CustomerName')->title('Name')->searchable(false),    
            Column::make('Email')->title('Email')->searchable(false),    
            // Column::make('Email')->title('Email'),
            Column::make('Phone')->title('Phone')->searchable(false),
            // Column::make('Phone')->title('Phone'),
            Column::computed('settings')
                ->exportable(false)
                ->printable(false)
                ->width('20%')
                ->addClass('text-center')->title('Settings')->searchable(false),
            // Column::make('is_admin')->title('Make Admin'),
            // Column::make('email_update')->title('Email configuration'),
            // Column::make('change_password')->title('Change Password'),
            // Column::computed('permissions')->title('Permission'),
            // Column::computed('access')->title('PC Access'),
            // Column::computed('action')
            //     ->exportable(false)
            //     ->printable(false)
            //     ->width('20%')
            //     ->addClass('text-center')->title('Action'),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'Users_' . date('YmdHis');
    }
}
