<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;

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\Service;
use App\Models\ServiceBookingField;
use App\Models\FieldCondition;
use App\Models\DelieveryTypes;
use App\Models\ServiceDetail;
use App\Models\TranslationTypeCategories;

use App\Models\ServiceFaq;
use App\Models\Cities;
use App\Models\Country;
use App\Models\Booking;
use App\Models\Language;
use App\Models\TranslationType;
use App\Models\ServicePricing;
use App\Models\Quote;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class ServicesController extends Controller
{
    public function index()
    {
      $page_tittle = 'Our Services';
      
      $headerimage = asset('front/assets/images/page-header-default.jpg');
    $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();

        
        
        return view('front.services', compact('page_tittle','headerimage','services'));

    }

  public function detail($id) {
   
        
      $service = Service::with(['details', 'faqs'])->find($id);
      $formfields = ServiceBookingField::where('service_id',$id)->get();
      $attributeOptions = [];
        foreach ($formfields as $field) {
            if ($field->type === 'select' && $field->attribute_id) {
                // Fetch attribute values from the relevant table
                $attributeOptions[$field->id] = DB::table('service_atributes_value')->where('attribute_id', $field->attribute_id)->pluck('name', 'id');
            }
        }
        $fieldConditions = FieldCondition::where('service_id', $id)->get();

        
     
      
        $page_tittle = $service->title;
        $headerimage = asset('storage/services/' . $service->background_image);
        $minPrice = ServicePricing::where('service_id', $service->service_type_id)->min('price');
        $maxPrice = ServicePricing::where('service_id', $service->service_type_id)->max('price');
      
      return view('front.servicedetail', compact('service','headerimage','page_tittle','fieldConditions', 'minPrice', 'maxPrice','attributeOptions','formfields'));
  }
  public function booking($id) {
          
      $service = Service::with(['details', 'faqs'])->find($id);
      $page_tittle = $service->title;
      $headerimage = asset('storage/services/' . $service->background_image);
      $languages = Language::where('status', 1)->get();
      $cities = Cities::where('status', 1)->orderby('name','asc')->get();
      $serviceCategoryId = $service->service_type_id;
      
     
       
        $languagesFrom = Language::whereIn('id', function ($query) use ($serviceCategoryId) {
            $query->select('translation_from')
                ->distinct()
                ->from('service_pricing')
                ->where('service_id', $serviceCategoryId)
                ->whereNotNull('translation_from');
        })->get();


            // Get the languages where there's a valid pricing combination for "translation_to"
            $languagesTo = Language::whereIn('id', function ($query) use ($serviceCategoryId) {
                $query->select('translation_to')
                    ->from('service_pricing')
                    ->where('service_id', $serviceCategoryId)
                    ->whereNotNull('translation_to') // Ensure translation_to is valid
                    ->whereNotNull('price') // Ensure that there's a valid price set
                    ->where('price', '>', 0); // Ensure the price is greater than zero
            })->distinct()->get();

            // Now we want to ensure that the `languagesTo` only contains those that have a valid combination with `translation_from`
            $languagesToFiltered = $languagesTo->filter(function ($languageTo) use ($serviceCategoryId, $languagesFrom) {
                // Check if there exists a valid price for both translation_from and translation_to
                return DB::table('service_pricing')
                    ->where('service_id', $serviceCategoryId)
                    ->where('translation_to', $languageTo->id)
                    ->whereIn('translation_from', $languagesFrom->pluck('id')) // Match from languages
                    ->whereNotNull('price')
                    ->where('price', '>', 0)
                    ->exists();
            }); 
            
            $translationcat = TranslationTypeCategories::where('status',1)->get();
            



      
      return view('front.servicebooking', compact('service','headerimage','page_tittle','languages','cities','languagesFrom','languagesTo','languagesToFiltered','translationcat'));
  }

    public function getLanguages(Request $request)
    {
        $serviceId = $request->get('service_id');
        $selectedToLang = $request->get('translation_to');

        // Get the languages where there's a valid pricing combination for "translation_from"
        $languagesFrom = Language::whereIn('id', function ($query) use ($serviceId, $selectedToLang) {
            $query->select('translation_to')
                ->from('service_pricing')
                ->where('service_id', $serviceId)
                ->where('translation_from', $selectedToLang) // Filter by the selected translation_to
                ->whereNotNull('translation_to') // Ensure translation_from is valid
                ->whereNotNull('price') // Ensure that there's a valid price set
                ->where('price', '>', 0); // Ensure the price is greater than zero
        })->distinct()->get();

        // Return the filtered languages
        $availableLanguages = $languagesFrom->map(function ($language) {
            return [
                'id' => $language->id,
                'name' => $language->name
            ];
        });

        return response()->json([
            'languages' => $availableLanguages
        ]);
    }


  public function saveBookingData(Request $request)
    {

        $request->validate([
            'recipient' => 'required|string|max:255',
            'city' => 'required|string|max:255',
            'zipcode' => 'required|numeric',
            'address' => 'required|string|max:255',
            'appartment' => 'nullable|string|max:255',
            'phone' => 'required|numeric',
        ]);

        
        session([
            'service_id' =>  $request->input('service_id'),
            'recipient' => $request->input('recipient'),
            'city' => $request->input('city'),
            'zipcode' => $request->input('zipcode'),
            'address' => $request->input('address'),
            'appartment' => $request->input('appartment'),
            'phone' => $request->input('phone'),
            'additional_info' => $request->input('additional_info'),
            'full_name' => $request->input('full_name'),
            'full_email' => $request->input('full_email'),
            'translation_from' => $request->input('translation_from'),
            'translation_to' => $request->input('translation_to'),
            'total_pagestranslation' => $request->input('total_pagestranslation'),
            'word_counttranslation' => $request->input('word_counttranslation'),
            'file_names' => $request->input('file_names'),
            'inlineRadioOptions' => $request->input('inlineRadioOptions'),
            'addinfotextarea' => $request->input('addinfotextarea'),
        ]);

        return response()->json([
            'message' => 'Booking data saved successfully.',
            'data' => session()->all(),
            'redirect_url' => route('services.confirmbooking', $request->service_id)
        ]);
    }

  public function confirmbooking($id) {
            
      $service = Service::with(['details', 'faqs'])->find($id);
         
        $page_tittle = "Confirm Request";
        $headerimage = asset('storage/services/' . $service->background_image);
        $totalPrice = session('total_price', 0);
        $priceDetails = session('price_details', []);
        $wordsCount = session('words_count', 0);
        $translationTypePrice = session('translation_type_price', 0);
        $countries = Country::orderby('created_at','desc')->get();

      return view('front.confirmbooking', compact('service','headerimage','countries','page_tittle','totalPrice','priceDetails','wordsCount','translationTypePrice'));
  }
    private function generateUniqueBookingId()
    {
        do {
            $randomNumber = mt_rand(100000000, 999999999);
            $bookingId = '#TS' . $randomNumber;
        } while (Booking::where('booking_id', $bookingId)->exists()); 

        return $bookingId;
    }
   
    public function saveconfirmbookingdata(Request $request)
    {
        
        $bookingId = $this->generateUniqueBookingId();

        
        $postData = $request->only([
            'first_name', 'last_name', 'company_name', 'country', 'street_address',
            'apartment', 'city', 'state', 'phone', 'email', 
             'order_notes','file_namesconfirm'
        ]);


        $sessionData = session()->only([
            'total_price', 'price_details', 'words_count', 'translation_type_checkout_price', 
            'service_id', 'recipient', 'zipcode', 'address', 'appartment', 
            'phone', 'additional_info', 'full_name', 'full_email', 
            'translation_from', 'translation_to', 'total_pagestranslation', 
            'word_counttranslation', 'file_names', 'inlineRadioOptions', 'addinfotextarea','translation_type','delivery_method','delivery_type','delivery_method_checkout_price','delivery_type_checkout_price'
        ]);

        $priceDetails = isset($sessionData['price_details']) && is_array($sessionData['price_details']) 
            ? json_encode($sessionData['price_details']) 
            : $sessionData['price_details'];

        $fileNames = isset($sessionData['file_names']) && is_array($sessionData['file_names']) 
            ? json_encode($sessionData['file_names']) 
            : $sessionData['file_names'];

            $confirmfileNames = $postData['file_namesconfirm'];

        $bookingData = array_merge($postData, [
            'booking_id' => $bookingId,
            'total_price' => isset($sessionData['total_price']) ? $sessionData['total_price'] + ($sessionData['total_price'] * 0.05)  : null,
            'vat_amount' => isset($sessionData['total_price']) ? $sessionData['total_price'] * 0.05  : null,
            'price_details' => $priceDetails,
            'words_count' => $sessionData['words_count'] ?? null,
            'translation_type_price' => (is_numeric($sessionData['translation_type_checkout_price'] ?? null) || $sessionData['translation_type_checkout_price'] !== 'Free') ? $sessionData['translation_type_checkout_price'] ?? 0 : 0,
            'delivery_method_price' => isset($sessionData['delivery_method_checkout_price']) ? (is_numeric($sessionData['delivery_method_checkout_price']) || $sessionData['delivery_method_checkout_price'] !== 'Free') ? $sessionData['delivery_method_checkout_price'] : 0 : 0,
            //'delivery_method_price' => (is_numeric($sessionData['delivery_method_checkout_price'] ?? null) || $sessionData['delivery_method_checkout_price'] !== 'Free') ? $sessionData['delivery_method_checkout_price'] ?? 0 : 0,
            'delivery_type_price' => (is_numeric($sessionData['delivery_type_checkout_price'] ?? null) || $sessionData['delivery_type_checkout_price'] !== 'Free') ? $sessionData['delivery_type_checkout_price'] ?? 0 : 0,
            'service_id' => $sessionData['service_id'] ?? null,
            'recipient' => $sessionData['recipient'] ?? null,
            'zipcode' => $sessionData['zipcode'] ?? null,
            'address' => $sessionData['address'] ?? null,
            'appartment' => $sessionData['appartment'] ?? null,
            'session_phone' => $sessionData['phone'] ?? null,
            'translation_type' => $sessionData['translation_type'] ?? null,
            'delivery_type' => $sessionData['delivery_type'] ?? null,
            'delivery_method' => $sessionData['delivery_method'] ?? null, 
            'additional_info' => $sessionData['additional_info'] ?? null,
            'full_name' => $sessionData['full_name'] ?? null,
            'full_email' => $sessionData['full_email'] ?? null,
            'translation_from' => $sessionData['translation_from'] ?? null,
            'translation_to' => json_encode($sessionData['translation_to'] ?? []), 
            'total_pagestranslation' => $sessionData['total_pagestranslation'] ?? null,
            'word_counttranslation' => $sessionData['word_counttranslation'] ?? null,
            'file_names' => $fileNames,
            'confirmfile_names' => $confirmfileNames,
            'inlineRadioOptions' => $sessionData['inlineRadioOptions'] ?? null,
            'addinfotextarea' => $sessionData['addinfotextarea'] ?? null,
            'status'          => 'Pending',
        ]);

        $booking = Booking::create($bookingData);
        session([
            'booking_id' => $booking->id, 
        ]);

        return response()->json(['booking_id' => $booking->id]);
    
       
    }

    public function thankYouPage($id)
    {

        if (session('booking_id') != $id) {
            return redirect()->route('home')->with('error', 'Unauthorized access to the thank you page.');
        }
        $booking = Booking::findOrFail($id);
        
        $service = Service::with(['details', 'faqs'])->find($booking->service_id);

        $page_tittle = "Confirm Request";
        $headerimage = asset('storage/services/' . $service->background_image);
        session()->forget([
            //'booking_id',
            'total_price',
            'price_details',
            'words_count',
            'translation_type_checkout_price',
            'delivery_type_checkout_price',
            'delivery_method_checkout_price',
            'translation_type',
            'delivery_type',
            'delivery_method',
            'service_id',
            'recipient',
            'city',
            'zipcode',
            'address',
            'appartment',
            'phone',
            'additional_info',
            'full_name',
            'full_email',
            'translation_from',
            'translation_to',
            'total_pagestranslation',
            'word_counttranslation',
            'file_names',
            'inlineRadioOptions',
            'addinfotextarea',
        ]);
        $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.thankyoubooking', compact('service', 'headerimage', 'page_tittle', 'booking', 'fromLanguage', 'toLanguages','documentTypes','fileCount'));
    }

    

    

  

   public function quote(Request $request)
    {
        
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'from_lang' => 'required|string',
            'to_lang' => 'required|array',
            'service_id' => 'required|integer',
            'total_pages' => 'required|numeric',
            'word_count' => 'required|numeric',
        ]);

        
        
        $quote = Quote::create([
          'name' => $validated['name'],
          'email' => $validated['email'],
          'from_lang' => $validated['from_lang'],
          'to_lang' => implode(',', $validated['to_lang']),
          'total_pages' => $validated['total_pages'],
          'word_count' => $validated['word_count'],
          'service_id' => $validated['service_id'],
      ]);

        
        return response()->json(['message' => 'Quote submitted successfully'], 200);
    } 

    public function storedocuments(Request $request)
    {
        
        $disk = Config::get('global.disk');
        $imagePath = Config::get('global.booking_service');
        $uploadedFiles = [];
        $validExtensions = ['pdf', 'doc', 'docx'];
        
        foreach ($request->file('file') as $file) {
          $fileExtension = $file->getClientOriginalExtension();
          if (!in_array($fileExtension, $validExtensions)) {
            return response()->json(['error' => 'Invalid file type. Only PDF and DOC files are allowed.'], 400);
          }

          $fileName = time() . uniqid() . '.' . $fileExtension;
  
          $file->storeAs($imagePath, $fileName, 'public');  
  
          $uploadedFiles[] = $fileName;
      }
        
        return response()->json(['success' => 'File uploaded successfully', 'files' => $uploadedFiles]);
    }

    public function deleteFile(Request $request)
    {
        $fileName = $request->input('file_name');
        
        $disk = Config::get('global.disk');
        $imagePath = Config::get('global.booking_service');

        $filePath = $imagePath . '/' . $fileName;
        
        if (Storage::disk($disk)->exists($filePath)) {
            Storage::disk($disk)->delete($filePath);
            
          

            return response()->json(['success' => 'File deleted successfully']);
        } else {
            return response()->json(['error' => 'File not found'], 404);
        }
    }

    public function getServicePrice(Request $request)
    {

        $validatedData = $request->validate([
            'service_id' => 'required|integer',
            'translation_from' => 'required|string', 
            'translation_to' => 'required|array|min:1', 
            'words_count' => 'required|integer',
        ]);
    
        $translationFrom = $validatedData['translation_from'];
        $translationTo = $validatedData['translation_to'];
        $serviceId = $validatedData['service_id'];
        $words_count = $validatedData['words_count'];
    
        $languageNames = Language::whereIn('id', array_merge([$translationFrom], $translationTo))
            ->pluck('name', 'id'); 
    
        $prices = ServicePricing::where('service_id', $serviceId)
            ->where('translation_from', $translationFrom)
            ->whereIn('translation_to', $translationTo)
            ->get(['translation_to', 'price']);
    
        $totalPrice = $prices->sum('price') * $words_count;
    
        $priceDetails = $prices->map(function ($price) use ($translationFrom, $languageNames, $words_count) {
            return [
                'from' => $languageNames[$translationFrom] ?? 'Unknown', 
                'to' => $languageNames[$price->translation_to] ?? 'Unknown', 
                 'price' => $price->price * $words_count,     
            ];
        });
        session([
            'total_price' => $totalPrice,
            'price_details' => $priceDetails,
            'words_count' => $words_count,
            'translation_type_price' => 0, 
        ]);
    
        return response()->json([
            'total_price' => $totalPrice,
            'price_details' => $priceDetails,
            'words_count' => $words_count,
            'translation_type_price' => 0
        ]);
    }

    public function calculateTotaltranslationprice(Request $request)
    {

        $translationPrice = $request->input('translationPrice'); 
        $translationOptionSlug = $request->input('translationOptionSlug'); 
        $percentage = $request->input('percentage', 0); 
        $translationOptionTitle = $request->input('title'); 
        $totalPrice = $request->input('totalPrice'); 

        
        
       
        
        if ($percentage > 0) {
            $totalPrice += ($totalPrice * ($percentage / 100));  
            $translationamount =   $totalPrice * ($percentage / 100);
        }
        if ($translationPrice > 0) {
            $totalPrice += ($translationPrice);  
        }
        
        if($translationPrice == 0){
            $translationPrice = "Free";
            $translationamount  = 0;

        }else{
            $translationPrice = $translationPrice;
            $translationamount  = $translationPrice;
        }

        

        session([  
            'translation_type' => $translationOptionTitle,
            'translation_type_checkout_price' => $translationPrice,
        ]);
        return response()->json([
            'success' => true,
            'totalPrice' => $totalPrice,
            'translationtype' => $translationOptionTitle,
            'translationPrice' => $translationPrice,
            'translationamount' => $translationamount,
        ]);
    }

    public function calculateTotalfordelieverydelection(Request $request)
    {
        // Retrieve inputs from the request
        $delieverytypeprice = $request->input('delieverytypeprice', 0); 
        $translationOptionSlug = $request->input('translationOptionSlug'); 
        $percentage = $request->input('percentage', 0); 
        $title = $request->input('title'); 
        $totalPrice = $request->input('totalPrice', 0); 
        $translationamount = $request->input('translationamount', 0);

        $finalTotalPrice = $totalPrice;
        $finalTotalPrice = floatval($finalTotalPrice);  // Convert to float
        $translationamount = floatval($translationamount);
        $delieveryselectionprice = 0;

        // If delivery type price is greater than 0, add it to the total
        if ($delieverytypeprice > 0) {
            $finalTotalPrice += $delieverytypeprice;
        }

        // If percentage is greater than 0, apply the percentage to the total price
        if ($percentage > 0) {
            $percentageAmount = $finalTotalPrice * ($percentage / 100);
            $delieveryselectionprice = $percentageAmount;
            $finalTotalPrice += $percentageAmount; // Add the percentage amount to the final price
        }
       
        if ($translationamount > 0) {
            $finalTotalPrice += ($translationamount);  
        }
        

        $translationPrice = $translationamount > 0 ?  $translationamount : 0;
        $deliverySelectionAmount = $delieveryselectionprice > 0 ?  $delieveryselectionprice : 0;

        // Update session data (if necessary)
        session([
            'delivery_method' => $title, // assuming 'title' is the delivery type
            'delivery_method_checkout_price' => $deliverySelectionAmount,
        ]);

       

        // Return the calculated data as JSON response
        return response()->json([
            'success' => true,
            'totalPrice' => number_format($finalTotalPrice, 2), // Format total price
            'deliveryselection' => $title, // Delivery selection title (e.g., EXPEDITED)
            'translationPrice' => $translationPrice,
            'deliveryselectionamount' => $deliverySelectionAmount, // Amount for delivery selection
            'deliveryselectiontype' => $delieverytypeprice > 0 ? 1 : 0, // Example: 1 for delivery, 0 for no delivery
        ]);
    }

    public function calculateTotalfordelieverymethod(Request $request)
    {
        // Retrieve inputs from the request
        $delieverytypeprice = $request->input('delieverytypeprice', 0); 
        $translationOptionSlug = $request->input('translationOptionSlug'); 
        $percentage = $request->input('percentage', 0); 
        $title = $request->input('title'); 
        $totalPrice = $request->input('totalPrice', 0); 
        $translationamount = $request->input('translationamount', 0);
        $delieveryselectionamount = $request->input('delieveryselectionamount', 0);

        // Initialize final total price as float
        $finalTotalPrice = floatval($totalPrice);  
        $translationamount = floatval($translationamount);
        $delieveryselectionamount = floatval($delieveryselectionamount);
        $delieverymethodprice = 0;

        // Add delivery selection amount to the final total price if greater than 0
        if ($delieveryselectionamount > 0) {
            $finalTotalPrice += $delieveryselectionamount; // Add delivery selection to total price
            
        }

        // Add delivery type price to the final total price if greater than 0
        if ($delieverytypeprice > 0) {
            $finalTotalPrice += $delieverytypeprice; // Add delivery type price to the total price
            $delieverymethodprice = $delieverytypeprice;
            
        }

        // Apply percentage to the total price if percentage is greater than 0
        if ($percentage > 0) {
            $percentageAmount = $finalTotalPrice * ($percentage / 100);
            $delieverymethodprice = $percentageAmount;
            $finalTotalPrice += $percentageAmount; // Add the percentage amount to the total price
            
        }
        if ($translationamount > 0) {
            $finalTotalPrice += ($translationamount);  
        }

        // Calculate the translation price and delivery selection amount in AED
        $translationPrice = $translationamount > 0 ?  $translationamount : 0;
        $deliverySelectionAmount = $delieverymethodprice > 0 ?  $delieverymethodprice : 0;

        // Update session data (if necessary)
        session([
            'delivery_type' => $title, // assuming 'title' is the delivery type
            'delivery_type_checkout_price' => $deliverySelectionAmount,
            'total_price' => $finalTotalPrice,
        ]);

        // Return the calculated data as JSON response
        return response()->json([
            'success' => true,
            'totalPrice' => number_format($finalTotalPrice, 2), // Format total price
            'deliveryselection' => $title, // Delivery selection title (e.g., DIGITAL DELIVERY)
            'translationPrice' => $translationPrice, // Formatted translation price
            'deliveryselectionamount' => $deliverySelectionAmount, // Formatted delivery selection amount
            'deliveryselectiontype' => $delieverytypeprice > 0 ? 1 : 0, // Example: 1 for delivery, 0 for no delivery
        ]);
    }





    public function getTranslationTypeDetails(Request $request)
    {

        $validatedData = $request->validate([
            'translationOption' => 'required|string|in:certified,only_translation,notarized',
        ]);

        
        $translationOption = $validatedData['translationOption'];
        $translationTypes = TranslationType::where('category', $translationOption)->get();


        if ($translationTypes->isNotEmpty()) {
            return response()->json([
                'success' => true,
                'data' => $translationTypes->map(function ($translationType) {
                    return [
                        'id' => $translationType->id,
                        'title' => $translationType->name,
                        'description' => $translationType->description,
                        'price_type' => $translationType->price_type,
                        'percentage' => $translationType->percentage,
                        'price' => $translationType->price,
                    ];
                }),
            ]);
        }


        return response()->json(['success' => false, 'message' => 'Translation type not found.'], 404);
    }

    public function getTranslationTypeDelieverey(Request $request)
    {

        $validatedData = $request->validate([
            'translationOption' => 'required|string',
        ]);

        
        $translationOption = $validatedData['translationOption'];
        $translationTypes = DelieveryTypes::where('translation_type_id', $translationOption)->get();


        if ($translationTypes->isNotEmpty()) {
            return response()->json([
                'success' => true,
                'data' => $translationTypes->map(function ($translationType) {
                    return [
                        'id' => $translationType->id,
                        'title' => $translationType->name,
                        'description' => $translationType->description,
                        'price_type' => $translationType->price_type,
                        'percentage' => $translationType->percentage,
                        'price' => $translationType->price,
                    ];
                }),
            ]);
        }


        return response()->json(['success' => false, 'message' => 'Translation type not found.'], 404);
    }

    





   
}
