<?php

namespace App\Modules\Clients\controllers\api\v1;

use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class LicensesControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $query = License::select('*');

        if ($request->input('client_id') && $request->input('client_type')) {
            $query->where('client_id', $request->input('client_id'))->where('client_type', $request->input('client_type'));
        }

        // Apply limits and execute the query
        $query = $query->paginate($request->input('limit', 20));

        // Load all the clients
        // unfortuately eager loading is not available
        // for polymorphic relationships at the moment..
        if ($request->input('client') && $request->input('client') != 'false') {
            foreach ($query as $value) {
                $value->client;
            }
        }

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'per_page'     => $query->perPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

        return Response::json($response, ($response['success']) ? 200 : 400);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $license = License::create($request->all());

        if (! $license->exists) {
            return Response::json(['errors' => $license->errors->all()], 400);
        }

        return $license;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $license = License::findOrFail($id);
        $license->fill($request->all());

        if (! $license->save()) {
            return Response::json(['errors' => $license->errors->all()], 400);
        }

        return $license;
    }
}
