<?php

namespace Workdo\MobileServiceManagement\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;

use Workdo\MobileServiceManagement\Entities\MobileServiceContact;

use Workdo\MobileServiceManagement\DataTables\MobileServiceContactDataTable;

class MobileServiceContactController extends Controller
{
    public function index(MobileServiceContactDataTable $dataTable)
    {
        if (Auth::user()->isAbleTo('mobileservice_contact manage')) {
            return $dataTable->render('mobile-service-management::contacts.index');
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function destroy($id)
    {
        if (Auth::user()->isAbleTo('mobileservice_contact manage')) {
            $contact = MobileServiceContact::where('id', $id)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($contact) {
                $contact->delete();
                return redirect()->route('mobileservice.contacts.index')->with('success', __('The contact has been deleted'));
            } else {
                return redirect()->back()->with('error', __('Contact not found.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function description($id)
    {
        if (Auth::user()->isAbleTo('mobileservice_contact manage')) {
            $contact = MobileServiceContact::where('id', $id)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($contact) {
                return view('mobile-service-management::contacts.description', compact('contact'));
            } else {
                return response()->json(['error' => __('Contact not found.')], 404);
            }
        } else {
            return response()->json(['error' => __('Permission denied.')], 401);
        }
    }
}
