<?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\DataTables\MobileServiceDataTable;

use Workdo\MobileServiceManagement\Entities\MobileService;
use Workdo\MobileServiceManagement\Entities\MobileServiceCategory;

use Workdo\MobileServiceManagement\Events\CreateMobileService;
use Workdo\MobileServiceManagement\Events\UpdateMobileService;
use Workdo\MobileServiceManagement\Events\DestroyMobileService;

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

    public function create()
    {
        if (Auth::user()->isAbleTo('mobileservice_service create')) {
            $categories = MobileServiceCategory::where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->get();

            return view('mobile-service-management::services.create', compact('categories'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function store(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice_service create')) {
            $validator = Validator::make($request->all(), [
                'name'              => 'required|string',
                'category_id'       => 'required|exists:mobile_service_categories,id',
                'expected_price'    => 'required|numeric|min:0',
                'expected_duration' => 'required|string',
                'icon'              => 'required|string'
            ]);

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

            $service                    = new MobileService();
            $service->name              = $request->name;
            $service->description       = $request->description;
            $service->icon              = $request->icon;
            $service->category_id       = $request->category_id;
            $service->expected_price    = $request->expected_price;
            $service->expected_duration = $request->expected_duration;

            // Filter out empty whats_included
            $whatsIncluded           = $request->whats_included ?? [];
            $filteredWhatsIncluded   = array_filter($whatsIncluded, function ($item) {
                return !empty($item['title']) || !empty($item['description']);
            });
            $service->whats_included = array_values($filteredWhatsIncluded);

            $service->show_in_expertise = $request->has('show_in_expertise') ? 1 : 0;
            $service->show_in_footer    = $request->has('show_in_footer') ? 1 : 0;
            $service->is_active         = $request->has('is_active') ? 1 : 0;
            $service->workspace         = getActiveWorkSpace();
            $service->created_by        = creatorId();
            $service->save();

            event(new CreateMobileService($request, $service));

            return redirect()->route('mobileservice.services.index')->with('success', __('The service has been created successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function show($id)
    {
        if (Auth::user()->isAbleTo('mobileservice_service manage')) {
            $id      = decrypt($id);
            $service = MobileService::with('category')
                ->where('id', $id)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($service) {
                return view('mobile-service-management::services.show', compact('service'));
            } else {
                return redirect()->back()->with('error', __('Service not found.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function edit($id)
    {
        if (Auth::user()->isAbleTo('mobileservice_service edit')) {
            $id      = decrypt($id);
            $service = MobileService::where('id', $id)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($service) {
                $categories = MobileServiceCategory::where('created_by', creatorId())
                    ->where('workspace', getActiveWorkSpace())
                    ->get();

                return view('mobile-service-management::services.edit', compact('service', 'categories'));
            } else {
                return redirect()->back()->with('error', __('Service not found.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function update(Request $request, $id)
    {
        if (Auth::user()->isAbleTo('mobileservice_service edit')) {
            $validator = Validator::make($request->all(), [
                'name'              => 'required|string',
                'category_id'       => 'required|exists:mobile_service_categories,id',
                'expected_price'    => 'required|numeric|min:0',
                'expected_duration' => 'required|string',
                'icon'              => 'required|string'
            ]);

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

            $id      = decrypt($id);
            $service = MobileService::where('id', $id)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($service) {
                $service->name              = $request->name;
                $service->description       = $request->description;
                $service->icon              = $request->icon;
                $service->category_id       = $request->category_id;
                $service->expected_price    = $request->expected_price;
                $service->expected_duration = $request->expected_duration;

                // Filter out empty whats_included
                $whatsIncluded           = $request->whats_included ?? [];
                $filteredWhatsIncluded   = array_filter($whatsIncluded, function ($item) {
                    return !empty($item['title']) || !empty($item['description']);
                });
                $service->whats_included = array_values($filteredWhatsIncluded);

                $service->show_in_expertise = $request->has('show_in_expertise') ? 1 : 0;
                $service->show_in_footer    = $request->has('show_in_footer') ? 1 : 0;
                $service->is_active         = $request->has('is_active') ? 1 : 0;
                $service->save();

                event(new UpdateMobileService($request, $service));

                return redirect()->route('mobileservice.services.index')->with('success', __('The service details are updated successfully'));
            } else {
                return redirect()->back()->with('error', __('Service not found.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function destroy($id)
    {
        if (Auth::user()->isAbleTo('mobileservice_service delete')) {
            $id      = decrypt($id);
            $service = MobileService::where('id', $id)
                ->where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->first();

            if ($service) {
                event(new DestroyMobileService($service));
                $service->delete();

                return redirect()->route('mobileservice.services.index')->with('success', __('The service has been deleted'));
            } else {
                return redirect()->back()->with('error', __('Service not found.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }
}
