<?php

namespace App\Modules\Bookings;

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

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

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

        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('completed')) {
            $query->completed();
        }

        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('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->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->load('contract');
                }
            }

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

    /**
     * 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::saleLeads()->first();

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

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

        $sale_lead = SaleLead::create($data);

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

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

        $sale_lead->load('user', 'client', 'creator', 'subscribers');

        $sale_lead->statuses = Status::saleLeads()->get();

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

        return $sale_lead;
    }

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

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

        if ($sale_lead->save()) {
            $sale_lead->load('user');

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

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