<?php

namespace App\Modules\Bookings;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\BaseController;
use App\Modules\Bookings\Project;
use App\Models\User;

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

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

        if ($request->get('completed')) {
            $query->where('completed', 1);
        }

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

        if ($request->get('client_type')) {
            $query->where('client_type', $request->get('client_type'));
        }

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

        if ($request->get('overdue') && $request->get('overdue') != 'false') {
            $query->overdue();
        }

        if ($request->get('notInvoiced') && $request->get('notInvoiced') != 'false') {
            $query->whereNull('invoice_number');
        }

        if ($request->get('invoiced') && $request->get('invoiced') != 'false') {
            $query->whereNotNull('invoice_number');
        }

        if ($request->get('results')) {
            switch ($request->get('results')) {
                case 'completed':
                    $query->where('completed', '=', 1);    break;
                case 'own':
                    $query = $query->where('assigned_to', '=', $request->get('user_id', Auth::user()->id))->where('completed', 0); break;
                case 'unassigned':
                    $query = $query->where('completed', 0); break;
                case 'accounts':
                    $query = $query->where('paid', '=', 0); break;
            }
        }

        if ($request->get('summary')) {
            $query->orderBy('id', 'desc');
        }

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $project = Project::create($data);

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

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

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

        $project->load('tasks.user', 'tasks.status', 'tasks.parts', 'tasks.severity', 'site', 'site_user', 'tasks.comments', 'tasks.publicComments'); // tasks.comments & tasks.publicComments - nadeem 7.3.17
        $project->client;

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

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update(Request $request, $id)
    {
        $project = Project::find($id);

        $project->fill($request->all());

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

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

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

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

        // unlink all associated tasks
        if ($project::has('tasks')) {
          foreach ($project->tasks as $task) {
              $task->project_id = null;
              $task->save();
          }
        }
        
        if ($project->delete()) {
            return response()->json($project->toArray());
        } else {
            return response()->json([
                'errors' => $project->errors->all(),
            ], 400);
        }
    }
}
