<?php
namespace App\Http\Controllers\api\v1;
use App\Http\Controllers\Controller;
use App\Models\AdReport;
use App\Models\User;
use App\Models\SupportTicket;
use App\Models\UserDetail;
use App\Models\UserDisease;
use App\Models\UserDiseaseVariant;
use App\Models\UserChronicDisease;
use App\Models\UserChronicDiseaseVariant;
use App\Models\UserImage;
use App\Models\UserPreference;
use Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class UsersController extends Controller
{
    public function __construct(Request $request)
    {
        if (isset($request->lang)) {
            \App::setLocale($request->lang);
        }
        $this->lang = \App::getLocale();
    }
    private function validateAccesToken($access_token)
    {
        $user = User::where(['user_access_token' => $access_token])->first();
        if (!$user) {
            http_response_code(401);
            echo json_encode([
                'status' => (string) 0,
                'message' => 'Invalid access token',
                'oData' => (object) [],
                'errors' => (object) [],
            ]);
            exit();
        }
        if ($user->status != 1) {
            http_response_code(401);
            echo json_encode([
                'status' => (string) 0,
                'message' => 'User is not active',
                'oData' => (object) [],
                'errors' => (object) [],
            ]);
            exit();
        }
        return $user;
    }
    public function my_profile(Request $request)
    {
        $status = (string) 0;
        $message = '';
        $o_data = [];
        $errors = [];
        $validator = Validator::make($request->all(), [
            'access_token' => 'required',
        ]);
        if ($validator->fails()) {
            $status = (string) 0;
            $message = 'Validation error occured';
            $errors = $validator->messages();
        } else {
            $user = User::where(['user_access_token' => $request->access_token])->first();
            if (!$user) {
                return response()->json(
                    [
                        'status' => '0',
                        'message' => 'User Session Expired',
                        'oData' => [],
                        'errors' => (object) [],
                    ],
                    401,
                );
            }
            $user_id = $user->id;
            $userData = User::with(['children', 'preference','preference.city_emirate', 'nationality', 'emirate', 'country', 'images', 'details.sect', 'details.education', 'details.profession', 'details.maritalStatus', 'details.dressCode', 'plan', 'sports.sport', 'activities.activity', 'known_languages.language', 'notification_settings', 'geneticDiseases.geneticDisease', 'geneticDiseases.geneticDiseaseVariant.geneticDiseaseVariant', 'chronicDiseases.chronicDisease', 'chronicDiseases.chronicDiseaseVariant.chronicDiseaseVariant'])
                ->find($user->id)
                ->toArray();
            if ($userData) {
                convertNullRelationsToObjects($userData);
                $o_data = convert_all_elements_to_string($userData, true);
                $status = (string) 1;
                $message = 'data fetched Successfully';
            } else {
                $message = 'no data to show';
            }
        }
        return response()->json(['status' => $status, 'error' => $errors, 'message' => $message, 'user' => $o_data], 200);
    }

    public function get_user_profile(Request $request)
    {
        $status = '0';
        $message = '';
        $o_data = [];
        $errors = [];

        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
            'access_token' => 'required'
        ], [
            'user_id.required' => 'User ID is required',
            'access_token.required' => trans('validation.access_token_required')
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'error' => $validator->messages(),
                'message' => 'Validation error occurred',
                'oData' => $o_data
            ], 200);
        }

        $currentUser = $this->validateAccesToken($request->access_token);
        if (!$currentUser) {
            return response()->json([
                'status' => '0',
                'message' => trans('validation.invalid_user'),
                'error' => (object) [],
            ], 401);
        }

        $profileUser = User::with([
            'children',
            'preference',
            'nationality',
            'emirate',
            'country',
            'images',
            'details.sect',
            'details.education',
            'details.profession',
            'details.maritalStatus',
            'details.dressCode',
            'plan',
            'sports.sport',
            'activities.activity',
            'known_languages.language',
            'notification_settings',
            'geneticDiseases.geneticDisease',
            'geneticDiseases.geneticDiseaseVariant.geneticDiseaseVariant'
        ])->find($request->user_id);

        if ($profileUser) {
            // Use your existing helper to process connection/block/report/request statuses
            $processedUsers = processConnectionStatus($currentUser, collect([$profileUser]), true);

            if (count($processedUsers) > 0) {
                // The helper returns array of users; get the first one (only one here)
                $userArray = $processedUsers[0];
                $o_data = $userArray;
            }

            $status = '1';
            $message = 'Data fetched successfully';
        } else {
            $message = 'No data to show';
        }

        return response()->json([
            'status' => $status,
            'error' => $errors,
            'message' => $message,
            'oData' => $o_data
        ], 200);
    }


    public function get_minimal_user_profile(Request $request)
    {
        $status = (string) 0;
        $message = '';
        $o_data = [];
        $errors = [];

        $validator = Validator::make($request->all(), [
            'user_id' => 'required|exists:users,id',
            'access_token' => 'required'
        ], [
            'user_id.required' => 'User ID is required',
            'access_token.required' => trans('validation.access_token_required')
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'error' => $validator->messages(),
                'message' => 'Validation error occurred',
                'oData' => $o_data
            ], 200);
        }

        $currentUser = $this->validateAccesToken($request->access_token);
        if (!$currentUser) {
            return response()->json([
                'status' => '0',
                'message' => trans('validation.invalid_user'),
                'error' => (object) [],
            ], 401);
        }

        $profileUser = User::select(['id', 'name', 'profile_image'])->where('id', $request->user_id)->first();

        if ($profileUser) {
            // Check connection status and get hide_image
            $connection = DB::table('user_connections')
                ->where('user_id', $currentUser->id)
                ->where('connected_user_id', $profileUser->id)
                ->first();

            $profileUser->is_connected = $connection ? 1 : 0;
            $profileUser->hide_image = $connection ? (int) $connection->hide_image : 0;

            // Check if blocked
            $profileUser->is_blocked = DB::table('user_blocks')
                ->where('user_id', $currentUser->id)
                ->where('blocked_user_id', $profileUser->id)
                ->exists() ? 1 : 0;

            // Check if reported
            $profileUser->is_reported = DB::table('user_reports')
                ->where('reporter_id', $currentUser->id)
                ->where('reported_user_id', $profileUser->id)
                ->exists() ? 1 : 0;

            // Check request direction
            $profileUser->is_sent = DB::table('user_requests')
                ->where('sender_id', $currentUser->id)
                ->where('receiver_id', $profileUser->id)
                ->exists() ? 1 : 0;

            $profileUser->is_received = DB::table('user_requests')
                ->where('sender_id', $profileUser->id)
                ->where('receiver_id', $currentUser->id)
                ->exists() ? 1 : 0;

            $userArray = $profileUser->toArray();
            convertNullRelationsToObjects($userArray);
            $o_data = convert_all_elements_to_string($userArray, true);

            $status = (string) 1;
            $message = 'Data fetched successfully';
        } else {
            $message = 'No data to show';
        }

        return response()->json([
            'status' => $status,
            'error' => $errors,
            'message' => $message,
            'oData' => $o_data
        ], 200);
    }
    public function update_user_profile(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];
        $validator = Validator::make($request->all(), [
            'access_token' => 'required',
            'first_name' => 'nullable|string',
            'last_name' => 'nullable|string',
            'whatsapp_number' => 'nullable|string',
            'country_id' => 'nullable|exists:countries,id',
            'emirates_id' => 'nullable|exists:emirates,id',
            'nationality_id' => 'nullable|exists:nationalities,id',
            'profile_image' => 'nullable|image|mimes:jpeg,png,jpg',
            'user_image' => 'nullable|image|mimes:jpeg,png,jpg', // optional alias
            'sect_id' => 'nullable|exists:sects,id',
            'education_id' => 'nullable|exists:educations,id',
            'profession_id' => 'nullable|exists:professions,id',
            'height_cm' => 'nullable|numeric',
            'height_ft' => 'nullable|numeric',
            'weight_kg' => 'nullable|numeric',
            'weight_lbs' => 'nullable|numeric',
            'languages_id' => 'nullable|array',
            'marital_status_id' => 'nullable|exists:marital_statuses,id',
            'kids' => 'nullable|array',
            'kids.*.count' => 'nullable|integer',
            'kids.*.age' => 'nullable|string',
            'wives' => 'nullable|integer',
            'children' => 'nullable|integer',
            'religious_practice' => 'nullable|string',
            'dress_code_id' => 'nullable|exists:dress_codes,id',
            'smoking' => 'nullable|string',
            'genetic_disease_id' => 'nullable|array',
            'genetic_disease_ids' => 'nullable|array',
            'genetic_disease_ids.*.genetic_disease_id' => 'required',
            'genetic_disease_ids.*.genetic_disease_variant_id' => 'nullable|array',
            'genetic_disease' => 'nullable|string',
            'about' => 'nullable|string',
            'sports_id' => 'nullable|array',
            'activities_id' => 'nullable|array',
            'images' => 'nullable|array',
            'images.*' => 'nullable|image|mimes:jpeg,png,jpg',
            'is_image_blur' => 'nullable|in:0,1',
            'email' => 'nullable|email',
            'phone' => 'nullable|string',
            'dial_code' => 'nullable|string',
            'profile_setup_completed' => 'nullable',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'message' => 'Validation error occurred',
                'errors' => $validator->errors(),
                'oData' => $o_data,
            ]);
        }
        $user = User::where('user_access_token', $request->access_token)->first();
        if (!$user) {
            return response()->json(
                [
                    'status' => '0',
                    'message' => 'User session expired',
                    'errors' => (object) [],
                    'oData' => [],
                ],
                401,
            );
        }
        // Update profile basics
        if ($request->has('first_name')) {
            $user->first_name = $request->first_name;
        }
        if ($request->has('not_show_over_aged')) {
            $user->not_show_over_aged = $request->not_show_over_aged;
        }
        if ($request->has('hide_on_search')) {
            $user->hide_on_search = $request->hide_on_search;
        }

        if ($request->who_can_contact) {
            $user->who_can_contact = $request->who_can_contact;
        }

        if ($request->has('last_name')) {
            $user->last_name = $request->last_name;
        }
        // Rebuild name only if either first or last name was present
        if ($request->has('first_name') || $request->has('last_name')) {
            $user->name = trim(($request->has('first_name') ? $request->first_name : $user->first_name) . ' ' . ($request->has('last_name') ? $request->last_name : $user->last_name));
        }
        if ($request->has('whatsapp_number')) {
            $user->whatsapp_number = $request->whatsapp_number;
        }
        if ($request->has('is_image_blur')) {
            $user->is_image_blur = $request->is_image_blur;
        }
        if ($request->has('country_id')) {
            $user->country_id = $request->country_id;
        }
        if ($request->has('emirates_id')) {
            $user->emirates_id = $request->emirates_id;
        }
        if ($request->has('nationality_id')) {
            $user->nationality_id = $request->nationality_id;
        }
        if ($request->has('profile_setup_completed')) {
            $user->profile_setup_completed = $request->profile_setup_completed;
        }
        if ($request->has('skin_color')) {
            $user->skin_color = $request->skin_color;
        }
        if ($request->is_mother_uae_national == 1) {
            $user->is_mother_uae_national = $request->is_mother_uae_national;
            $user->is_pending_from_admin = 1;
        }

        // Handle email/phone update with OTP
        if ($request->filled('phone') && $user->phone !== $request->phone) {
            $user->temp_dial_code = $request->dial_code;
            $user->temp_phone = $request->phone;
            $user->user_phone_otp = (string) generate_otp();
            $user->phone_verified = 0;
        }
        if ($request->filled('email') && $user->email !== $request->email) {
            $user->temp_email = $request->email;
            $user->user_email_otp = (string) generate_otp();
            $user->email_verified = 0;
        }
        $user->save();
        // Upload profile image
        if ($request->file('profile_image')) {
            $response = image_upload($request, config('global.user_image_upload_dir'), 'profile_image');
            if ($response['status']) {
                $user->profile_image = $response['link'];
                $user->save();
            }
        }

        if ($request->file('birth_certificate')) {
            $response = image_upload($request, config('global.user_image_upload_dir'), 'birth_certificate');
            if ($response['status']) {
                $user->birth_certificate = $response['link'];
                $user->save();
            }
        }
        if ($request->file('mothers_emirates_id')) {
            $response = image_upload($request, config('global.user_image_upload_dir'), 'mothers_emirates_id');
            if ($response['status']) {
                $user->mothers_emirates_id = $response['link'];
                $user->save();
            }
        }


        // Upload additional images
        if ($request->has('images') && is_array($request->images)) {
            $disk = config('global.upload_bucket');
            $imagePath = config('global.user_image_upload_dir');
            foreach ($request->file('images') as $file) {
                $fileName = time() . uniqid() . '.' . $file->getClientOriginalExtension();
                $file->storeAs($imagePath, $fileName, $disk);
                UserImage::create([
                    'user_id' => $user->id,
                    'url' => $fileName,
                ]);
            }
        }
        // Update user detail
        $detailFields = ['sect_id', 'education_id', 'profession_id', 'height_cm', 'height_ft', 'weight_kg', 'weight_lbs', 'marital_status_id', 'wives', 'children', 'religious_practice', 'dress_code_id', 'smoking', 'genetic_disease', 'about','chronic_disease'];
        $detailData = [];
        foreach ($detailFields as $field) {
            if ($request->has($field)) {
                if ($request->input($field) == 'all') {
                    $detailData[$field] = null;
                } else {
                    $detailData[$field] = $request->input($field);
                }
            }
        }
        if (!empty($detailData)) {
            UserDetail::where(['user_id' => $user->id])->update($detailData);
        }
        // Sync many-to-many relations
        if ($request->has('languages_id')) {
            $user->syncknown_languages()->sync($request->input('languages_id'));
        }
        if ($request->has('genetic_disease') && $request->genetic_disease == 0) {
            UserDisease::where('user_id', $user->id)->delete();
            UserDiseaseVariant::where('user_id', $user->id)->delete();
        }
        if ($request->genetic_disease == 1 && $request->has('genetic_disease_ids') && is_array($request->genetic_disease_ids)) {
            UserDisease::where('user_id', $user->id)->delete();
            UserDiseaseVariant::where('user_id', $user->id)->delete();
            foreach ($request->genetic_disease_ids as $dis) {
                $diseaseRecord = UserDisease::create([
                    'user_id' => $user->id,
                    'genetic_disease_id' => $dis['genetic_disease_id'] ?? null,
                ]);

                if (isset($dis['genetic_disease_variant_id']) && is_array($dis['genetic_disease_variant_id'])) {
                    foreach ($dis['genetic_disease_variant_id'] as $variantId) {
                        UserDiseaseVariant::create([
                            'user_id' => $user->id,
                            'genetic_disease_id' => $diseaseRecord->id,
                            'genetic_disease_variant_id' => $variantId,
                        ]);
                    }
                }
            }
        }

        if ($request->has('chronic_disease') && $request->chronic_disease == 0) {
            UserChronicDisease::where('user_id', $user->id)->delete();
            UserChronicDiseaseVariant::where('user_id', $user->id)->delete();
        }
        if ($request->chronic_disease == 1 && $request->has('chronic_disease_ids') && is_array($request->chronic_disease_ids)) {
            UserChronicDisease::where('user_id', $user->id)->delete();
            UserChronicDiseaseVariant::where('user_id', $user->id)->delete();
            foreach ($request->chronic_disease_ids as $dis) {
                $diseaseRecord = UserChronicDisease::create([
                    'user_id' => $user->id,
                    'chronic_disease_id' => $dis['chronic_disease_id'] ?? null,
                ]);

                if (isset($dis['chronic_disease_variant_id']) && is_array($dis['chronic_disease_variant_id'])) {
                    foreach ($dis['chronic_disease_variant_id'] as $variantId) {
                        UserChronicDiseaseVariant::create([
                            'user_id' => $user->id,
                            'chronic_disease_id' => $diseaseRecord->id,
                            'chronic_disease_variant_id' => $variantId,
                        ]);
                    }
                }
            }
        }
        if ($request->has('sports_id')) {
            $user->syncsports()->sync($request->input('sports_id'));
        }
        if ($request->has('activities_id')) {
            $user->syncactivities()->sync($request->input('activities_id'));
        }
        // Sync kids
        if ($request->has('kids')) {
            $kids = $request->input('kids');
            $ids = collect($kids)->pluck('id')->filter()->all();
            $user->children()->whereNotIn('id', $ids)->delete();
            foreach ($kids as $kid) {
                if (!empty($kid['id'])) {
                    $user
                        ->children()
                        ->where('id', $kid['id'])
                        ->update([
                            'kid_count' => $kid['count'] ?? null,
                            'age' => $kid['age'] ?? null,
                        ]);
                } else {
                    $user->children()->create([
                        'kid_count' => $kid['count'] ?? null,
                        'age' => $kid['age'] ?? null,
                    ]);
                }
            }
        }
        $userData = User::with(['children', 'preference', 'nationality', 'emirate', 'country', 'images', 'details.sect', 'details.education', 'details.profession', 'details.maritalStatus', 'details.dressCode', 'plan', 'sports.sport', 'activities.activity', 'known_languages.language', 'notification_settings', 'geneticDiseases.geneticDisease', 'geneticDiseases.geneticDiseaseVariant.geneticDiseaseVariant'])
            ->find($user->id)
            ->toArray();

        convertNullRelationsToObjects($userData);
        $o_data['user'] = convert_all_elements_to_string($userData, true);
        $status = '1';
        $message = $request->has('profile_completed') ? trans('validation.profile_completed_message') : trans('validation.profile_update_message');
        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => $o_data,
        ]);
    }

    public function update_user_device_token(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];

        $validator = Validator::make($request->all(), [
            'access_token' => 'required',
            'fcm_token' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'message' => 'Validation error occurred',
                'errors' => $validator->errors(),
                'oData' => $o_data,
            ]);
        }

        $user = User::where('user_access_token', $request->access_token)->first();

        if (!$user) {
            return response()->json([
                'status' => '0',
                'message' => 'User session expired',
                'errors' => (object) [],
                'oData' => [],
            ], 401);
        }

        // Update FCM token
        if ($request->filled('fcm_token') && $user->user_device_token !== $request->fcm_token) {
            $user->user_device_token = $request->fcm_token;
        }

        $user->save();

        $o_data['user'] = convert_all_elements_to_string($user, true);
        $status = '1';
        $message = $request->has('profile_completed')
            ? trans('validation.profile_completed_message')
            : trans('validation.profile_update_message');

        return response()->json([
            'status' => $status,
            'message' => $message,
            'errors' => (object) $errors,
            'oData' => $o_data,
        ]);
    }

    public function validate_otp_phone_email_update(Request $request)
    {
        $status = (string) 0;
        $message = '';
        $o_data = [];
        $errors = [];
        $rule = [
            'access_token' => 'required',
            'type' => 'required|in:1,2',
            'otp' => 'required',
        ];
        if ($request->type == 1) {
            $rule['dial_code'] = 'required';
            $rule['phone'] = 'required';
        } else {
            $rule['email'] = 'required';
        }
        $validator = Validator::make($request->all(), $rule);
        if ($validator->fails()) {
            $status = (string) 0;
            $message = 'Validation error occured';
            $errors = $validator->messages();
        } else {
            $user = $this->validateAccesToken($request->access_token);
            $sent_opt = $user->user_phone_otp;
            if ($request->type == 2) {
                $sent_opt = $user->user_email_otp;
            }
            if ($sent_opt == $request->otp) {
                if ($request->type == 1) {
                    $user->dial_code = $request->dial_code;
                    $user->phone = $request->phone;
                    $user->user_phone_otp = '';
                    $user->phone_verified = 1;
                    $user->temp_dial_code = '';
                    $user->temp_phone = '';
                    $user->save();
                    $status = (string) 1;
                    $message = 'Phone number updated successfully';
                } else {
                    $user->email = $request->email;
                    $user->user_email_otp = '';
                    $user->email_verified = 1;
                    $user->temp_email = '';
                    $user->save();
                    $status = (string) 1;
                    $message = 'email id updated successfully';
                }
                // if (config('global.server_mode') == 'local') {
                //     \Artisan::call('update:firebase_node ' . $user->id);
                // } else {
                //     exec("php " . base_path() . "/artisan update:firebase_node " . $user->id . " > /dev/null 2>&1 & ");
                // }
            } else {
                $message = 'Invalid otp sent';
            }
        }
        return response()->json(['status' => $status, 'message' => $message, 'errors' => $errors, 'oData' => $o_data]);
    }
    public function change_password(Request $request)
    {
        $status = (string) 0;
        $message = '';
        $o_data = [];
        $errors = [];
        $validator = Validator::make($request->all(), [
            'access_token' => 'required',
            'old_password' => 'required|min:9',
            'new_password' => 'required|min:9',
        ]);
        if ($validator->fails()) {
            $status = (string) 0;
            $message = 'Validation error occured';
            $errors = $validator->messages();
        } else {
            $user = User::where(['user_access_token' => $request->access_token])->first();
            if (!$user) {
                return response()->json(
                    [
                        'status' => '0',
                        'message' => 'User Session Expired',
                        'oData' => [],
                        'errors' => (object) [],
                    ],
                    401,
                );
            }
            $user_id = $user->id;
            $user = User::find($user_id);
            if (Hash::check($request->old_password, $user->password)) {
                $user->password = bcrypt($request->new_password);
                $user->save();
                $status = (string) 1;
                $message = 'Password Updated successfully';
            } else {
                $message = 'Old password not match';
            }
        }
        return response()->json(['status' => $status, 'message' => $message, 'errors' => $errors, 'oData' => $o_data]);
    }
    public function create_support_ticket(Request $request)
    {
        $status = (string) 0;
        $message = '';
        $o_data = [];
        $errors = [];
        $validator = Validator::make($request->all(), [
            'access_token' => 'required',
            'subject' => 'required',
            'description' => 'required',
        ]);
        if ($validator->fails()) {
            $status = (string) 0;
            $message = 'Validation error occured';
            $errors = $validator->messages();
        } else {
            $user = $this->validateAccesToken($request->access_token);
            $ticket = SupportTicket::create([
                'user_id' => $user->id,
                'subject' => $request->subject,
                'description' => $request->description,
                'status' => 1,
            ]);
            $ticket->ticket_number = 'SP-' . str_pad($ticket->id, 6, '0', STR_PAD_LEFT);
            $ticket->save();
            $o_data['ticket'] = $ticket;
            $status = (string) 1;
            $message = trans('message.support_ticket_created');
            $o_data = convert_all_elements_to_string($o_data);
        }
        return response()->json(['status' => $status, 'message' => $message, 'errors' => $errors, 'oData' => $o_data]);
    }
    public function get_my_support_tickets(Request $request)
    {
        $status = (string) 0;
        $message = 'Support tickets fetched successfully';
        $o_data = [];
        $errors = [];
        $user = $this->validateAccesToken($request->access_token);
        $validator = Validator::make($request->all(), [
            'access_token' => 'required',
        ]);
        if ($validator->fails()) {
            $status = (string) 0;
            $message = 'Validation error occured';
            $errors = $validator->messages();
        } else {
            $tickets = SupportTicket::where('user_id', $user->id)->get();
            $o_data['tickets'] = $tickets;
            $o_data['tickets'] = convert_all_elements_to_string($o_data['tickets']);
            $status = (string) 1;
        }
        return response()->json(['status' => $status, 'message' => $message, 'errors' => (object) $errors, 'oData' => $o_data], 200);
    }
    public function deleteUserImage(Request $request)
    {
        $status = '1';
        $message = trans('validation.user_image_deleted');
        $o_data = [];
        $errors = [];
        $rules = [
            'access_token' => 'required',
            'image_id' => 'required',
        ];
        $messages = [
            'access_token.required' => trans('validation.access_token_required'),
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $message = $validator->errors()->first();
            $errors = $validator->messages();
            return response()->json(
                [
                    'status' => '0',
                    'message' => $message,
                    'error' => (object) $errors,
                ],
                200,
            );
        }
        $user = $this->validateAccesToken($request->access_token);
        $picture = UserImage::where(['id' => $request->image_id, 'user_id' => $user->id])->first();
        if (!$picture) {
            $status = '0';
            $message = trans('validation.user_image_not_found_for_this_user');
            return response()->json(['status' => $status, 'error' => $errors, 'message' => $message, 'oData' => $o_data], 200);
        }
        $picture->delete();
        return response()->json(['status' => $status, 'error' => $errors, 'message' => $message, 'oData' => $o_data], 200);
    }
    public function update_notification_setting(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];
        $validator = Validator::make($request->all(), [
            'settings' => 'required|array',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'message' => 'Validation error occurred',
                'errors' => $validator->errors(),
                'oData' => $o_data,
            ]);
        }
        $user = $this->validateAccesToken($request->access_token);
        if (empty($user)) {
            $message = trans('validation.invalid_user');
            return response()->json(
                [
                    'status' => '0',
                    'message' => $message,
                    'error' => (object) [],
                ],
                401,
            );
        }

        foreach ($request->settings as $setting) {
            $user->notification_settings()->updateOrCreate(['slug' => $setting['slug']], ['value' => $setting['value']]);
        }

        $user = User::with(['children', 'preference', 'nationality', 'emirate', 'country', 'images', 'details.sect', 'details.education', 'details.profession', 'details.maritalStatus', 'details.dressCode', 'plan', 'sports.sport', 'activities.activity', 'known_languages.language', 'notification_settings', 'geneticDiseases.geneticDisease', 'geneticDiseases.geneticDiseaseVariant.geneticDiseaseVariant'])
            ->find($user->id)
            ->toArray();
        convertNullRelationsToObjects($user);
        $o_data['user'] = convert_all_elements_to_string($user, true);
        return response()->json(
            [
                'oData' => $o_data,
                'status' => '1',
                'message' => trans('validation.notification_setting_updated_message'),
            ],
            200,
        );
    }
    public function get_user_preference(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];
        $user = $this->validateAccesToken($request->access_token);
        if (empty($user)) {
            $message = trans('validation.invalid_user');
            return response()->json(
                [
                    'status' => '0',
                    'message' => $message,
                    'error' => (object) [],
                ],
                401,
            );
        }
        $user = User::with(['preference.sect', 'preference.education', 'preference.profession', 'dressCodes.dressCode', 'maritalStatuses.maritalStatus', 'sects.sect', 'professions.profession', 'educations.education', 'preference.city_emirate'])->where('id', $user->id)->first()->toArray();
        convertNullRelationsToObjects($user);
        $o_data['user'] = convert_all_elements_to_string($user, true);
        return response()->json(
            [
                'oData' => $o_data,
                'status' => '1',
                'message' => trans('validation.preference_fetched'),
            ],
            200,
        );
    }
    public function update_user_preference(Request $request)
    {
        $status = '0';
        $message = '';
        $errors = [];
        $o_data = [];
        $validator = Validator::make($request->all(), [
            'sect_id' => 'nullable|array',
            'education_id' => 'nullable|array',
            'profession_id' => 'nullable|array',
            'from_height_cm' => 'nullable|string',
            'to_height_cm' => 'nullable|string',
            'from_height_ft' => 'nullable|string',
            'to_height_ft' => 'nullable|string',
            'from_weight_kg' => 'nullable|string',
            'to_weight_kg' => 'nullable|string',
            'from_weight_lbs' => 'nullable|string',
            'to_weight_lbs' => 'nullable|string',
            'religion_practice' => 'nullable|string',
            'dress_code_id' => 'nullable|array',
            'smoking' => 'nullable|string',
            'marital_status_id' => 'nullable|array',
            'height_all' => 'nullable',
            'weight_all' => 'nullable',
            'preference_setup_completed' => 'nullable',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => $status,
                'message' => 'Validation error occurred',
                'errors' => $validator->errors(),
                'oData' => $o_data,
            ]);
        }
        $user = $this->validateAccesToken($request->access_token);
        if (empty($user)) {
            $message = trans('validation.invalid_user');
            return response()->json(
                [
                    'status' => '0',
                    'message' => $message,
                    'error' => (object) [],
                ],
                401,
            );
        }
        // Fields to update
        $detailFields = ['from_height_cm', 'to_height_cm', 'from_height_ft', 'to_height_ft', 'from_weight_kg', 'to_weight_kg', 'from_weight_lbs', 'to_weight_lbs', 'religion_practice', 'smoking', 'height_all', 'weight_all', 'city_emirate_id'];
        $detailData = [];
        foreach ($detailFields as $field) {
            if ($request->has($field)) {

                if ($request->input($field) == 'all') {
                    $detailData[$field] = null;
                } else {
                    $detailData[$field] = $request->input($field);
                }


            }
        }
        if ($request->has('height_all') && $request->input('height_all')) {
            // If user says "all heights," clear height ranges
            $detailData['from_height_cm'] = null;
            $detailData['to_height_cm'] = null;
            $detailData['from_height_ft'] = null;
            $detailData['to_height_ft'] = null;
        }
        if ($request->has('weight_all') && $request->input('weight_all')) {
            // If user says "all weights," clear weight ranges
            $detailData['from_weight_kg'] = null;
            $detailData['to_weight_kg'] = null;
            $detailData['from_weight_lbs'] = null;
            $detailData['to_weight_lbs'] = null;
        }
        if (!empty($detailData)) {
            UserPreference::updateOrCreate(['user_id' => $user->id], $detailData);
        }

        if ($request->has('sect_id')) {
            $user->syncSect()->sync($request->input('sect_id'));
        }

        if ($request->has('education_id')) {
            $user->syncEducation()->sync($request->input('education_id'));
        }

        if ($request->has('profession_id')) {
            $user->syncProfession()->sync($request->input('profession_id'));
        }

        if ($request->has('dress_code_id')) {
            $user->syncDressCodes()->sync($request->input('dress_code_id'));
        }

        if ($request->has('marital_status_id')) {
            $user->syncMaritalStatuses()->sync($request->input('marital_status_id'));
        }

        if ($request->has('preference_setup_completed')) {
            $user->preference_setup_completed = $request->preference_setup_completed;
            $user->save();
        }

        if (config('global.server_mode') == 'local') {
            \Artisan::call("matchmaking:process --userId=" . $user->id);
        } else {
            exec("php " . base_path() . "/artisan matchmaking:process --userId=" . $user->id . " > /dev/null 2>&1 & ");
        }
        $user = User::with(['preference.sect', 'preference.education', 'preference.profession', 'dressCodes.dressCode', 'maritalStatuses.maritalStatus', 'sects.sect', 'professions.profession', 'educations.education'])
            ->find($user->id)
            ->toArray();
        convertNullRelationsToObjects($user);
        $o_data['user'] = $user;
        return response()->json(
            [
                'oData' => convert_all_elements_to_string($o_data, true),
                'status' => '1',
                'message' => trans('validation.preference_updated_message'),
            ],
            200,
        );
    }

}
