<?php

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

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Modules\Clients\SiteUser;

class SiteUsersControllerREST extends BaseController
{
    /**
     * Return all the records as an encoded JSON.
     *
     * @return JSON
     */
    public function all(Request $request)
    {
        if ($request->input('modifiedSince')) {
            $query = SiteUser::query()->where('updated_at', '>=', $request->input('modifiedSince'));
            $query = $query->paginate($request->input('limit', 20));

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

        // Get an instance of a site so we can retrieve the table name
        $site_user = new SiteUser();
        $data = DB::table($site_user->getTable())->get();
        $total = count($data);

        $response = [
            'success'      => true,
            'data'         => $data,
            'total'        => $total,
            'current_page' => 1,
            'last_page'    => 1,
            'from'         => 1,
            'to'           => $total,
        ];

        return $response;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request, $site_id)
    {
        $query = SiteUser::query()->where('site_id', $site_id);

        if ($request->input('name')) {
            $query = $query->where(DB::raw("CONCAT_WS(' ', first_name, last_name)"), 'like', '%'.$request->input('name').'%');
        }

        if ($request->input('modifiedSince')) {
            $query->where('updated_at', '>=', $request->input('modifiedSince'));
        }

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

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

        return Response::json($response);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request, $site_id)
    {
        $user = SiteUser::create([
            'site_id'    => $site_id,
            'first_name' => $request->input('first_name', ''),
            'last_name'  => $request->input('last_name', ''),
            'email'      => $request->input('email', ''),
            'phone'      => $request->input('phone', ''),
            'mobile'     => $request->input('mobile', ''),
            'position'   => $request->input('position', ''),
            'authority'  => $request->input('authority', 0),
        ]);

        if (! $user->id) {
            return Response::json(['errors' => $user->errors->all()], 400);
        } else {
            return Response::json($user->toArray());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($site_id, $id)
    {
        $user = SiteUser::findOrFail($id);
        $user->load('site');

        return Response::json($user->toArray());
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update(Request $request, $site_id, $id)
    {
        $user = SiteUser::query()->find($id);

        if ($request->has('first_name')) {
            $user->first_name = $request->input('first_name');
        }
        if ($request->has('last_name')) {
            $user->last_name = $request->input('last_name');
        }
        if ($request->has('email')) {
            $user->email = $request->input('email');
        }
        if ($request->has('phone')) {
            $user->phone = $request->input('phone');
        }
        if ($request->has('mobile')) {
            $user->mobile = $request->input('mobile');
        }
        if ($request->has('position')) {
            $user->position = $request->input('position');
        }
        if ($request->has('authority')) {
            $user->authority = $request->input('authority');
        }

        if ($user->save()) {
            Event::dispatch('SiteUserUpdated', $user);
            return Response::json($user->toArray());
        } else {
            return Response::json(['errors' => $user->errors->all()], 400);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $success = SiteUser::query()->find($id)->delete();

        return Response::json(['success' => $success]);
    }
}
