<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Models\CmsPages;
use App\Models\CmsPagesTranslation;
use App\Models\DeliveryAddresses;
use App\Models\DeliveryAreas;
use App\Models\Languages;
use App\Models\NonWorkingDays;
use App\Models\Partners;
use App\Models\PartnersTranslation;
use App\Models\Timeslots;
use App\Models\TimeslotsTranslation;
use App\Models\User;
use App\Models\UserAuthLogin;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;

class UserAPIController extends Controller
{
    private $language;

    public function __construct(Request $request)
    {
        // parent::__construct();
        $this->request = $request;
        $this->language = $request->header('lang-code') && $request->header('lang-code') != '' ? $request->header('lang-code') : 'en';
    }

    public function doLogin(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required',
        ]);
        $user = User::where('phone', $request->input('phone'))->first();
        $otp = 1234; //rand(1000, 9999);
        if ($user) {
            $postUpdate = [
                'is_verified' => 0,
                'otp' => $otp,
            ];
            User::where('id', $user->id)->update($postUpdate);
            $response = [
                'id' => $user->id,
                'phone' => $user->phone,
                'otp' => $otp,
                'is_verified' => 0,
            ];
            //\Helpers::sendSms('Your One time Password is ' .$otp,$request->input('phone'));
            return $this->sendResponse($response, 'OTP send successfully.');
        } else {
            $postUpdate = [
                'phone' => $request->input('phone'),
                'is_verified' => 0,
                'otp' => $otp,
                'password' => Hash::make('123456'),
                'created_at' => date('y-m-d H:i:s'),
            ];
            $id = User::insertGetId($postUpdate);
            $response = [
                'id' => $id,
                'phone' => $request->input('phone'),
                'otp' => $otp,
                'is_verified' => 0,
            ];
            //\Helpers::sendSms('Your One time Password is ' .$otp,$request->input('phone'));
            return $this->sendResponse($response, 'OTP send successfully.');
        }
    }

    public function doVerifyOtp(Request $request)
    {
        $this->validate($request, [
            'device_token' => 'required',
            'device_type' => 'required',
            'phone' => 'required',
            'otp' => 'required',
        ]);
        $user = User::where('phone', $request->input('phone'))->where('otp', $request->input('otp'))->first();
        if ($user) {
            $postUpdate = [
                'is_verified' => 1,
            ];
            User::where('id', $user->id)->update($postUpdate);

            $postUpdate = [
                'user_id' => $user->id,
                'api_token' => \Helpers::generateApiToken(),
                'device_token' => $request->input('device_token'),
                'device_type' => $request->input('device_type'),
                'created_at' => date('y-m-d H:i:s'),
            ];
            UserAuthLogin::insert($postUpdate);

            return $this->sendResponse($postUpdate, 'User retrieved successfully.');
        } else {
            return $this->sendError('User not found', 401);
        }
    }

    public function doResndOtp(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required',
        ]);
        $user = User::where('phone', $request->input('phone'))->first();
        if ($user) {
            $response = [
                'id' => $user->id,
                'phone' => $user->phone,
                'is_verified' => 0,
            ];
            //\Helpers::sendSms('Your One time Password is ' .$user->otp,$request->input('phone'));
            return $this->sendResponse($response, 'OTP send successfully.');
        } else {
            return $this->sendError('User not found', 401);
        }
    }

    public function doDriverLogin(Request $request)
    {

        $rules = [
            'username' => 'required',
            'password' => 'required',
        ];

        $request->validate($rules);

        if (auth()->attempt(['phone' => $request->input('username'), 'password' => $request->input('password')])) {
            $user = auth()->user();
            if ($user->status == 1) {
                $postUpdate = [
                    'user_id' => $user->id,
                    'api_token' => \Helpers::generateApiToken(),
                    'created_at' => date('y-m-d H:i:s'),
                ];
                UserAuthLogin::insert($postUpdate);
                $response = ['user' => $user->id, 'token' => \Helpers::generateApiToken()];

                return $this->sendResponse($postUpdate, 'Driver retrieved successfully');

            } else {
                return $this->sendError('Driver Is not active');
            }
        } else {
            return $this->sendError('Driver valid details');
        }
    }

     public function doCustSign(Request $request)
     {
        $phone  = $request->input('phone');
        $name  = $request->input('name');
        $email  = $request->input('email');
        $password  = md5($request->input('password'));
        $emirates  = $request->input('emirates');
        $area = $request->input('area');
        $flat_no = $request->input('flat_no');
        $no_of_bottles = $request->input('no_of_bottles');
        $building = $request->input('building');
        if($phone != null && $name != null && $email != null && $password != null && $emirates != null && $area != null && $flat_no != null && $building != null)
        {
             $cust_exist  = DB::table('users')->where('phone', $request->input('phone'))->get();
        $status = 0;
        foreach($cust_exist as $ce)
        {
            $status = $ce->status;
        }



        if ($status == 1) {
                
                return $this->sendError('User already Exists');
            }


            else
            {
                
                 $reg = array('name'=>$name,
                'email'=>$email,
                'phone'=>$phone,
                'type' => 'user',
                'password'=>$password,
                'emirates'=>$emirates,
                'area' =>$area,
                'flat_no'=>$flat_no,
                'building'=>$building,
                'no_of_bottles'=>$no_of_bottles,
                'created_at'=>date('Y-m-d H:i:s'));
                DB::table('users')->insert($reg);

                $user_id  = DB::table('users')->where(array('phone' => $phone, 'password' => $password,'type' => 'user'))->first()->id;

                $api_token = \Helpers::generateApiToken();
                $postUpdate = [
                    'api_token' => $api_token,
                    'user_id'   => $user_id,
                    'created_at'=> date('Y-m-d H:i:s')
                ];
                
                $postUpdates = [
                    'api_token' => $api_token,
                    'user_id'   => $user_id,
                    'no_of_bottles' => $no_of_bottles,
                    'created_at'=> date('Y-m-d H:i:s')
                ];
                DB::table('user_auth_login')->insert($postUpdate);

                return $this->sendResponse($postUpdates, 'User Registered successfully');

               // echo "new useer";
            }
        }
        else{
            return response()->json(['Please fill all fields']);
        }
       

      }

     public function getEmirates(Request $request)
 {
       
        $data = [];
       

            try
            {
               $emirates = DB::table('emirates')->get();
               foreach($emirates as $em)
               {
                $emi = ['emirates_id'=>$em->id,'name'=>$em->name];
                $data[]= $emi;
               }

               return response()->json($data); 

            }
            catch (\Exception $e) {
    
                return response()->json(['error' => 'error in fetching data'], 500);
            }

            

       

    }

     public function custLogin(Request $request)
 {
        

                $phone = $request->input('username');
                $password = md5($request->input('password'));

                try{

                     $user_id = DB::table('users')->where(array('phone'=>$phone,'password'=>$password))->first()->id;


                if($user_id >0)
                {
                     $api_token = \Helpers::generateApiToken();

                 $postUpdate = [
                    'api_token' => $api_token,
                    'user_id'   => $user_id,
                    'created_at'=> date('Y-m-d H:i:s')
                ];
                DB::table('user_auth_login')->insert($postUpdate);
                
                UserAuthLogin::insert($postUpdate);

                return $this->sendResponse($postUpdate, 'User login successfully');

                }

               
                }

                catch (\Exception $e) {
    
                return response()->json(['error' => 'wrong username or password'], 500);
            }

                 

               


            

       

    }

    public function getArea(Request $request)
 {
       
        $data = [];
        
            try
            {
                $emirates_id =$request->input('emirates_id');
               $areas = DB::table('areas')->where('emirates_id',$emirates_id)->get();

                foreach($areas as $em)
               {
                $emi = ['area_id'=>$em->id,'name'=>$em->name];
                $data[]= $emi;
               }

               return response()->json($data); 

            }
            catch (\Exception $e) {
    
                return response()->json(['error' => 'error in fetching data'], 500);
            }

    }

    public function driverProfile($token)
    {
        $user_id = DB::table('user_auth_login')->where('api_token', $token)->first()->user_id;

        $driver = DB::table('users')->where('id', $user_id)->get();

        foreach ($driver as $d) {
            $data = ['phone' => $d->phone,
                'name' => $d->name,
                'email' => $d->email];
        }

        return response()->json($data);
    }

    public function customerProfile($token)
    {
        $user_id = DB::table('user_auth_login')->where('api_token', $token)->first()->user_id;

        $customer = DB::table('users')->where('id', $user_id)->get();

        foreach ($customer as $c) {
            if($c->emirates > 0)
            {
              $emirates = DB::table('emirates')->where('id',$c->emirates)->first()->name;
              $area = DB::table('areas')->where('id',$c->area)->first()->name;  
            }
            else
            {
                $emirates = "--";
                $area = "--";
            }
            
            $data = ['phone' => $c->phone,
                'name' => $c->name,
                'email' => $c->email,
                'emirates' =>$emirates,
                'area' => $area,
                'building'=>$c->building,
                'flat_no'=>$c->flat_no];
        }

        return response()->json($data);
    }

    public function driverLogout($token)
    {
        $user_id = DB::table('user_auth_login')->where('api_token', $token)->first()->user_id;

        if ($user_id != null) {
            DB::table('user_auth_login')->where('api_token', $token)->delete();

            $response = 'Success,Logged out!';
        } else {
            $response = 'Error, Unauthorised user';
        }

        return response()->json($response);

    }

    public function getProfile(Request $request)
    {
        try {
            if ($request->userAuthData) {
                if ($request->userAuthData->user) {
                    return $this->sendResponse($request->userAuthData->user, 'Profile retrieved successfully');
                }
            }

            return $this->sendError('User not found', 401);
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function getDriverProfile(Request $request)
    {
        try {
            if ($request->userAuthData) {
                if ($request->userAuthData->user) {
                    return $this->sendResponse($request->userAuthData->user, 'Profile retrieved successfully');
                }
            }

            return $this->sendError('User not found', 401);
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    /**
     *  update profile
     *
     * @return \Illuminate\Http\Response
     */
    public function doUpdateProfile(Request $request)
    {
        try {
            if ($request->userAuthData) {
                if ($request->userAuthData->user) {
                    $post = $request->all();
                    $user = $request->userAuthData->user;

                    if ($request->input('phone') != '') {
                        $userPhone = User::where('phone', $request->input('phone'))->where('id', '!=', $user->id)->first();
                        if ($userPhone) {
                            return $this->sendError('Mobile number is already exists', 401);
                        }
                    }

                    if ($request->input('email') != '') {
                        $userEmail = User::where('email', $request->input('email'))->where('id', '!=', $user->id)->first();
                        if ($userEmail) {
                            return $this->sendError('Email is already exists', 401);
                        }
                    }

                    $postData = [
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    if (isset($post['name'])) {
                        $postData['name'] = $post['name'];
                    }

                    if (isset($post['lang_code'])) {
                        $postData['lang_code'] = $post['lang_code'];
                    }

                    if (isset($post['phone'])) {
                        $postData['phone'] = $post['phone'];
                    }

                    if (isset($post['email'])) {
                        $postData['email'] = $post['email'];
                    }
                    User::where('id', $user->id)->update($postData);
                    $user = User::where('id', $user->id)->first();

                    return $this->sendResponse($user, 'Succefully updated');
                }
            }

            return $this->sendError('User not found', 401);
        } catch (\Exception $ex) {
            return $this->sendError($ex->getMessage());
        }
    }

    public function doUpdateDriverProfile(Request $request)
    {
        try {
            if ($request->userAuthData) {
                if ($request->userAuthData->user) {
                    $post = $request->all();
                    $user = $request->userAuthData->user;

                    $user2 = User::where('phone', $request->input('phone'))->where('id', '!=', $user->id)->first();
                    if ($user2) {
                        return $this->sendError('Mobile number is already exists', 401);
                    }

                    $user3 = User::where('email', $request->input('email'))->where('id', '!=', $user->id)->first();
                    if ($user3) {
                        return $this->sendError('Email is already exists', 401);
                    }

                    $postData = [
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    if (isset($post['name'])) {
                        $postData['name'] = $post['name'];
                    }

                    if (isset($post['lang_code'])) {
                        $postData['lang_code'] = $post['lang_code'];
                    }

                    if (isset($post['phone'])) {
                        $postData['phone'] = $post['phone'];
                    }

                    if (isset($post['email'])) {
                        $postData['email'] = $post['email'];
                    }
                    User::where('id', $user->id)->update($postData);
                    $user = User::where('id', $user->id)->first();

                    return $this->sendResponse($user, 'Succefully updated');
                }
            }

            return $this->sendError('User not found', 401);
        } catch (\Exception $ex) {
            return $this->sendError($ex->getMessage());
        }
    }

    /**
     *  update profile
     *
     * @return \Illuminate\Http\Response
     */
    public function doUpdateNotification(Request $request)
    {
        try {
            if ($request->userAuthData) {
                if ($request->userAuthData->user) {
                    $post = $request->all();
                    $user = $request->userAuthData->user;
                    $postData = [
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];

                    if (isset($post['enable_notificaton'])) {
                        $postData['enable_notificaton'] = $post['enable_notificaton'];
                    } else {
                        $postData['enable_notificaton'] = 0;
                    }
                    User::where('id', $user->id)->update($postData);
                    $user = User::where('id', $user->id)->first();

                    return $this->sendResponse($user, 'Succefully updated');
                }
            }

            return $this->sendError('User not found', 401);
        } catch (\Exception $ex) {
            return $this->sendError($ex->getMessage());
        }
    }

    public function listUserAddress(Request $request)
    {
        try {
            $user_id = 0;
            if ($request->userAuthData) {
                $user_id = $request->userAuthData->user_id;
            }
            $results = DeliveryAddresses::where('user_id', $user_id)->get();

            return $this->sendResponse($results, 'User address retrieved successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function addUpdateUserAddress(Request $request)
    {
        try {

            $user_id = 0;
            if ($request->userAuthData) {
                $user_id = $request->userAuthData->user_id;
            }
            $post = $request->all();
            $post['user_id'] = $user_id;

            if ($post['id']) {
                DeliveryAddresses::where('id', $post['id'])->update($post);
            } else {
                DeliveryAddresses::create($post);
            }
            $results = DeliveryAddresses::where('user_id', $user_id)->get();

            return $this->sendResponse($results, 'User address saved successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function deleteUserAddress($id, Request $request)
    {
        try {

            DeliveryAddresses::where('id', $id)->delete();

            return $this->sendResponse([], 'User address deleted successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function setDefaultUserAddress($id, Request $request)
    {
        try {
            $user_id = 0;
            if ($request->userAuthData) {
                $user_id = $request->userAuthData->user_id;
            }
            $post = $request->all();
            $results = DeliveryAddresses::where('user_id', $user_id)->update(['is_default' => $post['is_default']]);
            DeliveryAddresses::where('id', $id)->update(['is_default' => 1]);

            return $this->sendResponse([], 'User address updated successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function settings(Request $request)
    {
        $response = [];
        $response['delivery_areas'] = DeliveryAreas::where('status', 1)->get();
        $response['holidays'] = NonWorkingDays::where('status', 1)->get();
        $response['setting'] = AppSetting::all();
        $response['languages'] = Languages::all();
        $response['timeslots'] = Timeslots::all();
        $response['terms'] = CmsPages::where('page_name', 'terms')->first();
        if ($response['terms']) {
            $translated_data = CmsPagesTranslation::where('lang_code', $this->language)->where('cms_id', $response['terms']->id)->first();
            if ($translated_data) {
                if ($translated_data->page_title != '') {
                    $response['terms']->page_title = $translated_data->page_title;
                }
                if ($translated_data->description != '') {
                    $response['terms']->description = $translated_data->description;
                }
            }
        }

        $response['about_us'] = CmsPages::where('page_name', 'about')->get();
        foreach ($response['about_us'] as $row) {
            $translated_data = CmsPagesTranslation::where('lang_code', $this->language)->where('cms_id', $row->id)->first();
            if ($translated_data) {
                if ($translated_data->page_title != '') {
                    $row->page_title = $translated_data->page_title;
                }
                if ($translated_data->description != '') {
                    $row->description = $translated_data->description;
                }
            }
        }

        foreach ($response['timeslots'] as $row) {
            $translated_data = TimeslotsTranslation::where('lang_code', $this->language)->where('timeslots_id', $row->id)->first();
            if ($translated_data) {
                if ($translated_data->name != '') {
                    $row->name = $translated_data->name;
                }
            }
        }

        $response['partners'] = Partners::where('type', 'partner')->get();
        foreach ($response['partners'] as $row) {
            $translated_data = PartnersTranslation::where('lang_code', $this->language)->where('partner_id', $row->id)->first();
            if ($translated_data) {
                if ($translated_data->name != '') {
                    $row->name = $translated_data->name;
                }
            }
        }

        $response['awards'] = Partners::where('type', 'awards')->get();
        foreach ($response['awards'] as $row) {
            $translated_data = PartnersTranslation::where('lang_code', $this->language)->where('partner_id', $row->id)->first();
            if ($translated_data) {
                if ($translated_data->name != '') {
                    $row->name = $translated_data->name;
                }
            }
        }

        return $this->sendResponse($response, 'Settings retrieved successfully');
    }

    public function doLogout(Request $request)
    {
        try {
            if ($request->userAuthData) {
                if ($request->userAuthData->user) {
                    $post = $request->all();
                    $user = $request->userAuthData->user;
                    $postUpdate = [
                        'user_id' => $user->id,
                        'api_token' => '',
                        'device_token' => '',
                        'updated_at' => date('y-m-d H:i:s'),
                    ];
                    UserAuthLogin::where('id', $request->userAuthData->id)->update($postUpdate);

                    return $this->sendResponse([], 'Logout Succefully updated');
                }
            }

            return $this->sendError('User not found', 401);
        } catch (\Exception $ex) {
            return $this->sendError($ex->getMessage());
        }
    }

    public function doDriverLogout(Request $request)
    {
        try {
            if ($request->userAuthData) {
                if ($request->userAuthData->user) {
                    $post = $request->all();
                    $user = $request->userAuthData->user;
                    $postUpdate = [
                        'user_id' => $user->id,
                        'api_token' => '',
                        'device_token' => '',
                        'updated_at' => date('y-m-d H:i:s'),
                    ];
                    UserAuthLogin::where('id', $request->userAuthData->id)->update($postUpdate);

                    return $this->sendResponse([], 'Logout Succefully updated');
                }
            }

            return $this->sendError('Driver not found', 401);
        } catch (\Exception $ex) {
            return $this->sendError($ex->getMessage());
        }
    }
}