<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\DeactivatedParentsAccount;
use App\Models\ParentAccount;
use App\Models\Parents;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{

    /**
     * Login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if ($this->guard()->attempt($this->credentials($request))) {

            $user = $this->guard()->user();
            $success['token'] =  $user->createToken('Sama-AlAshrafia')->accessToken;
            $parent = Parents::find($user->parent_id);
            $success['user'] =  [
                "username" => $user->username,
                "email" => $user->email,
                "account_id" => $user->id,
                "parent_id" =>  $parent->id,
                "first_name" => $parent->first_name,
                "last_name" => $parent->last_name,
                "phone" => $parent->phone,
            ];

            $data = [
                "code" => 1,
                "data" => $success,
                "msg" => ""
            ];
            return new JsonResponse($data, 200);
        } else if ($res = DeactivatedParentsAccount::checkCredentials($request->username, $request->password)) {

            $data = [
                "code" => 0,
                "data" => [
                    'DAccount_id' => $res->id,
                    'parent_id' => $res->parent_id,
                ],
                "msg" => ""
            ];

            return new JsonResponse($data, 200);
        } else {
            $data = [
                "code" => -1,
                "data" => [],
                "msg" => trans('auth.failed')
            ];
            return new JsonResponse($data, 400);
        }
    }


    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request)
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return [
            $this->username($request) => $request->username,
            'password' => $request->password,
        ];
    }


    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username(Request $request)
    {
        $fieldType = filter_var($request->username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        return $fieldType;
    }


    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('parent');
    }

    public function register(Request $request)
    {
        $data = $request->all();
        Validator::make($data, [
            'DAccount_id' => ['required', 'max:255', 'exists:App\Models\DeactivatedParentsAccount,id'],
            'parent_id' => ['required', 'max:255', 'exists:App\Models\Parents,id'],
            'email' => ['required', 'unique:parent_accounts', 'max:255', 'email'],
            'username' => ['required', 'max:255', 'unique:parent_accounts'],
            'password' => ['required', 'confirmed', Password::min(4)],
        ], [], [])->validate();

        ParentAccount::create([
            'parent_id' => $data['parent_id'],
            'email' => $data['email'],
            'username' => $data['username'],
            'password' => Hash::make($data['password']),
        ]);

        DeactivatedParentsAccount::find($data['DAccount_id'])->delete();


        $data = [
            "code" => 1,
            "data" => [],
            "msg" => trans('general.New Account Created Successfully')
        ];

        return new JsonResponse($data, 200);
    }

    public function logout(Request $request)
    {
        $request->user()->token()->revoke();;

        $data = [
            "code" => 1,
            "data" => [],
            "msg" => trans('general.loged_out')
        ];

        return new JsonResponse($data, 200);
    }

    public function updateFMCToken(Request $request)
    {
        $data = $request->all();
        Validator::make($data, [
            'account_id' => ['required', 'exists:App\Models\ParentAccount,id'],
            'fmc_token' => ['required'],
        ], [], [])->validate();

        $parent_account = ParentAccount::find($data['account_id']);
        $parent_account->fmc_token = $data['fmc_token'];
        $parent_account->save();
        
        $data = [
            "code" => 1,
            "data" => [],
            "msg" => trans('general.token_updated')
        ];

        return new JsonResponse($data, 200);
    }


    public function changePassword(Request $request)
    {
        $data = $request->all();
        Validator::make($data, [
            'account_id' => ['required', 'exists:App\Models\ParentAccount,id'],
            'oldPassword' => ['required',],
            'newPassword' => ['required', Password::min(4)],
        ], [], [])->validate();

        $parent_account = ParentAccount::find($data['account_id']);
        if (Hash::check($data['oldPassword'], $parent_account->password)) {
            $parent_account->password = Hash::make($data['newPassword']);
            $parent_account->save();
            $data = [
                "code" => 1,
                "data" => [],
                "msg" => trans('passwords.reset')
            ];

            return new JsonResponse($data, 200);
            
        } else {
            $data = [
                "code" => 1,
                "data" => [],
                "msg" => trans('auth.password')
            ];

            return new JsonResponse($data, 400);
        }
    }
}
