<?php

namespace Ignite\Core\Models\Grid;

use Ignite\Core\Entities\Filters\QueryPermissionFilters;
use Ignite\Core\Entities\User;
use Ignite\Core\Http\Forms\ProfileForm;
use Ignite\Core\Traits\ReportFormConfiguration;
use Illuminate\Database\DatabaseManager;
use Yajra\DataTables\DataTables;

class ParticipantTable extends QueryTable
{
    use ReportFormConfiguration {
        getColumns as getFormColumns;
    }

    /**
     * The columns that should always be displayed when using the ReportFormConfiguration trait.
     * @var array
     */
    protected $alwaysDisplay = ['action', 'checkbox', 'user_id'];

    /**
     * The form to configure report columns when using ReportFormConfiguration trait.
     * @var string
     */
    protected $form = ProfileForm::class;

    /**
     * @var ParticipantFormatter
     */
    protected $formatter;

    /**
     * ParticipantTable constructor.
     *
     * @param DataTables $datatables
     * @param DatabaseManager $databaseManager
     * @param ParticipantFormatter $formatter
     * @param array $params
     */
    public function __construct(
        DataTables           $datatables,
        DatabaseManager      $databaseManager,
        ParticipantFormatter $formatter,
        array                $params = []
    ) {
        parent::__construct($datatables, $databaseManager, $params);

        $this->formatter = $formatter;
    }

    /**
     * @return array
     */
    protected function getColumns()
    {
        $columns = $this->getFormColumns();
        unset($columns['ssn']);
        unset($columns[config('services.recaptcha.field_name')]);

        return $columns;
    }

    /**
     * The columns to show.
     *
     * @return array
     */
    public function columns()
    {
        return [
            'action' => $this->actionsColumn(),
            'user_id' => [
                'title' => 'User ID',
                'name' => 'participant.user_id',
                'orderable' => true,
                'exportable' => true,
            ],
            'last_login_at' => [
                'title' => 'Last Login',
                'name' => 'user.last_login_at',
                'orderable' => true,
                'exportable' => true,
            ],
            'created_at' => [
                'title' => 'Enrollment Date',
                'name' => 'participant.created_at',
                'orderable' => true,
                'exportable' => true,
            ],
        ];
    }

    /**
     * The participants query.
     *
     * @return \Illuminate\Database\Query\Builder
     */
    public function query()
    {
        $columns = collect($this->getColumns())
            ->keyBy('name')
            ->except('actions')
            ->keys()
            ->toArray();

        $query = $this->getConnection()
            ->table('core_participant as participant')
            ->select($columns)
            ->leftJoin('core_user as user', 'user.user_id', '=', 'participant.user_id')
            ->where('user.internal', User::TYPE_PARTICIPANT)
            ->where('user.status', $this->status)
            ->whereNull('deleted_at');

        return QueryPermissionFilters::for('core.user.participant.browse')
            ->apply($query, 'participant');
    }

    /**
     * Get a map of column keys => functions to format columns.
     *
     * @return array
     */
    protected function getColumnFormattingMap()
    {
        return [
            'action' => [$this->formatter, 'actions'],
            'last_login_at' => [$this->formatter, 'lastLoginAt'],
            'created_at' => [$this->formatter, 'enrolledAt'],
            'agree_confirm_1' => [$this->formatter, 'agreeConfirm1'],
            'agree_confirm_2' => [$this->formatter, 'agreeConfirm2'],
            'archived' => [$this->formatter, 'archived'],
            'internal' => [$this->formatter, 'internal'],
            'status' => [$this->formatter, 'status'],
        ];
    }

    /**
     * Get default builder parameters.
     *
     * @return array
     */
    protected function getBuilderParameters()
    {
        $params = func_get_args();

        return parent::getBuilderParameters(array_merge([
            'order' => [[2, 'desc']],
        ], ...$params));
    }
}
