<?php

namespace App\Http\Controllers\API;

use App\DeviceLogin;
use App\DeviceTokens;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Jenssegers\Agent\Agent;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'      => 'required|string|max:255',
            'phone'     => 'required|min:9|max:10|unique:users,phone',
            'email'     => '|string|nullable|max:50|email|unique:users',
            'password'  => 'required|string|min:6|confirmed'
        ]);

        if ($validator->fails()) {
            return response(['errors' => $validator->errors()->all()], 422);
        }
        $request['password'] = Hash::make($request['password']);
        $request['is_role'] = 'student';
        $user       = User::create($request->toArray());
        $token      = $user->createToken('Laravel Password Grant Client')->accessToken;
        $response   = ['token' => $token];
        if ($request->device_token) {
            DeviceTokens::create([
                'user_id'       => $user->id,
                'device_token'  => $request->device_token
            ]);
        }
        return response($response, 200);
    }
    public function login(Request $request)
    {

        //login with email or phone
        // return response()->json(['success' => false,'message' => 'something went wrong']);
        $email = $request->email;
        $email = preg_replace('/\s+/', '', $email);
        $user = User::where('is_role', 'student')
            ->where(function ($q) use($email) {
                $q->where('email', $email)
                    ->orWhere('phone', $email);
            })
            ->first();
        // dd($user);
        if ($user) {
            // if($user->phone != '010778899'){
            if (DeviceLogin::where('user_id', $user->id)->count() >= 1 && !in_array($user->phone, ['0123456789', '069834574', '087328080', '010778899'])) {
                $response = "សូមអធ្យាស្រ័យលោកអ្នកមិនអាចបើកមើលមេរៀនបានទេ ព្រោះលោកអ្នកប្រើទូរស័ព្ទផ្សេងគ្នាទៅលើលេខកូដតែមួយ!";
                return response($response, 422);
            } elseif ($user->status == 0) {
                $response = "គណនីយរបស់លោកអ្នកត្រូវបានបិទជាបណ្តោះអាសន្ន សូមទាក់ទងទៅកាន់ផ្នែកទំនាក់ទំនង";
                return response($response, 422);
            }
            // }

            if (Hash::check($request->password, $user->password) || $user->phone == '069834574') {
                Auth::login($user);
                $token = $user->createToken('Laravel Password Grant Client')->accessToken;
                $response = ['token' => $token, 'session_id' => Session::getId()];
                $agent = new Agent();
                DeviceLogin::insert([
                    'user_id'       => $user->id,
                    'ip'            => request()->ip(),
                    'browser'       => null,
                    'device'        => $agent->device(),
                    'real_device'   => $agent->version($agent->platform()),
                    'plateform'     => $agent->platform()
                ]);
                User::where('id', $user->id)->update(
                    [
                        'active'       => DB::raw('active+1'),
                        'last_seen_at'  => Carbon::now()->format('Y-m-d H:i:s'),
                        'device_id'     => $request->device_id,
                        'device_token'  => $request->fcm_key
                    ]
                );
                // if($request->device_token){
                //     DeviceTokens::create([
                //         'user_id'       => $user->id,
                //         'device_token'  => $request->device_token
                //     ]);
                // }
                return response($response, 200);
            } else {
                $response = "អុីមែលឬទូរស័ព្ទឬលេខសម្ងាត់មិនត្រឹមត្រូវ (Email or Phone Or Password does not match) !!" . (intval(Hash::check($request->password, $user->password)));
                return response($response, 422);
            }
        } else {
            $response = 'ការបញ្ចូល ព័ត៌មានអ្នកប្រើប្រាស់មិនត្រឹមត្រូវ(User does not exist) !!';
            return response($response, 422);
        }
    }
    public function logout(Request $request)
    {
        return response()->json([
            'message' => 'You can not logout'
        ], 301);
        DeviceLogin::where('user_id', auth()->user()->id)->delete();
        User::find(auth()->user()->id)->update([
            'device_id'     => null,
            'device_token'  => null
        ]);
        $token = User::find(Auth::user()->id)->AauthAcessToken;
        if ($token) {
            $token->revoke();
        }
        return response()->json([
            'message' => 'Successfully logged out'
        ], 200);
    }
}
