<?php

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

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\Site;


class SitesControllerREST extends BaseController
{
    /**
     * Return all the records as an encoded JSON.
     *
     * @return JSON
     */
    public function all(Request $request)
    {
        // Get an instance of a site so we can retrieve the table name
        $site = new Site();
        $data = DB::table($site->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)
    {
        // Check to see if all the records were requested
        if ($request->input('all') && $request->input('all') != 'false') {
            return $this->all($request);
        }

        $query = Site::query()->select('*');

        if ($request->input('name')) {
            $query = $query->where('name', 'like', $request->input('name').'%');
        }

        if ($request->input('users')) {
            $query = $query->with('users');
        }

        if ($request->input('sla')) {
            $query = $query->with('sla');
        }

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

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

        // Apply limits and execute the query
        //$query = $query->take(Input::get('limit', 20))->skip(Input::get('skip', 0))->get();

        $query = $query->paginate($request->input('limit', 20));

/*		$response = array(
            'success' => TRUE,
            'data'    => $query->toArray()
        );*/
    $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 = Site::create([
            'name'          => $request->input('name', ''),
            'client_id'     => $request->input('client_id'),
            'address'       => $request->input('address', ''),
            'address2'      => $request->input('address2', ''),
            'postcode'      => $request->input('postcode', ''),
            'primary_phone' => $request->input('primary_phone', ''),
        ]);

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($id)
    {
        $site = Site::findOrFail($id);

        $site->load('users');

        return response()->json($site->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, $id)
    {
        $site = Site::query()->find($id);
        if ($request->has('name')) {
            $site->name = $request->input('name');
        }
        if ($request->has('address')) {
            $site->address = $request->input('address');
        }
        if ($request->has('address2')) {
            $site->address2 = $request->input('address2');
        }
        if ($request->has('postcode')) {
            $site->postcode = $request->input('postcode');
        }
        if ($request->has('primary_phone')) {
            $site->primary_phone = $request->input('primary_phone');
        }

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // Validate that the amount can cover all the invoices
        try {
            $success = false;

            DB::transaction((function () use (&$success, $id) {

                // Find the site
                $site = Site::query()->find($id);

                // Delete the site users
                $site->users()->delete();

                // Finally delete the site
                $success = $site->delete();
            }));

            return response()->json([
                'success' => $success,
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'error'   => $e->getMessage(),
            ], 400);
        }
    }
}
