<?php

namespace App\Modules\Bookings;

use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use App\Models\Keychain;

class KeychainRepositoryEloquent implements KeychainRepositoryInterface
{
    /**
     * A reference to the keychan model.
     *
     * @var \App\Models\Keychain
     */
    protected $model;

    /**
     * Constructor function where the dependency injection
     * magic happens.
     *
     * @param \App\Models\Keychain $model
     */
    public function __construct(Keychain $model)
    {
        $this->model = $model;
    }

    /**
     * Returns an empty paginator object,
     * with no items in the collection.
     *
     * @param  int $limit
     *
     * @return Illuminate\Pagination\Paginator
     */
    public function getEmptyPaginator($limit = 15)
    {
        return new Paginator([], 0, $limit);
    }

    /**
     * Get all the keychain related to a task.
     *
     * @return \Illuminate\Pagination\Paginator
     */
    public function getTaskKeychains($taskId)
    {

        // Build up the query and return the results
        // as a paginated class
        $query = $this->model->newQuery()
                    ->select('keychain.*')
                    ->join('task_keychains as links', function ($q) use ($taskId) {
                        $q->on('keychain.id', '=', 'links.keychain_id')->where('links.task_id', '=', $taskId);
                    });

        $collection = $query->get();

        return $collection;
    }

    /**
     * Get all the keychain related to a client.
     *
     * @return \Illuminate\Pagination\Paginator
     */
    public function getClientKeychains($clientType, $clientId)
    {

        // Build up the query and return the results
        // as a paginated class
        $query = $this->model->newQuery()
                    ->select('keychain.*')
                    ->where('client_id', $clientId)
                    ->where('client_type', $clientType)
                    ->where('disabled', 0);

        $collection = $query->get();

        return $collection;
    }
}
