<?php

namespace Workdo\MobileServiceManagement\Http\Controllers;

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

use Workdo\MobileServiceManagement\Entities\MobileServiceTrackingStatus;

use Workdo\MobileServiceManagement\Events\CreateMobileServiceTrackingStatus;
use Workdo\MobileServiceManagement\Events\UpdateMobileServiceTrackingStatus;
use Workdo\MobileServiceManagement\Events\DestroyMobileServiceTrackingStatus;

class MobileServiceTrackingStatusController extends Controller
{
    public function index(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice_trackingstatus manage')) {
            $trackingStatusData = MobileServiceTrackingStatus::where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->orderBy('order', 'asc')
                ->get();

            return view('mobile-service-management::service-setup.tracking-status.index', compact('trackingStatusData'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function orderUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'order'   => 'required|array',
            'order.*' => 'required|integer|exists:mobile_service_tracking_statuses,id'
        ]);

        if ($validator->fails()) {
            $messages = $validator->getMessageBag();
            return response()->json(['status' => false, 'message' => $messages->first()], 422);
        }

        foreach ($request->order as $key => $itemId) {
            $trackingStatus        = MobileServiceTrackingStatus::where('id', $itemId)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();
            $trackingStatus->order = $key;
            $trackingStatus->save();
        }

        return response()->json(['status' => true, 'message' => __('The status has been changed successfully')]);
    }

    public function create()
    {
        if (Auth::user()->isAbleTo('mobileservice_trackingstatus create')) {
            return view('mobile-service-management::service-setup.tracking-status.create');
        } else {
            return response()->json(['error' => __('Permission denied.')], 401);
        }
    }

    public function store(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice_trackingstatus create')) {
            $validator = Validator::make($request->all(), [
                'icon'         => 'required|string',
                'status_name'  => 'required|string',
                'status_color' => 'required|string'
            ]);

            if ($validator->fails()) {
                $messages = $validator->getMessageBag();
                return redirect()->back()->with('error', $messages->first());
            }

            $maxOrder = MobileServiceTrackingStatus::where('workspace', getActiveWorkSpace())
                ->where('created_by', creatorId())
                ->max('order') ?? 0;

            $trackingStatusData               = new MobileServiceTrackingStatus();
            $trackingStatusData->icon_name    = $request->icon;
            $trackingStatusData->status_color = $request->status_color;
            $trackingStatusData->status_name  = $request->status_name;
            $trackingStatusData->order        = $maxOrder + 1;
            $trackingStatusData->workspace    = getActiveWorkSpace();
            $trackingStatusData->created_by   = creatorId();
            $trackingStatusData->save();

            event(new CreateMobileServiceTrackingStatus($request, $trackingStatusData));

            return redirect()->back()->with('success', __('The tracking status has been created successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function edit(Request $request, $trackingStatusId)
    {
        if (Auth::user()->isAbleTo('mobileservice_trackingstatus edit')) {
            $trackingStatusData = MobileServiceTrackingStatus::where('id', $trackingStatusId)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($trackingStatusData) {
                return view('mobile-service-management::service-setup.tracking-status.edit', compact('trackingStatusData'));
            } else {
                return response()->json(['error' => __('Tracking status not found.')], 404);
            }
        } else {
            return response()->json(['error' => __('Permission denied.')], 401);
        }
    }

    public function update(Request $request, $trackingStatusId)
    {
        if (Auth::user()->isAbleTo('mobileservice_trackingstatus edit')) {
            $validator = Validator::make($request->all(), [
                'icon'         => 'required|string',
                'status_name'  => 'required|string',
                'status_color' => 'required|string'
            ]);

            if ($validator->fails()) {
                $messages = $validator->getMessageBag();
                return redirect()->back()->with('error', $messages->first());
            }

            $trackingStatusData = MobileServiceTrackingStatus::where('id', $trackingStatusId)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($trackingStatusData) {
                $trackingStatusData->icon_name    = $request->icon;
                $trackingStatusData->status_color = $request->status_color;
                $trackingStatusData->status_name  = $request->status_name;
                $trackingStatusData->save();

                event(new UpdateMobileServiceTrackingStatus($request, $trackingStatusData));

                return redirect()->back()->with('success', __('The tracking status details are updated successfully'));
            } else {
                return redirect()->back()->with('error', __('Tracking status not found.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function destroy($trackingStatusId)
    {
        if (Auth::user()->isAbleTo('mobileservice_trackingstatus delete')) {
            $trackingStatusData = MobileServiceTrackingStatus::where('id', $trackingStatusId)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($trackingStatusData) {
                event(new DestroyMobileServiceTrackingStatus($trackingStatusData));
                $trackingStatusData->delete();

                return redirect()->back()->with('success', __('The tracking status has been deleted'));
            } else {
                return redirect()->back()->with('error', __('Tracking status not found.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }
}
