<?php

namespace App\Http\Controllers;

use App\Contact;
use App\Company;
use Illuminate\Http\Request;
use Auth;

class ContactController extends Controller
{
    public function index()
    {
        $contacts = Contact::where('user_id', Auth::user()->id)->where('id', $id)->get();

        if (!$contacts)
        {
            return response()->json(['message'=>'Access Denied!'], 404);
        }

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

    public function sendRequest(Request $request)
    {
        $user = Auth::user();
        $com_id = $request->input('com_id');

        // query to find company asisng to $company
        $company = Company::find($com_id);

        // get user from session
        $request->user();
        $user = $request->user();

        // prepare query
         $contact = new Contact();
         $contact->com_id = $company->id;
         $contact->user_id = $user->id;
         $contact->save();

        return response()->json($contact, 201);
    }

    public function acceptRequest(Request $request, $id)
    {
        $contact = Contact::where('com_id', Auth::user()->company())->where('id', $id)->first();
        //$contact = Contact::where('id', '=', e($id))->first();
        if($contact)
        {
            $action=$request->input('action');
            if ($action==1)
            {
                $contact->status=1;
            }
            if ($action==0)
            {
                $contact->status=0;
            }
            else{

                return response()->json(["message" => "not allowed"], 400);
            }

            $saved = $contact->save();
            if ($saved){
                return response()->json($contact, 201);
            }
                return response()->json($contact, 400);
        }
    }

    public function destroy($id)
    {
        $contact = Contact::where('com_id', Auth::user()->company())->where('id', $id)->first();

        if (!$contact)
        {
            return response()->json(['message'=>'Access Denied!'], 404);
        }

        $contact->delete($id);

        return response()->json($contact, 204);
    }
}
