<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use Session;
use App\Models\Cart;
use DB;
use Illuminate\Support\Str;
use Hash;
use App\Models\User;
use App\Models\Compare;
use File;
use Illuminate\Support\Facades\Storage;

class AuthController extends Controller
{
    public function Login($phone, $password, $session_id){
        if(Auth::attempt(['phone'=>$phone,'password'=>$password])){
            Cart::where(['session_id'=>$session_id])->update([
                'user_id'=>Auth::user()->id,
                'session_id'=>'',
            ]);
            Compare::where(['session_id'=>$session_id])->update([
                'user_id'=>Auth::user()->id,
                'session_id'=>'',
            ]);
            $user = Auth::user();
            $success['authToken'] = $user->createToken('myApp')->plainTextToken;
            $cart = DB::table('carts')->where(['user_id'=>Auth::user()->id])->get();
            $cartsum = DB::table('carts')->where(['user_id'=>Auth::user()->id])->sum('total_price');
            return response()->json([
                'success'=>true,
                'user'=>Auth::user(),
                'cart'=>$cart,
                'cartSum'=>$cartsum,
                'data' => $success['authToken'],
                'message'=>'Successfully Logged.'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'phone_verify'=>'not_login',
                'message'=>'Incorrect Phone Number & Password.'
            ]);
        }
    }
    public function logout($tokenId){
        Session::forget('CouponCode');
        Session::forget('CouponAmount');
        DB::table('personal_access_tokens')->where(['id'=>$tokenId])->delete();
    }
    public function sessionGet(){
        return response()->json([
            'session'=>Session::getId(),
        ]);
    }
    public function AuthCheck(){
        if(Auth::check()){
            return response()->json([
                'success'=>true
            ]);
        }else{
            return response()->json([
                'success'=>false
            ]);
        }
    }
    public function checkUser($tokenId){
        $authTokenID = DB::table('personal_access_tokens')->where(['id'=>$tokenId])->first();
        $userId = DB::table('users')->where(['id'=>$authTokenID->tokenable_id])->first();
        $shipping = 0;
        $division_shipping = DB::table('divisions')->where(['name'=>$userId->division])->first();
        if($division_shipping){
             if($division_shipping->shipping_charge > 0){
                $shipping = $division_shipping->shipping_charge;    
            }
            $district_shipping = DB::table('districts')->where(['name'=>$userId->district])->first();
            if($district_shipping->shipping_charge > 0){
                $shipping = $district_shipping->shipping_charge;    
            }
            $upazila_shipping = DB::table('upazilas')->where(['name'=>$userId->upazila])->first();
            if($upazila_shipping->shipping_charge > 0){
                $shipping = $upazila_shipping->shipping_charge;    
            }   
        }
        
        return response()->json([
            'user'=>$userId,
            'shipping'=>$shipping
        ]);
    }
    public function UserUpdate(Request $request){
        $authTokenID = DB::table('personal_access_tokens')->where(['id'=>$request->tokenId])->first();
        $userId = DB::table('users')->where(['id'=>$authTokenID->tokenable_id])->first();
        DB::table('users')->where(['id'=>$userId->id])->update([
            'address'=>$request->address,
            'email'=>$request->email,
            'name'=>$request->name,
            'phone'=>$request->phone,
        ]);
        $user = DB::table('users')->where(['id'=>$userId->id])->first();
        return response()->json([
            'user'=>$user
        ]);
    }
    public function forgotPassword($phone_no){
        $phone_no_check = DB::table('users')->where(['phone'=>$phone_no])->count();
        if($phone_no_check > 0){
            $otp = mt_rand(20000,90000);
            $user = DB::table('users')->where(['phone'=>$phone_no])->select('phone')->first();
            // Phone No Message Use
            // StartSend Message Phone
            $setting = DB::table('settings')->select('sms_api_key','sms_sender_id','web_name','sms_url')->first();
            $api_key = $setting->sms_api_key;
            $to = $user->phone;
            $from = $setting->sms_sender_id;
            $sms = "Your $setting->web_name One time pin is $otp";

            $url = $setting->sms_url;

            $data= array(
            'api_key'=>"$api_key",
            'from'=>"$from",
            'to'=>"+880$to",
            'sms'=>"$sms",
            ); // Add parameters in key value
            $ch = curl_init(); // Initialize cURL
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_ENCODING, '');
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $smsresult = curl_exec($ch);
            return response()->json([
                'success'=>true,
                'otp'=>$otp,
                'user'=>$user,
                'message'=>'Your OTP Successfully Send'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'message'=>'Your Phone Number Not Valid.'
            ]);
        }
    }
    public function changePassword(Request $request, $phone = null){
        if($request->newPassword == $request->confirmPassword){
            DB::table('users')->where(['phone'=>$phone])->update(['password'=>Hash::make($request->newPassword)]);
        }
        return response()->json([
            'phone'=>$request->all(),
        ]);
    }
    public function userChangePassword(Request $request){
        $authTokenID = DB::table('personal_access_tokens')->where(['id'=>$request->AuthTokenId])->first();
        $userId = DB::table('users')->where(['id'=>$authTokenID->tokenable_id])->first();
        if(Hash::check($request->oldPassword,$userId->password)){
            if($request->newPassword == $request->confirmPassword){
                DB::table('users')->where(['phone'=>$userId->phone])->update(['password'=>Hash::make($request->newPassword)]);
            }
            return response()->json([
                'success'=>true,
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'msg'=>'Incorrect current password.',
            ]);
        }

    }
    public function userSignUp(Request $request){
        $userCheck = User::where(['phone'=>$request->phone_no])->count();
        $phonecheck = strlen((string)$request->phone_no);
        $three_number = substr($request->phone_no, 0, 3);
        if($phonecheck > 10 && $phonecheck < 12 && $three_number == '013' || $three_number == '016' || $three_number == '017' || $three_number == '018' || $three_number == '015'  || $three_number == '019' || $three_number == '014'){
            if($userCheck > 0){
                return response()->json([
                    'success'=>false,
                    'msg'=>'User Already Added.',
                ]);
            }else{
                $user = new User;
                $user->phone = $request->phone_no;
                $user->email = $request->email;
                $user->password = Hash::make($request->password);
                $user->save();
                return response()->json([
                    'success'=>true,
                    'user'=>$user,
                ]);
            }
        }else{
            return response()->json([
                'success'=>false,
                'msg'=>'Incorrect Phone Number.',
                'phone'=>$three_number
            ]);
        }
    }
    public function defaultOTP($phone){
        $otp = mt_rand(20000,90000);
        // Phone No Message Use
        $user = DB::table('users')->where(['phone'=>$phone])->select('phone')->first();
        $setting = DB::table('settings')->select('sms_api_key','sms_sender_id','web_name','sms_url')->first();
        $api_key = $setting->sms_api_key;
        $to = $user->phone;
        $from = $setting->sms_sender_id;
        $sms = "Your $setting->web_name One time pin is $otp";

        $url = $setting->sms_url;

        $data= array(
        'api_key'=>"$api_key",
        'from'=>"$from",
        'to'=>"+880$to",
        'sms'=>"$sms",
        ); // Add parameters in key value
        $ch = curl_init(); // Initialize cURL
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_ENCODING, '');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $smsresult = curl_exec($ch);
        return response()->json([
            'success'=>true,
            'otp'=>$otp,
            'message'=>'Your OTP Successfully Send'
        ]);
    }
    public function confirmVerifyOTP($phone){
        User::where(['phone'=>$phone])->update(['verify'=>1]);
        $user = DB::table('users')->where(['phone'=>$phone])->first();
        return response()->json([
            'success'=>true,
        ]);
    }
    public function updateProfilePicture(Request $request){
        $user = DB::table('users')->where(['id'=>$request->userId])->first();
        $destination = 'storage/image/profile/'.$user->image;
        if(File::exists($destination))
        {
            File::delete(public_path($destination));
        }
        $img_explode = strpos($request->image, ';');
        $str_image =  substr($request->image, 0, $img_explode);
        $files_explode = strpos($str_image, '/');
        $files_extenstion = substr($str_image, 11, $files_explode);
        $img_slug = $user->name;
        $img_name = $img_slug.'-'.mt_rand(2000,9000).'.'.$files_extenstion;
        $img_path = 'image/profile/'.$img_name;
        Storage::disk('public')->put($img_path, file_get_contents($request->image));
        DB::table('users')->where(['id'=>$request->userId])->update(['image'=>$img_name]);
        return response()->json([
            'success'=>true,
        ]);
    }
    public function LatitudeLongitudeAdd($latitude, $longitude, $tokenId){
        $authTokenID = DB::table('personal_access_tokens')->where(['id'=>$tokenId])->first();
        // $userId = DB::table('users')->where(['id'=>$authTokenID->tokenable_id])->first();
        DB::table('users')->where(['id'=>$authTokenID->tokenable_id])->update([
            'lat'=>$latitude,
            'long'=>$longitude,
        ]);
        return response()->json([
            'success'=>true,
        ]);
    }
}
