<?php

namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Config;
use App\Models\ServicesBooking;
use App\Models\ServiceAtributes;
use App\Models\ServiceAtributesValue;
use App\Models\Country;
use App\Models\Service;
use App\Models\ServicesBookingField;
use App\Models\ServiceBookingField;

class ServicesBookingController extends Controller
{
    public function store(Request $request)
    {
        
        
        $validatedData = $request->validate([
            'service_id' => 'required|integer',
            'booking_fields' => 'nullable|array',
        ]);
        $bookingId = $this->generateUniqueBookingId();
        $service_id = $validatedData['service_id'];
        $serviceBookingData = [
            'service_id' => $validatedData['service_id'],
            'booking_id' => $bookingId,
        ];

        $imagePath = Config::get('global.booking_service');
        $bookingFields = [];
        $wordCount = 0;
        $attributePrices = 0;
        $attributeDetails = [];
        foreach ($validatedData['booking_fields'] as $fieldId => $value) {
            $fieldLabel = ServiceBookingField::where('field_id', $fieldId)
                ->where('service_id', $validatedData['service_id'])
                ->value('label');
            $attribute = ServiceAtributes::where('name', 'LIKE', '%' . $fieldLabel . '%')
                ->where('service_id', $validatedData['service_id'])
                ->first();
                
           
            if ($attribute) {
                $attributeValue = ServiceAtributesValue::where('id',$value)->where('attribute_id', $attribute->id)
                    ->where('service_id', $validatedData['service_id'])
                    ->first();
                  
                
                if ($attributeValue && $attributeValue->price > 0) {
                    $attributePrices += $attributeValue->price; 
                    $attributeDetails[] = [
                        'name' => $attribute->name, 
                        'value' =>$attributeValue->name,
                        'price' => $attributeValue->price 
                    ]; 
                }
            }
            
               
            if ($fieldLabel == "Word Count") {
                    $wordCount = (int) $value;
                }

            if ($value instanceof \Illuminate\Http\UploadedFile) {
                $fileName = time() . '_' . $value->getClientOriginalName();
                $filePath = $value->storeAs($imagePath, $fileName, 'public');
                $value = $filePath;
            } elseif (is_array($value)) {
                $value = implode(',', $value);
            }
            

            $bookingFields[] = [
                'field_id' => $fieldId,
                'field_label' => $fieldLabel,
                'value' => $value,
            ];
        }
        

        $service = Service::with(['details', 'faqs'])->find($service_id);
        
        //$totalPrice = $wordCount > 0 ? $wordCount * $service->price_from : $service->price_from;
       // $totalPrice = $service->price_from; 
       $totalPrice = ($service->price_to > 0 && $service->price_to < $service->price_from) ? $service->price_to : $service->price_from;

        if ($attributePrices > 0) {
            $totalPrice = $wordCount > 0 ? ($wordCount * $attributePrices) : $attributePrices;
        } elseif ($wordCount > 0) {
            $totalPrice = $wordCount * $service->price_from;
        }

        // Store booking data in session
        session([
            'total_price' => $totalPrice,
            'service_booking' => $serviceBookingData,
            'booking_fields' => $bookingFields,
            'attribute_prices' => $attributePrices,
            'attribute_details' => $attributeDetails,
        ]);
        $service = Service::with(['details', 'faqs'])->find($service_id);

        $page_tittle = "Confirm Request";
        $headerimage = asset('storage/services/' . $service->background_image);
        $countries = Country::orderby('created_at','desc')->get();


        return view('front.confirmbookingservice', compact('page_tittle','wordCount','countries','headerimage','service_id','service','totalPrice'));

        //DB::beginTransaction();

        // try {
            
        //     $bookingId = $this->generateUniqueBookingId();
        //     $serviceBooking = ServicesBooking::create([
        //         'service_id' => $validatedData['service_id'],
        //         'booking_id' => $bookingId,
        //     ]);

        //     $imagePath = Config::get('global.booking_service');
            
        //     foreach ($validatedData['booking_fields'] as $fieldId => $value) {
        //         $fieldLabel = ServiceBookingField::where('field_id', $fieldId)->where('service_id',$validatedData['service_id'])->value('label');
                
        //         if ($value instanceof \Illuminate\Http\UploadedFile) {
                    
        //             $fileName = time() . '_' . $value->getClientOriginalName();
                    
        //             $filePath = $value->storeAs($imagePath, $fileName, 'public');
                    
        //             $value = $filePath;
        //         } elseif (is_array($value)) {
                    
        //             $value = implode(',', $value);
        //         }

        //         ServicesBookingField::create([
        //             'services_booking_id' => $serviceBooking->id,
        //             'field_id' => $fieldId,
        //             'field_label' => $fieldLabel,
        //             'value' => $value,
        //         ]);
        //     }

        //     DB::commit();
        //     return redirect()->back()->with('success', 'Service booking submitted successfully.');
        // } catch (\Exception $e) {
        //     DB::rollBack();
        //     return redirect()->back()->with('error', 'Failed to submit service booking. Please try again.');
        // }
    }
    public function storeBillingDetails(Request $request)
    {
        $validatedData = $request->validate([
            'first_name' => 'required|string',
            'total'    => 'required|numeric',
            'last_name' => 'required|string',
            'company_name' => 'nullable|string',
            'country' => 'required|string',
            'street_address' => 'required|string',
            'apartment' => 'nullable|string',
            'city' => 'required|string',
            'state' => 'required|string',
            'phone' => 'required|string',
            'email' => 'required|email',
            'file_namesconfirm' => 'nullable|string',
            'order_notes' => 'nullable|string',
        ]);
    
        // Retrieve session data
        $serviceBookingData = session('service_booking');
        $bookingFields = session('booking_fields');
    
        if (!$serviceBookingData || !$bookingFields) {
            return response()->json(['success' => false, 'message' => 'No booking data found in session. Please restart booking process.']);
        }
    
      
            // Merge billing details into service booking data
            $serviceBooking = ServicesBooking::create(array_merge($serviceBookingData, [
                'first_name' => $validatedData['first_name'],
                'last_name' => $validatedData['last_name'],
                'company_name' => $validatedData['company_name'],
                'country' => $validatedData['country'],
                'street_address' => $validatedData['street_address'],
                'apartment' => $validatedData['apartment'],
                'city' => $validatedData['city'],
                'state' => $validatedData['state'],
                'phone' => $validatedData['phone'],
                'email' => $validatedData['email'],
                'order_notes' => $validatedData['order_notes'],
                'total'      => number_format((float) $validatedData['total'], 2, '.', ''),
                'status' => 'Pending',
            ]));
    
            // Save booking fields
            foreach ($bookingFields as $field) {
                ServicesBookingField::create([
                    'services_booking_id' => $serviceBooking->id,
                    'field_id' => $field['field_id'],
                    'field_label' => $field['field_label'],
                    'value' => $field['value'],
                ]);
            }
            session([
                'booking_id' => $serviceBooking->id, 
            ]);
    
            
    
            
            session()->forget(['service_booking', 'booking_fields']);
    
            return response()->json(['success' => true, 'message' => 'Booking submitted successfully!', 'booking_id' => $serviceBooking->id]);
       
    }

    public function thankYouPage($id)
    {
        // Ensure user is authorized to view this booking
        if (session('booking_id') != $id) {
            return redirect()->route('home')->with('error', 'Unauthorized access to the thank you page.');
        }

        // Fetch the booking
        $booking = ServicesBooking::findOrFail($id);
        
        // Fetch the associated service with details & FAQs
        $service = Service::with(['details', 'faqs'])->find($booking->service_id);

        // Page metadata
        $page_tittle = "Booking Confirmation";
        $headerimage = asset('storage/services/' . ($service->background_image ?? 'default.jpg'));
        $total = $booking->total;
        // Extract billing details
        $billingDetails = [
            'first_name' => $booking->first_name,
            'last_name' => $booking->last_name,
            'company_name' => $booking->company_name,
            'country' => $booking->country,
            'street_address' => $booking->street_address,
            'apartment' => $booking->apartment,
            'city' => $booking->city,
            'state' => $booking->state,
            'phone' => $booking->phone,
            'email' => $booking->email,
            'order_notes' => $booking->order_notes,
        ];

        

        // Clear only relevant session data after displaying the page
        session()->forget(['booking_id', 'service_booking', 'booking_fields']);

        // Render the thank-you page with all required data
        return view('front.thankyoubookingservice', compact(
            'service', 'headerimage', 'page_tittle', 'booking',
            'billingDetails','total',
        ));
    }


    private function generateUniqueBookingId()
    {
        do {
            $randomNumber = mt_rand(100000000, 999999999);
            $bookingId = '#TS' . $randomNumber;
        } while (ServicesBooking::where('booking_id', $bookingId)->exists()); 

        return $bookingId;
    }
}
