<?php

namespace Workdo\MobileServiceManagement\Http\Controllers;

use App\Models\EmailTemplate;

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

use Workdo\MobileServiceManagement\DataTables\MobileServicePendingRequestDataTable;

use Workdo\MobileServiceManagement\Entities\MobileServiceRequest;

use Workdo\MobileServiceManagement\Events\DestroyMobileServicePendingRequest;
use Workdo\MobileServiceManagement\Events\AcceptMobileServicePendingRequest;
use Workdo\MobileServiceManagement\Events\RejectMobileServicePendingRequest;


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

    public function show(Request $request, $serviceId)
    {
        if (Auth::user()->isAbleTo('mobileservice_pendingrequest show')) {
            $serviceId      = decrypt($serviceId);
            $serviceReqData = MobileServiceRequest::where('service_id', $serviceId)
                ->where('workspace_id', getActiveWorkSpace())
                ->with('getServiceCreatedName', 'service', 'deviceBrand')
                ->first();

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

    public function destroy($serviceId)
    {
        if (Auth::user()->isAbleTo('mobileservice_pendingrequest delete')) {
            $serviceReqData = MobileServiceRequest::where('service_id', $serviceId)
                ->where('workspace_id', getActiveWorkSpace())
                ->first();

            if ($serviceReqData) {
                event(new DestroyMobileServicePendingRequest($serviceReqData));

                // Delete multiple attachments
                if (!empty($serviceReqData->attachment)) {
                    $attachments = explode(',', $serviceReqData->attachment);
                    foreach ($attachments as $attachment) {
                        if (!empty($attachment) && check_file($attachment)) {
                            delete_file($attachment);
                        }
                    }
                }

                // Delete request
                $serviceReqData->delete();

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

    public function acceptPendingRequest($serviceId)
    {
        if (Auth::user()->isAbleTo('mobileservice_pendingrequest approve-reject')) {
            $serviceReqData = MobileServiceRequest::where('service_id', $serviceId)
                ->where('workspace_id', getActiveWorkSpace())
                ->first();

            if ($serviceReqData) {
                $serviceReqData->is_approve = 1;
                $serviceReqData->save();

                $company_settings = getCompanyAllSetting();
                if (!empty($company_settings['Service Request Accept']) && $company_settings['Service Request Accept'] == true) {
                    $activeWorkspace = getActiveWorkSpace();
                    $workspace       = \App\Models\WorkSpace::where('id', $activeWorkspace)->where('created_by', creatorId())->first();
                    $trackingUrl     = route('mobileservice.frontend.index', ['workspaceSlug' => $workspace->slug]). '#tracking';
                    $link            = '<a href="' . $trackingUrl . '">Click here to track your courier</a>';

                    $uArr = [
                        'service_id'   => $serviceReqData->service_id,
                        'tracking_url' => $link,
                    ];
                    try {
                        $resp = EmailTemplate::sendEmailTemplate('Service Request Accept', [$serviceReqData->email], $uArr);
                    } catch (\Exception $e) {
                        $resp['error'] = $e->getMessage();
                    }
                }

                event(new AcceptMobileServicePendingRequest($serviceReqData));

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

    public function rejectPendingRequest($serviceId)
    {
        if (Auth::user()->isAbleTo('mobileservice_pendingrequest approve-reject')) {
            $serviceReqData = MobileServiceRequest::where('service_id', $serviceId)
                ->where('workspace_id', getActiveWorkSpace())
                ->first();

            if ($serviceReqData) {
                $serviceReqData->is_approve = 0;
                $serviceReqData->save();

                $company_settings = getCompanyAllSetting();
                if (!empty($company_settings['Service Request Reject']) && $company_settings['Service Request Reject'] == true) {
                    $uArr = [
                        'service_id' => $serviceReqData->service_id,
                    ];

                    try {
                        $resp = EmailTemplate::sendEmailTemplate('Service Request Reject', [$serviceReqData->email], $uArr);
                    } catch (\Exception $e) {
                        $resp['error'] = $e->getMessage();
                    }
                }

                event(new RejectMobileServicePendingRequest($serviceReqData));

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