<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Models\Slider;
use App\Models\Service;
use App\Models\ServiceDetail;
use App\Models\ServiceFaq;
use App\Models\Booking;
use App\Models\ServicesBooking;
use App\Models\Language;
use App\Models\ContactUs;

use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Http\JsonResponse;
use App\Models\Whychooseus;
use App\Models\WorkProcess;
use App\Models\HomeLogos;
use App\Models\CustomerReviews;
use App\Models\Insights;
class HomeController extends Controller 
{
    public function index()
    { 
      $page_tittle = 'Home';
      $sliders = Slider::with('buttons')->where('status', 1)->orderBy('created_at', 'desc')->get();
      $services = Service::with(['details', 'faqs'])->where('status', 1)->orderBy('created_at', 'desc')->get();
    //   $services = Service::with(['details', 'faqs'])->where('status', 1)
    //     ->whereHas('servicePricing', function ($query) {
    //         $query->whereColumn('service_pricing.service_id', 'services.service_type_id');
    //     })->orderBy('created_at', 'desc')->get();

        $whychooseus = Whychooseus::where('status', 1)->orderBy('created_at', 'desc')->get();
        $workprocess = WorkProcess::where('status', 1)->orderBy('created_at', 'desc')->get();
        $logos = HomeLogos::where('status', 1)->orderBy('created_at', 'desc')->get();
        $reviews = CustomerReviews::where('status', 1)->orderBy('created_at', 'desc')->get();
        $insights = Insights::where('status', 1)->orderBy('created_at', 'desc')->get();
      
        
        return view('front.index', compact('page_tittle', 'sliders','services','whychooseus','workprocess','logos','reviews','insights'));

    }
    public function track_status(Request $request)
    {
        $page_tittle = 'Track Status';
        
        return view('front.track_status', compact('page_tittle'));
        
    }
    public function trackStatusbyid(Request $request)
    {

        $page_tittle = 'Track Result';
        $request->validate([
            'tracking_id' => 'required|string|max:255', 
        ]);

        $trackingId = $request->input('tracking_id');
        if (!str_starts_with($trackingId, '#')) {
            $trackingId = '#' . $trackingId;
        }
        $booking = Booking::where('booking_id', $trackingId)->first();
        

        if ($booking) {
            $fromLanguage = Language::find($booking->translation_from)?->name ?? 'N/A';
            $toLanguages = Language::whereIn('id', json_decode($booking->translation_to, true) ?? [])->pluck('name')->toArray();
            $fileNames = explode(',', $booking->file_names ?? '');
            $documentTypes = collect($fileNames)->map(function ($fileName) {
                $extension = pathinfo($fileName, PATHINFO_EXTENSION);
                return match (strtolower($extension)) {
                    'doc', 'docx' => 'Word Document',
                    'pdf' => 'PDF Document',
                    'txt' => 'Text Document',
                    default => 'Unknown Document',
                };
            });
            $fileCount = count(explode(',', $booking->file_names ?? ''));
            return view('front.trackresult', ['booking' => $booking ,'fromLanguage' => $fromLanguage, 'toLanguages' => $toLanguages, 'fileNames' => $fileNames,'documentTypes' => $documentTypes,'fileCount' => $fileCount, 'page_tittle' => $page_tittle]);
        } else {
            return back()->withErrors(['tracking_id' => 'Tracking ID not found. Please try again.']);
        }
    }
    public function trackbookingstatusbyid(Request $request)
    {

        $page_tittle = 'Track Result';
        $request->validate([
            'tracking_id' => 'required|string|max:255', 
        ]);

        $trackingId = $request->input('tracking_id');
        if (!str_starts_with($trackingId, '#')) {
            $trackingId = '#' . $trackingId;
        }
        $booking = ServicesBooking::with(['fields','service'])->where('booking_id', $trackingId)->first();
        

        if ($booking) {
           
            return view('front.trackbookingresult', ['booking' => $booking , 'page_tittle' => $page_tittle]);
        } else {
            return back()->withErrors(['tracking_id' => 'Tracking ID not found. Please try again.']);
        }
    }

    public function saveContactForm(Request $request)
    {
        // Define validation rules
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'subject' => 'nullable|string|max:255',
            'message' => 'required|string',
        ]);

        // Check if validation fails
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => $validator->errors()->first()
            ]);
        }

        // Save the data in the contact_us table
        $contact = new ContactUs();
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->subject = $request->subject;
        $contact->message = $request->message;
        $contact->save();

        // Return a success response
        return response()->json([
            'status' => 'success',
            'message' => 'Your message has been sent successfully!'
        ]);
    }
   
}
