<?php

namespace App\Http\Controllers;


use App\Http\Controllers\Controller;
use App\Models\Country;
use App\Models\Currency;
use App\Models\DistanceRequest;
use App\Models\WebRequestModel;
use App\Models\LanguageModel;
use App\Models\ManageRequestModel;
use App\Models\PagesModel;
use App\Models\ProductBrandModel;
use App\Models\ProductIndustryModel;
use App\Models\ProductTypeModel;
use App\Models\Service;
use App\Models\ServiceTypeModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Settings;
use App\Models\SliderModel;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;

class FrontendController extends Controller
{
    
    public function index(Request $request)
    {        
        $slidersData = SliderModel::Where('status',1)->get();
        return view('index',compact('slidersData'));
    }

    public function contact()
    {
        return view('contact');
    }

    public function products()
    {
        $productType = ProductTypeModel::Where('status',1)->get();
        $brandData = ProductBrandModel::Where('status',1)->get();
        $industryData = ProductIndustryModel::Where('status',1)->get();
        return view('products',compact('productType','brandData','industryData'));
    }

    public function career()
    {
        return view('career');
    }

    public function privacy_policy()
    {
         $record = PagesModel::Where('type',1)->first();
         $type = 1;
          return view('pages',compact('record','type'));
    }

    public function terms_condition()
    {
        $record = PagesModel::Where('type',2)->first();
         $type = 2;
        return view('pages',compact('record','type'));
    }

    public function about()
    {
        return view('about');
    }

    public function vendor()
    {
        return view('vendor');
    }





    public function getCurrencyByCountry(Request $request)
    {
        $countryId = $request->country_id;

        $country = Country::where('iso3', $countryId)->first();

        if (!$country) {
            return response()->json(['status' => false, 'message' => 'Country not found']);
        }

        $currencyCode = $country->currency_code;

        $currency = Currency::where('code', $currencyCode)->first();

        if (!$currency) {
            return response()->json(['status' => false, 'message' => 'Currency not found']);
        }

        return response()->json([
            'status' => true,
            'currency' => $currency
        ]);
    }
    public function requestWaiting($token)
    {
        try {
            $data = Crypt::decrypt($token);
        } catch (\Exception $e) {
            return redirect('/'); // bad token -> redirect
        }

        $request_id = $data['request_id'];
        $web_time = $data['web_time'];
        $service = $data['service'];

        // Fetch request data with joins
        $data = WebRequestModel::leftJoin('service_type', 'service_type.id', '=', 'web_request.service_type')
            ->leftJoin('countries', 'countries.id', '=', 'web_request.country')
            ->select([
                'web_request.service_type as service_type_id',
                'service_type.service_type as service_type',

                'countries.name as country',
                'countries.id as countryId',

                'web_request.location',
                'web_request.day_rate_min',
                'web_request.day_rate_max',
                'web_request.night_rate_min',
                'web_request.night_rate_max',
                'web_request.availability',
                'web_request.language',
            ])
            ->where('web_request.request_id', $request_id)
            ->first();


        //dd($data);

        // --------------------- Language ---------------------
        // If language column has IDs like "1,2", fetch names
        $languageNames = [];
        if (isset($data->language)) {
            $languageIds = explode(',', $data->language); // ["1", "2"]
            $languageNames = LanguageModel::whereIn('id', $languageIds)->pluck('name')->toArray();
        }
        $languages = !empty($languageNames) ? implode(', ', $languageNames) : 'N/A';

        // --------------------- Availability ---------------------

        // Now pass to Blade
        $requestData = (object) [
            'service_type' => $data->service_type ?? 'N/A',
            'service_type_id' => $data->service_type_id,
            'countryId'      => $data->countryId ?? 'India',
            'location'     => $data->location ?? 'N/A',
            'hour_min'     => $data->day_rate_min ?? 0,
            'hour_max'     => $data->day_rate_max ?? 0,
            'night_min'    => $data->night_rate_min ?? 0,
            'night_max'    => $data->night_rate_max ?? 0,
            'availability' => $data->availability,
            'languages'    => $languages
        ];


        //dd($data);

        $countryModels = Country::get();
        $languageModels = LanguageModel::get();
        $serviceTypeModels = ServiceTypeModel::get();


        return view('request-waiting', compact('serviceTypeModels', 'countryModels', 'languageModels', 'request_id', 'web_time', 'service', 'requestData'));
    }


    public function sendRequest(Request $request)
    {

        $service = $request->input('service') == 5 ? 1 : $request->input('service');

        $languages = $request->input('languages');
        $languages_csv = !empty($languages) ? implode(',', $languages) : null;
        $countryInput = $request->input('country'); // can be name, iso2, or iso3
        $country_id = null;

        // If country is sent, find country by name OR iso2 OR iso3
        if (!empty($countryInput)) {
            $country = DB::table('countries')
                ->where('name', $countryInput)
                ->orWhere('iso2', $countryInput)
                ->orWhere('iso3', $countryInput)
                ->first();

            if ($country) {
                $country_id = $country->id;
            }
        }

        // Now $country_id contains the final ID FROM table

        $preferred_location = $request->input('preferred_location');
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');
        $hourly_min = $request->input('hourly_min');
        $hourly_max = $request->input('hourly_max');
        $nightly_min = $request->input('nightly_min');
        $nightly_max = $request->input('nightly_max');
        $availability = $request->input('availability', 3);

        $request_id = strtoupper(uniqid());

        $app_time = Settings::value('app_time');



        // $start_time = now()->timezone('Asia/Kolkata');
        // $end_time   = now()->timezone('Asia/Kolkata')->addSeconds($app_time);

        $timezone = DB::table('country_timezones as ct')
            ->join('timezones as t', 't.id', '=', 'ct.timezone_id')
            ->where('ct.country_iso3', $countryInput)
            ->where('ct.is_default', 1)
            ->value('t.timezone'); // ✅ string

        $timezone = $timezone ?? 'IND';
        $start_time = now($timezone);
        $end_time   = now($timezone)->addSeconds($app_time);

        //dd($start_time, $start_time1, $end_time, $end_time1);
        $insertArray = array(

            'request_id'    => $request_id,
            'service_type'  => $service,
            'country'       => $country_id,
            'day_rate_min'  => $hourly_min,
            'day_rate_max'  => $hourly_max,
            'night_rate_min' => $nightly_min,
            'night_rate_max' => $nightly_max,
            'availability'  => $availability,
            'language'      => $languages_csv,
            'location'      => $preferred_location,
            'latitude'      => $latitude,
            'longitude'     => $longitude,
            'start_time'    => $start_time,
            'end_time'      => $end_time,

        );

        WebRequestModel::create($insertArray);

        $km = $request->input('service') != 4 ? 5 : 0;

        $getServicesUserIds = $this->getrequestBasedServices($request_id, $km);

        if ($getServicesUserIds) {
            sendTestRequestNotification('FindFlicker', 'New-request notification from FindFlicker', $getServicesUserIds);
        }
        // $request_id = "692AA2759D1E5";

        $web_time = Settings::value('web_time');
        $encrypted = Crypt::encrypt([
            'request_id' => $request_id,
            'web_time'   => $web_time,
            'service'    => $service,
        ]);
        // return redirect()->route('request.waiting', [
        //     'request_id' => $request_id,
        //     'web_time'   => $web_time,
        //     'service'    => $service
        // ]);
        return redirect()->route('request.waiting', ['token' => $encrypted]);
        //return view('request-waiting', compact('request_id', 'web_time', 'service'));
    }

    public function getrequestBasedServices($requestId, $distance = null)
    {
        try {
            $requestModel = WebRequestModel::where('request_id', $requestId)->first();
            if (!$requestModel) {
                return [];   // return empty array
            }

            $serviceType = $requestModel->service_type;

            if ($serviceType != 4) {
                $range = $this->rangeController->getLatLngRange(
                    $requestModel->latitude,
                    $requestModel->longitude,
                    $distance
                );
            }

            $availability = $requestModel->availability;
            $languagesCsv = $requestModel->language ?? null;
            $country      = $requestModel->country;

            $hourly_min   = $requestModel->day_rate_min;
            $hourly_max   = $requestModel->day_rate_max;
            $nightly_min  = $requestModel->night_rate_min;
            $nightly_max  = $requestModel->night_rate_max;

            $languages = $languagesCsv ? explode(',', $languagesCsv) : [];
            // dd([
            //     'all_fields' => $requestModel->toArray(),
            //     'languages_value' => $requestModel->language,
            //     'language_value'  => $requestModel->language ?? null
            // ]);
            $query = DB::table('service')
                ->leftJoin('advertisement as ad', 'ad.service_id', '=', 'service.id')
                ->where('service_type', $serviceType);

            if (in_array($availability, [1, 2])) {
                $query->where('availability', $availability);
            }
            if ($country) {
                $query->where('country_id', $country);
            }
            if ($serviceType != 4) {
                $query->whereBetween('ad.latitiude', [$range['min_lat'], $range['max_lat']]);
                $query->whereBetween('ad.logitude', [$range['min_lng'], $range['max_lng']]);
            }

            if (!empty($languages)) {

                $query->where(function ($q) use ($languages) {
                    foreach ($languages as $lang) {
                        $q->orWhereRaw("FIND_IN_SET(?, language)", [$lang]);
                    }
                });
            }



            // Day rate overlap
            if ($hourly_min && $hourly_max) {
                $query->where(function ($q) use ($hourly_min, $hourly_max) {
                    $q->where('day_rate_min', '<=', $hourly_max)
                        ->where('day_rate_max', '>=', $hourly_min);
                });
            }

            // Night rate overlap
            if ($nightly_min && $nightly_max) {
                $query->where(function ($q) use ($nightly_min, $nightly_max) {
                    $q->where('night_rate_min', '<=', $nightly_max)
                        ->where('night_rate_max', '>=', $nightly_min);
                });
            }

            // Fetch services
            $services = $query->select(
                'service.id as service_id',
                'service.country_id',
                'service.user_id',
                'service.service_type',
                'service.title',
                'service.description',
                'service.photo',
                'service.day_rate_min',
                'service.day_rate_max',
                'service.night_rate_min',
                'service.night_rate_max',
                'service.availability',
                'service.language',
                'service.created_at',
                'service.updated_at',

            )
                ->groupBy('service.id')
                ->get();

            // ->pluck('user_id')
            // ->toArray();
            $app_time = Settings::value('app_time');

            // $start_time = now()->timezone('Asia/Kolkata');
            // $end_time   = now()->timezone('Asia/Kolkata')->addSeconds($app_time);
            $iso3 = Country::where('id', $requestModel->country)->value('iso3');

            // get default timezone
            $timezone = DB::table('country_timezones as ct')
                ->join('timezones as t', 't.id', '=', 'ct.timezone_id')
                ->where('ct.country_iso3', $iso3)
                ->where('ct.is_default', 1)
                ->value('t.timezone') ?? 'UTC';

            $start_time = now($timezone);
            $end_time   = now($timezone)->addSeconds($app_time);

            $createdUserIds = []; // store only created ones

            for ($i = 0; $i < count($services); $i++) {

                if ($serviceType != 4) {

                    $exists = DistanceRequest::where('requestId', $requestId)
                        ->where('service_id', $services[$i]->service_id)
                        ->where('distance', $distance)
                        ->exists();

                    if (! $exists) {

                        DistanceRequest::create([
                            'requestId'   => $requestId,
                            'distance'    => $distance,
                            'service_id'  => $services[$i]->service_id,
                            'range_km'    => json_encode($range),
                            'userIds'     => $services[$i]->user_id,
                            'start_time'  => $start_time,
                            'end_time'    => $end_time,
                        ]);

                        // store only new created userId
                        $createdUserIds[] = $services[$i]->user_id;
                    }
                } else {


                    $inserted = DistanceRequest::create([
                        'requestId'   => $requestId,
                        'distance'    => $distance,
                        'service_id'  => $services[$i]->service_id,
                        'range_km'    => null,
                        'userIds'     => $services[$i]->user_id,
                        'start_time'  => $start_time,
                        'end_time'    => $end_time,
                    ]);


                    // store only new created userId
                    $createdUserIds[] = $services[$i]->user_id;
                }
            }


            $createdUserIds = array_values(array_unique($createdUserIds));

            // remove duplicates (if any)


            // return only created user IDs
            return $createdUserIds;
        } catch (\Exception $e) {

            // log error
            Log::error("getrequestBasedServices error: " . $e->getMessage(), [
                'request_id' => $requestId,
                'distance' => $distance
            ]);

            return [];  // safe fallback
        }
    }

    public function getAcceptedrequests(Request $request)
    {
        $id = $request->query('id'); // GET parameter 'id' // get only active records
        $models = ManageRequestModel::where('request_id', $id)->where('type', 1)->get();
        if ($models->isEmpty()) {
            return response()->json([
                'data' => []
            ]);
        }

        $serviceIds = $models->pluck('service_id')->unique()->toArray();

        $services = Service::whereIn('id', $serviceIds)->get()->keyBy('id');

        $responseData = [];

        foreach ($models as $model) {

            $service = $services[$model->service_id] ?? null;
            $serviceType = ServiceTypeModel::find($service->service_type);
            $languageIds = !empty($service->language)
                ? explode(',', $service->language)
                : [];

            $languageNames = LanguageModel::whereIn('id', $languageIds)
                ->pluck('name')
                ->toArray();

            $languageText = implode(', ', $languageNames);
            $firstImage = null;
            if (!empty($service->photo)) {
                $images = explode(',', $service->photo);
                $firstImage = trim($images[0]);
            }

            $badgePath = null;

            if (isset($serviceType->id)) {
                switch ($serviceType->id) {
                    case 1:
                        $badgePath = asset('assets/image/svg/escordagency.svg');
                        break;
                    case 2:
                        $badgePath = asset('assets/image/svg/indipentant_badge.svg');
                        break;
                    case 3:
                        $badgePath = asset('assets/image/svg/message_badge.svg');
                        break;
                    default:
                        $badgePath =  asset('assets/image/svg/audio_video_call_badge.svg');  // or some default badge
                        break;
                }
            }
            $responseData[] = [
                'request_id'  => $model->request_id,
                'id'           => $service->id ?? null,
                'title'        => $service->title ?? null,
                'serviceImage' => $firstImage,
                'badge_image'  => $badgePath,
                'language'     => $languageText ?? null,
                'service_type' => $serviceType->service_type ?? null,


            ];
        }



        return response()->json([
            'data' => $responseData
        ]);
    }

    public function showVendor(Request $request, $serviceId)
    {

        $requestId = $request->input('request_id');
        $serviceModel = Service::where('id', $serviceId)->first();
        $requestModel = WebRequestModel::where('request_id', $requestId)

            ->first();
        //dd($requestModel);
        // Your logic here
        return view('vendor', compact('serviceId', 'requestId', 'serviceModel', 'requestModel'));
    }



    public function storeUserVendorView(Request $request)
    {
        $request_id = $request->request_id;
        $service_id = $request->service_id;

        // Check if already exists
        $exists = DB::table('user_view_vendor')
            ->where('request_id', $request_id)
            ->where('service_id', $service_id)
            ->exists();

        if (!$exists) {

            DB::table('user_view_vendor')->insert([
                'request_id' => $request_id,
                'service_id' => $service_id,
                'created_at' => now(),
                'updated_at' => now()
            ]);
        }

        return response()->json(['status' => 'success']);
    }
}
