<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Models\Status;
use Illuminate\Support\Arr;

class OnsiteControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $query = Onsite::select('tasks.*')->onsite();

        if ($request->input('q')) {
            $query->where(function ($query) {
                $query->where('tasks.id', 'like', $request->input('q').'%');
            });
        }

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

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

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

        if ($request->input('show')) {
            switch ($request->input('show')) {
                case 'completed': $query->completed(); break;
                case 'open': $query->open(); break;
            }
        }

        if ($request->input('unpaid')) {
            $query->unpaid();
        }

        if ($request->input('notInvoiced')) {
            $query->notInvoiced();
        }

        if ($request->input('parts_total')) {
            $query->with('parts');
        }

        if ($request->input('results')) {
            switch ($request->input('results')) {
                case 'own':
                    $query = $query->where('assigned_to', '=', $request->input('user_id', Auth::user()->id))->open(); break;
                case 'unassigned':
                    $query = $query->whereNull('assigned_to')->open();
            }
        }

        // Sort results based on priority
        $query->join('severities', 'severities.id', '=', 'tasks.severity_id', 'left');

        if ($request->input('summary')) {
            $query->orderBy('tasks.id', 'desc');
        } else {
            $query->orderBy('severities.priority', 'desc')
                    ->orderBy('tasks.id', 'asc');
        }

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

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

                // Load the contract data only if this is a business customer
                if ($value->client_type == 'client') {
                    $value->client->load('contract');
                }
            }

            if ($request->input('parts_total')) {
                $value->parts_total = 0;

                foreach ($value->parts as $part) {
                    $value->parts_total += $part->amount_paid;
                }
            }

            // Load all the comment stats
            $value->comments_count = [
                'total'   => $value->comments()->count(),
                'unread'  => $value->comments()->unread()->count(),
            ];
        }

        $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, ($response['success']) ? 200 : 400);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        // Assign a default status
        $status = Status::repairs()->first();

        if (! $status) {
            return response()->json(['success' => false, 'errors' => ['No statuses defined']], 400);
        }

        $data = $request->except('id');
        $data['status_id'] = $status->id;

        $onsite = Onsite::create($data);

        if (! $onsite->id) {
            $response = [
                'success' => false,
                'errors'  => $onsite->errors->all(),
            ];
        } else {
            $service = \App::make('App\Modules\Bookings\CalendarEventService');

            try {
                if ($exchange_id = $service->create($onsite)) {
                    $onsite->exchange_id = $exchange_id;
                    $onsite->save();
                }
            } catch (Exception $e) {
                Log::error($e);
            }

            if ($request->has('templates')) {
                $onsite->templates()->sync(Arr::pluck($request->get('templates'), 'id'));
            }

            $response = [
                'success' => true,
                'data'    => $onsite->toArray(),
            ];
        }

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($id)
    {
        $onsite = Onsite::find($id);

        $onsite->load('user', 'client', 'parts', 'parts.stock', 'creator', 'template_items', 'templates.items');

        $onsite->statuses = Status::repairs()->get();

        // Check for deliveries for this client
        $onsite->deliveries = Repair::where('client_id', '=', $onsite->client_id)->where('client_type', '=', $onsite->client_type)->where('needs_delivery', '=', 1)->where('delivered', '=', 0)->get()->toArray();

        if ($onsite->client_type == 'client') {
            $onsite->load('client.sites', 'client.sites.users', 'site', 'site_user');
        }

        if (! $onsite) {
            return response()->json(['error' => 'Onsite not found.'], 404);
        }

        return response()->json($onsite->toArray());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update($id)
    {
        $onsite = Onsite::find($id);

        $onsite->fill($request->except('id'));

        if ($onsite->save()) {
            if ($request->input('exchange_sync') && $onsite->exchange_id) {
                try {
                    $item = \Ews::getItem($onsite->exchange_id);
                    if ($item) {
                        \Ews::updateEvent($item->ItemId->Id, $item->ItemId->ChangeKey, $onsite->onsite_start, $onsite->onsite_end);
                    }
                } catch (Exception $e) {
                }
            }

            if ($request->has('templates')) {
                $onsite->templates()->sync(Arr::pluck($request->get('templates'), 'id'));
            }

            $onsite->load('template_items', 'templates.items');

            if ($onsite->client_type == 'client') {
                $onsite->load('client.sites', 'client.sites.users', 'site', 'site_user');
            }

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $onsite = Onsite::find($id);

        // Access validations
        // should be implemented here...

        if (! $onsite) {
            return response()->json(['error' => 'Onsite not found.'], 404);
        }

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