<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Mail\OTP;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Models\UserLanguage;
use App\Models\UserProfile;
use App\Models\Version;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class UserController extends Controller
{
    public function get_user(Request $request, $id)
    {
        // $userid  = $request->user_id;

        $user = User::find($id)->select('name', 'email', 'phone', 'xmppid');

        return response()->json([
            'status' => 'success',
            'data' => $user,
        ]);
    }

    public function store_profile(Request $request)
    {
        $user = Auth::user();
        $languages = $request->languages;
        // check languages is array or json
        if (is_array($languages)) {
            $languages = $languages;
        } else {
            $languages = json_decode($languages, true);
        }
        //   dd($languages);

        $profile = [
            'city' => $request->city,
            'state' => $request->state,
        ];

        $user->profile()->updateOrCreate(
            ['user_id' => $user->id],
            $profile
        );

        //  dd($user);
        //delete all languages
        $user->languages()->delete();



        foreach ($languages as $language) {
            $userLanguage = new UserLanguage();
            $userLanguage->user_id = $user->id;
            $userLanguage->language_id = $language;
            $userLanguage->save();
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Profile updated successfully',
        ]);
    }


    public function update_profile(Request $request)
    {
        $user = Auth::user();
        if ($request->has('name')) {
            $user->name = $request->name;
        }

        // dd($request->all());

        // if profile image is not null, then update profile image
        if ($request->has('profile_image')) {
            // upload file
            //dd($request->file('profile_image'));
            $file = $request->file('profile_image');
            $filename = time() . '.' . $file->getClientOriginalExtension();
            $filePath = $file->storeAs('public/profile_image/', $filename);


            $user->profile_picture = $filename;
        }
        // dd($user);
        $user->save();


        // $userProfile = UserProfile::where('user_id', $user->id)->first();

        // if ($userProfile == null) {
        //     // update settings missing

        //     return response()->json([
        //         'status' => 'error',
        //         'message' => 'Profile not found. please update profile first',
        //     ]);
        // }

        // //dd($userProfile);
        // if ($request->has('service_category')) {
        //     $userProfile->service_category = $request->service_category;
        // }

        // // service_offered
        // if ($request->has('service_offered')) {
        //     $userProfile->service_offered = $request->service_offered;
        // }
        // // skill_set
        // if ($request->has('skill_set')) {

        //     $skillset = $request->skill_set;

        //     if (is_array($skillset)) {
        //         $skillset = $skillset;
        //     } else {
        //         $skillset = json_decode($skillset, true);
        //     }

        //     $userProfile->skill_set = $skillset;
        // }

        // // save
        // $userProfile->save();

        // $user->profile = $userProfile;

        return response()->json([
            'status' => 'success',
            'message' => 'Profile updated successfully',
            'data' => $user
        ]);
    }

    public function update_profile_settings(Request $request)
    {
        $profileReq = (object)$request->basic_profile;
        $user = Auth::user();
        if (isset($profileReq->name)) {
            $user->name = $profileReq->name;
        }
        // if profile image is not null, then update profile image
        if (isset($profileReq->profile_image)) {
            $user->profile_picture = $profileReq->profile_image;
        }
        $user->save();


        $userProfile = UserProfile::where('user_id', $user->id)->first();

        if ($userProfile == null) {
            // update settings missing
            return [
                'status' => 'error',
                'message' => 'Profile not found. please update profile first',
            ];
        }

        //dd($userProfile);
        if (isset($profileReq->service_category)) {
            $userProfile->service_category = $profileReq->service_category;
        }

        // service_offered
        if (isset($profileReq->service_offered)) {
            $userProfile->service_offered = $profileReq->service_offered;
        }
        // skill_set
        if (isset($profileReq->skill_set)) {

            $skillset = $profileReq->skill_set;

            // if (is_array($skillset)) {
            //     $skillset = $skillset;
            // } else {
            //     $skillset = json_decode($skillset, true);
            // }

            $userProfile->skill_set = $skillset;
        }

        // save
        $userProfile->save();

        $user->profile = $userProfile;

        return $user;
    }



    public function remove_data(Request $request)
    {
        // deleta all users 
        User::truncate();
        // delete all user languages
        UserLanguage::truncate();
        // delete all user profile
        UserProfile::truncate();

        return response()->json([
            'status' => 'success',
            'message' => 'All data removed successfully',
        ]);
    }


    public function request_terms(Request $request)
    {
        // $user = Auth::user();
        // $user->terms_accepted = 0;
        // $user->save();
        $terms = "This is a terms and conditions sample text.";

        return response()->json([
            'status' => 'success',
            'data' => $terms,
        ]);
    }


    public function accept_terms(Request $request)
    {
        // $user = Auth::user();
        // $user->terms_accepted = 1;
        // $user->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Terms and conditions accepted successfully',
        ]);
    }

    public function get_user_by_xmpp(Request $request)
    {
        // return $request->xmppid;
        $user = User::where('xmppid', $request->xmppid)->first();
        if ($user == null) {
            return response()->json([
                'status' => 'error',
                'message' => 'User not found',
            ]);
        }
        return response()->json([
            'status' => 'success',
            'data' => $user,
        ]);
    }

    //check_version
    public function check_version(Request $request)
    {
        // DB::table('users')->update(['last_login' => date('Y-m-d H:i:s')]);
        $login_status = "";
        $device_id = "";
        if($request->version != "" && $request->user_id == "")
        {
            $version = Version::orderBy('id','desc')->first();
            if($request->version == $version->version)
            {
                $status = "success";
            }else{
                $status = $version->priority.' - '.$version->version;
            }
            

           
        }elseif($request->user_id != ""){
            $version = Version::orderBy('id','desc')->first();
            if($request->version == $version->version)
            {
                $status = "success";
            }else{
                $status = $version->priority.' - '.$version->version;
            }
             //update last login
             $user = User::findOrFail($request->user_id);
             $user->last_login = date('Y-m-d H:i:s');
             $user->save();
             $login_status = $user->account_status;
             $device_id = $user->device_id;
        }else{
            $status = 'Required fields are missing';
        }

        return response()->json(['version_status' => $status,'login_status' => $login_status,'device_id' => $device_id]);

    }

    //check login status
    public function login_status(Request $request,$id)
    {
        if($id == ""){
            return response(['status' => 'failed','message' => 'User id is required']);
        }else{
            $user = User::findOrFail($id);
            if($user->account_status == "login"){
                return response(['status' => 'success','message' => 'User is logged in']);
            }else{
                return response(['status' => 'failed','message' => 'User is not logged in']);
            }
        }
    }

    /* Send otp to verify email via email */
    public function request_for_mail_verification(Request $request){
        if(Auth::check()){
            $user = Auth::user();
            $otp = rand(100000, 999999);
            //set cache
            Cache::put("otp_$user->email", $otp, now()->addMinutes(10));
            try {
                Mail::to($user->email)->send(new OTP($otp));
                return response(['status' => 'success','message' => 'OTP sent successfully','otp' => $otp]);
            } catch (\Throwable $e) {
                dd($e);
                return response(['status' => 'failed','message' => 'Failed to send OTP','error' => $e]);
            }
            
        }else{
            return response(['status' => 'failed','message' => 'User is not logged in']);
        }
    }
    /* Verify otp */
    public function verify_mail(Request $request){
        if(Auth::check()){
           if($request->has('otp') && $request->otp != ""){
               $user = Auth::user();
               $cache_otp = Cache::get("otp_$user->email");
               if($cache_otp == $request->otp){
                   $user->email_verified_at = now();
                   $user->save();
                   return response(['status' => 'success','message' => 'Email verified successfully','user' => $user]);
               }else{
                   return response(['status' => 'failed','message' => 'Invalid OTP']);
               }
           }else{
               return response(['status' => 'failed','message' => 'OTP is required']);
           }
        }else{
            return response(['status' => 'failed','message' => 'User is not logged in']);
        }
    }
}
