<?php

namespace Workdo\MobileServiceManagement\Http\Controllers;

use App\Models\WorkSpace;

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

use Workdo\MobileServiceManagement\Entities\MobileService;
use Workdo\MobileServiceManagement\Entities\MobileServiceBrand;
use Workdo\MobileServiceManagement\Entities\MobileServiceCategory;
use Workdo\MobileServiceManagement\Entities\MobileServiceContact;
use Workdo\MobileServiceManagement\Entities\MobileServiceCustomPage;
use Workdo\MobileServiceManagement\Entities\MobileServiceLiveTracking;
use Workdo\MobileServiceManagement\Entities\MobileServiceRequest;
use Workdo\MobileServiceManagement\Entities\MobileServiceReview;
use Workdo\MobileServiceManagement\Entities\MobileServiceThemeSetting;
use Workdo\MobileServiceManagement\Entities\MobileServiceTrackingStatus;

use Workdo\MobileServiceManagement\Events\CreateMobileServiceRequest;

class MobileServiceFrontendController extends Controller
{
    protected $workspaceId;
    protected $workspaceSlug;
    protected $workspaceCreatedBy;

    // ============================================
    // Helper Function
    // ============================================
    private function initializeWorkspace($workspaceSlug, $shareData = true)
    {
        try {
            $workspace = WorkSpace::where('slug', $workspaceSlug)->firstOrFail();

            $this->workspaceSlug      = $workspaceSlug;
            $this->workspaceId        = $workspace->id;
            $this->workspaceCreatedBy = $workspace->created_by;

            // view are not randering that time false pass that in not need to run below query
            if ($shareData) {
                // Setting Get
                $settings = MobileServiceThemeSetting::getSettingsBySlug($workspaceSlug);

                // Footer in show service get
                $footerServices = MobileService::where('created_by', $this->workspaceCreatedBy)
                    ->where('workspace', $this->workspaceId)
                    ->where('show_in_footer', true)
                    ->where('is_active', true)
                    ->get();

                // Footer in show quick link get
                $footerCustomPages = MobileServiceCustomPage::where('created_by', $this->workspaceCreatedBy)
                    ->where('workspace', $this->workspaceId)
                    ->where('show_in_footer', true)
                    ->get();

                // current lang get
                if (!empty(session()->get('mobileservice_lang'))) {
                    $currantLang = session()->get('mobileservice_lang');
                } else {
                    $company_settings = getCompanyAllSetting($this->workspaceCreatedBy, $this->workspaceId);
                    $currantLang      = $company_settings['defult_language'] ?? 'en';
                }

                // Share this data in page
                view()->share([
                    'workspaceSlug'     => $this->workspaceSlug,
                    'workspaceId'       => $this->workspaceId,
                    'settings'          => $settings,
                    'footerServices'    => $footerServices,
                    'footerCustomPages' => $footerCustomPages,
                    'currantLang'       => $currantLang
                ]);
            }
        } catch (\Exception $e) {
            abort(404);
        }
    }

    public function index($workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        // Get services marked for expertise section
        $expertiseServices = MobileService::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->where('show_in_expertise', true)
            ->where('is_active', true)
            ->get();

        // Get latest approved reviews
        $approvedReviews = MobileServiceReview::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->where('is_approved', true)
            ->orderBy('created_at', 'desc')
            ->take(6)
            ->get();

        // Get review statistics
        $reviewStats = MobileServiceReview::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->where('is_approved', true)
            ->selectRaw('COUNT(*) as total_reviews, AVG(rating) as average_rating')
            ->first();

        // Get tracking statistics
        $trackingStats = [
            'completed_requests' => MobileServiceRequest::where('workspace_id', $this->workspaceId)
                ->where('is_repair_end', 1)
                ->count(),

            'satisfaction_rate'  => $reviewStats && $reviewStats->total_reviews > 0 ? round(($reviewStats->average_rating / 5) * 100) : 0,

            'five_star_reviews'  => MobileServiceReview::where('created_by', $this->workspaceCreatedBy)
                ->where('workspace', $this->workspaceId)
                ->where('is_approved', true)
                ->where('rating', 5)
                ->count(),

            'total_services'     => MobileService::where('created_by', $this->workspaceCreatedBy)
                ->where('workspace', $this->workspaceId)
                ->where('is_active', true)
                ->count()
        ];

        return view('mobile-service-management::frontend.index', compact('expertiseServices', 'approvedReviews', 'reviewStats', 'trackingStats'));
    }

    public function langChange($workspaceSlug, $key)
    {
        session(['mobileservice_lang' => $key]);
        return redirect()->back();
    }

    public function services($workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        $categories = MobileServiceCategory::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->get();

        $allServices = MobileService::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->where('is_active', true)
            ->get();

        return view('mobile-service-management::frontend.services', compact('categories', 'allServices'));
    }

    public function serviceDetails($workspaceSlug, $id)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        try {
            $serviceId = decrypt($id);
            $service   = MobileService::where('created_by', $this->workspaceCreatedBy)
                ->where('workspace', $this->workspaceId)
                ->where('is_active', true)
                ->find($serviceId);

            // Get similar services from same category first, then others
            $similarServices = MobileService::where('created_by', $this->workspaceCreatedBy)
                ->where('workspace', $this->workspaceId)
                ->where('is_active', true)
                ->where('id', '!=', $service->id)
                ->orderByRaw('CASE WHEN category_id = ? THEN 0 ELSE 1 END', [$service->category_id])
                ->take(6)
                ->get();

            // Get approved reviews for this service
            $reviews = MobileServiceReview::where('mobile_service_id', $service->id)
                ->where('created_by', $this->workspaceCreatedBy)
                ->where('workspace', $this->workspaceId)
                ->where('is_approved', true)
                ->orderBy('created_at', 'desc')
                ->get();

            return view('mobile-service-management::frontend.service-details', compact('service', 'similarServices', 'reviews'));
        } catch (\Exception $e) {
            return redirect()->back();
        }
    }

    public function reviewStore(Request $request, $workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug, false);

        $validator = Validator::make($request->all(), [
            'name'              => 'required|string',
            'email'             => 'required|email',
            'rating'            => 'required|integer|min:1|max:5',
            'review'            => 'required|string',
            'mobile_service_id' => 'required|exists:mobile_services,id'
        ]);

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

        // Get ALL requests by request email on service
        $serviceRequests = MobileServiceRequest::where('mobile_service_id', $request->mobile_service_id)
            ->where('email', $request->email)
            ->get();

        if (!$serviceRequests->isEmpty()) {
            // Filter completed service only get
            $completedRequests = $serviceRequests->where('is_repair_end', 1);
            if ($completedRequests->isEmpty()) {
                return redirect()->back()->with('error', __('You can leave a review after your service is completed.'))->withFragment('reviews');
            }

            // Find a completed request in not give review
            $unreviewedRequest = $completedRequests->first(function ($req) use ($request) {
                return !MobileServiceReview::where('service_id', $req->service_id)
                    ->where('email', $request->email)
                    ->exists();
            });
            if (!$unreviewedRequest) {
                return redirect()->back()->with('error', __('You have already submitted reviews for this service.'))->withFragment('reviews');
            }

            $review                    = new MobileServiceReview();
            $review->name              = $request->name;
            $review->email             = $request->email;
            $review->rating            = $request->rating;
            $review->review            = $request->review;
            $review->mobile_service_id = $request->mobile_service_id;
            $review->service_id        = $unreviewedRequest->service_id;
            $review->is_approved       = true;
            $review->workspace         = $this->workspaceId;
            $review->created_by        = $this->workspaceCreatedBy;
            $review->save();

            return redirect()->back()->with('success', __('Thank you for your review!'))->withFragment('reviews');
        } else {
            return redirect()->back()->with('error', __('Only customers who book this service can leave a review.'))->withFragment('reviews');
        }
    }

    public function faq($workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        return view('mobile-service-management::frontend.faq');
    }

    public function about($workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        return view('mobile-service-management::frontend.about');
    }

    public function contact($workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        return view('mobile-service-management::frontend.contact');
    }

    public function contactStore(Request $request, $workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug, false);

        $validator = Validator::make($request->all(), [
            'name'    => 'required|string',
            'email'   => 'required|email',
            'phone'   => 'nullable|string',
            'subject' => 'required|string',
            'message' => 'required|string'
        ]);

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

        $contact             = new MobileServiceContact();
        $contact->name       = $request->name;
        $contact->email      = $request->email;
        $contact->phone      = $request->phone;
        $contact->subject    = $request->subject;
        $contact->message    = $request->message;
        $contact->workspace  = $this->workspaceId;
        $contact->created_by = $this->workspaceCreatedBy;
        $contact->save();

        return redirect()->back()->with('success', __('Thank you for contacting us! We will get back to you soon.'));
    }

    public function customPage($workspaceSlug, $customPageSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        $page = MobileServiceCustomPage::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->where('slug', $customPageSlug)
            ->first();

        if ($page) {
            return view('mobile-service-management::frontend.custom-page', compact('page'));
        } else {
            return redirect()->back();
        }
    }

    public function booking($workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        $allServices = MobileService::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->where('is_active', true)
            ->get();

        $brands = MobileServiceBrand::where('created_by', $this->workspaceCreatedBy)
            ->where('workspace', $this->workspaceId)
            ->get();

        return view('mobile-service-management::frontend.booking', compact('allServices', 'brands'));
    }

    public function bookingStore(Request $request, $workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug, false);

        $validator = Validator::make($request->all(), [
            'customer_name'     => 'required|string',
            'email'             => 'required|email',
            'mobile_no'         => 'required|string',
            'address'           => 'nullable|string',
            'mobile_service_id' => 'required',
            'device_brand'      => 'required|exists:mobile_service_brands,id',
            'mobile_model'      => 'required|string',
            'priority'          => 'required|in:standard,priority,emergency',
            'description'       => 'required|string',
        ]);

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

        $url = null;
        if ($request->file('attachments')) {
            $uploadedPaths = [];
            foreach ($request->file('attachments') as $index => $file) {
                $ext             = $file->getClientOriginalExtension();
                $fileNameToStore = time() . '_' . $index . '.' . $ext;
                $path            = multi_upload_file($file, 'attachment', $fileNameToStore, 'mobileservice/');
                if ($path['flag'] == 1) {
                    $uploadedPaths[] = $path['url'];
                }
            }
            $url = !empty($uploadedPaths) ? implode(',', $uploadedPaths) : null;
        }

        $serviceReqData                      = new MobileServiceRequest();
        $serviceReqData->service_id          = time();
        $serviceReqData->customer_name       = $request->customer_name;
        $serviceReqData->email               = $request->email;
        $serviceReqData->mobile_no           = $request->mobile_no;
        $serviceReqData->address             = $request->address;
        $serviceReqData->mobile_service_id   = $request->mobile_service_id;
        $serviceReqData->device_brand        = $request->device_brand;
        $serviceReqData->mobile_model        = $request->mobile_model;
        $serviceReqData->priority            = $request->priority;
        $serviceReqData->description         = $request->description;
        $serviceReqData->special_requests    = $request->special_requests;
        $serviceReqData->attachment          = $url;
        $serviceReqData->tracking_status     = 'pending';
        $serviceReqData->tracking_status_log = 'pending';
        $serviceReqData->is_approve          = null;
        $serviceReqData->workspace_id        = $this->workspaceId;
        $serviceReqData->created_by          = $this->workspaceCreatedBy;
        $serviceReqData->save();

        $company_settings = getCompanyAllSetting($this->workspaceCreatedBy, $this->workspaceId);
        if (!empty($company_settings['New Mobile Service Request']) && $company_settings['New Mobile Service Request'] == true) {
            $trackingUrl = route('mobileservice.frontend.index', ['workspaceSlug' => $this->workspaceSlug]). '#tracking';
            $link        = '<a href="' . $trackingUrl . '">Click here to track your request</a>';

            $uArr = [
                'service_id'   => $serviceReqData->service_id,
                'tracking_url' => $link,
            ];

            try {
                $resp = \App\Models\EmailTemplate::sendEmailTemplate('New Mobile Service Request', [$serviceReqData->email], $uArr, $this->workspaceCreatedBy, $this->workspaceId);
            } catch (\Exception $e) {
                $resp['error'] = $e->getMessage();
            }
        }

        event(new CreateMobileServiceRequest($request, $serviceReqData));

        return redirect()->back()->with('success', __('Service request submitted successfully!'));
    }

    public function trackBookingRequest(Request $request, $workspaceSlug)
    {
        $slug = $workspaceSlug ?? abort(404);
        $this->initializeWorkspace($slug);

        $dataArray = $request->all();
        if (empty($dataArray) && session()->has('mobile_servicetrack_request')) {
            $dataArray = session('mobile_servicetrack_request');
        }

        $validator = Validator::make($dataArray, [
            'service_id' => 'required|string',
            'email'      => 'required|email',
        ]);

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

        $data = (object) $dataArray;

        $service = MobileServiceRequest::where('service_id', $data->service_id)
            ->where('workspace_id', $this->workspaceId)
            ->first();

        if ($service) {
            if ($service->email !== $data->email) {
                return redirect()->back()->with('error', __('The email you entered does not match our records for this booking.'))->withFragment('tracking');
            }

            if (is_null($service->is_approve)) {
                return redirect()->back()->with('error', __('Your booking is still pending approval. Please wait for confirmation.'))->withFragment('tracking');
            }

            if ($service->is_approve == 1) {
                $currentTrackingStatus = MobileServiceLiveTracking::where('service_id', $service->service_id)->pluck('date', 'tracking_status_id');
                $allTrackingStatus     = MobileServiceTrackingStatus::where('workspace', $this->workspaceId)->orderBy('order', 'asc')->get();
                // for lang change
                session([
                    'mobile_servicetrack_request' => [
                        'service_id' => $data->service_id,
                        'email'      => $data->email,
                    ]
                ]);
                return view('mobile-service-management::frontend.booking-details', compact('service', 'currentTrackingStatus', 'allTrackingStatus'));
            } else {
                return redirect()->back()->with('error', __('Unfortunately, your booking request was rejected.'))->withFragment('tracking');
            }
        } else {
            return redirect()->back()->with('error', __('Service not found.'))->withFragment('tracking');
        }
    }
}
