<?php

namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Validator;
use App\Complaint;
use App\Http\Requests\ComplaintRequest;

class ComplaintController extends Controller
{

	public function index()
    {

		$complaints = Complaint::where('company_id', $this->_getCompany()->id)
										->with(['customer', 'employee'])
											->orderBy('created_at', 'desc')
												->get();

		return response()->json($complaints, 200);
	
    }

    public function store(ComplaintRequest $request)
    {

		$complaint = $this->_save($request);
		
		if ($complaint) {
			return response()->json([
				'title' => 'Complaint',
				'message' => 'Complaint was added successfully.',
				'object' => $complaint
			], 201);
		} else {
			return response()->json([
				'title' => 'Complaint',
				'message' => 'It was not possible to add the Complaint.'
			], 500);
		}
	
    }

    public function show($id)
    {

		$complaint = Complaint::with(['employee', 'customer'])->find($id);

		if (!$complaint || $complaint->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Complaint',
				'message' => 'Record not found'
			], 404);
		}

		return response()->json($complaint, 200);
	
    }

    public function update(ComplaintRequest $request, $id)
    {
		
		$complaint = $this->_save($request, $id);

		if ($complaint) {
			return response()->json([
				'title' => 'Complaint',
				'message' => 'Complaint was edited successfully.',
				'object' => $complaint
			], 200);
		} else {
			return response()->json([
				'title' => 'Complaint',
				'message' => 'It was not possible to edit the Complaint.'
			], 500);
		}
		
    }

    public function destroy($id)
    {

		$complaint = Complaint::find($id);

		if (!$complaint || $complaint->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Complaint',
				'message' => 'Record not found',
			], 404);
		}

		$complaint->delete();
		
		return response()->json([
				'title' => 'Complaint',
				'message' => 'Complaint was deleted successfully.'
			], 200);
	
    }
	
	private function _save(Request $request, $id = null) 
    {

		if ($id) {

			$complaint = Complaint::find($id);

			if (!$complaint || $complaint->company_id != $this->_getCompany()->id) {
				return response()->json([
					'title' => 'Complaint',
					'message' => 'Record not found',
				], 404);
			}

		} else {

			$complaint = new Complaint();
			
			$complaint->created_at = date('Y-m-d H:i:s');

		}
		
		$complaint->updated_at = date('Y-m-d H:i:s');
		$complaint->company_id = $this->_getCompany()->id;
        $complaint->employee_id = $request->employee_id;
		$complaint->customer_id = $request->customer_id;
		$complaint->subject = $request->subject;
		$complaint->description = $request->description;

        if ($complaint->save()) {
			return $complaint;
		}

        return null;

    }

}
