<?php

namespace App\Modules\Bookings;

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

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

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

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

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

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

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

        if ($request->input('show') && $request->input('results') != 'managers') {
            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 'managers':
                    $query->where('completed', '=', 0)->with('user', 'status');
                    break;
                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->take($request->input('limit', 20))->skip($request->input('skip', 0))->get();
        $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) {
                    $value->client->load('contract');
                }
            }

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

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

                $value->parts_total = $parts_total;
            }

            // 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);
    }

    /**
     * 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)
    {
        // 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;

        $support = Support::create($data);

        if (! $support->id) {
            $response = [
                'success' => false,
                'errors'  => $support->errors->all(),
            ];
        } else {
            if ($request->input('urgent') == 1) {
                // Notify the support department using global SMTP configuration
                \App\Seraph\Services\GlobalMailerService::send('emails.alerts.support', ['task' => $support], function ($message) use ($support) {
                    $message->to(Config::get('emails.support'))->subject('[Seraph3] New remote support for '.$support->client->name)->priority(1);
                }, null, null, false); // false = no CC/BCC from SMTP settings for notifications
            }

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

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

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

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

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

        $support->statuses = Status::support()->get();

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

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

        return Response::json($response);
    }

    /**
     * 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)
    {
        $support = Support::findOrFail($id);

        $support->fill($request->except('id', 'client_id', 'client_type'));

        if ($support->save()) {
            if ($request->has('templates')) {
                $support->templates()->sync(Arr::pluck($request->input('templates'), 'id'));
            }

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

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}
