<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Token;
use App\Models\Education;
use App\Models\NextOfKin;
use App\Models\Guarantor;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Http;

class AuthController extends Controller
{

    public function guarantor(Request $request)
    {
        $credentials = $request->validate([
            'title' => ['required'],
            'fullName' => ['required'],
            'address' => ['required'],
            'email' => ['required'],
            'phone' => ['required'],
            'nin' => ['required'],
            'passport' => ['required', 'max:1000'],
            'employer' => ['required'],
            'jobTitle' => ['required'],
        ]);
        // check that a gurantor can only stand for two stafe in this organizaation
        // upload image of garantore
        $imageName = Storage::disk('local')->put('public/images', $request->passport);
        $imageName = basename($imageName);

        $guarantor = new Guarantor();
        $guarantor->title = $credentials["title"];
        $guarantor->fullName = $credentials["fullName"];
        $guarantor->address = $credentials["address"];
        $guarantor->phone = $credentials["phone"];
        $guarantor->email = $credentials["email"];
        $guarantor->nin = $credentials["nin"];
        $guarantor->passport = "storage/images/" . $imageName;
        $guarantor->employer = $credentials["employer"];
        $guarantor->jobTitle = $credentials["jobTitle"];
        $guarantor->user_id = Auth::id();
        $guarantor->save();

        $checkGarantor = Guarantor::where('user_id', '=', Auth::id())->count();

        // send nin verification request
        $message = "Guarantor " . $checkGarantor . " record added successfully. You can add more or click 'Next' to continue.";
        return back()->with('message', $message);
    }

    public function nextOfKin(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'fullName' => ['required'],
            'relationship' => ['required'],
            'phone' => ['required'],
            'email' => ['required'],
            'homeAddress' => ['required'],
            'workAddress' => ['required'],
        ]);


        $nextOfKin = new NextOfKin();
        $nextOfKin->fullName = $credentials["fullName"];
        $nextOfKin->relationship = $credentials["relationship"];
        $nextOfKin->phone = $credentials["phone"];
        $nextOfKin->email = $credentials["email"];
        $nextOfKin->homeAddress = $credentials["homeAddress"];
        $nextOfKin->workAddress = $credentials["workAddress"];
        $nextOfKin->user_id = Auth::id();
        $nextOfKin->save();

        return redirect()->intended('guarantor');
    }

    public function education(Request $request)
    {
        $credentials = $request->validate([
            'institution' => ['required'],
            'certification' => ['required'],
            'data' => ['required'],
        ]);

        $education = new Education();
        $education->institution = $credentials["institution"];
        $education->certification = $credentials["certification"];
        $education->date = Carbon::now();
        $education->user_id = Auth::id();
        $education->save();
        $message = "Educational record added successfully. You can add more or click 'Next' to continue.";
        return back()->with('message', $message);
    }

    public function personalInfo(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'homeAddress' => ['required'],
            'state' => ['required'],
            'lga' => ['required'],
            'gender' => ['required'],
            'dob' => ['required'],
            'height' => ['required'],
            'weight' => ['required'],
            'religion' => ['required'],
            'maritalStatus' => ['required'],
            'bloodGroup' => ['required'],
            'genotype' => ['required'],
            'medicalCon' => ['required'],
        ]);


        User::where('id', '=', Auth::id())->update([
            "address" =>  $credentials['homeAddress'],
            "gender" =>  $credentials['gender'],
            "state" =>  $credentials['state'],
            "lga" =>  $credentials['lga'],
            "dob" =>  $credentials['dob'],
            "religion" =>  $credentials['religion'],
            "height" =>  $credentials['height'],
            "weight" =>  $credentials['weight'],
            "bloodGroup" =>  $credentials['bloodGroup'],
            "genotype" =>  $credentials['genotype'],
            "medicalCon" =>  $credentials['medicalCon'],
            'updated_at' => Carbon::now()
        ]);


        return redirect()->intended('education');
    }

    public function verifyPhone(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'token' => ['required'],
        ]);

        $tokenDetails = Token::where('token', '=', $credentials['token'])->first();

        if ($tokenDetails && $tokenDetails->identifier == Auth::user()->phone) {
            User::where('id', '=', Auth::id())->update([
                "phone_verified_at" => Carbon::now(),
                'updated_at' => Carbon::now()
            ]);
            return redirect()->intended('personal-info');
        }
        return back()->withErrors([
            'token' => 'The provided token do not match our records.',
        ])->onlyInput('token');
    }

    public function login(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'emailPhone' => ['required'],
            'password' => ['required'],
        ]);

        $remember_me = $request->has('remember') ? true : false;
        $loginStatus = false;
        $userDetails = User::where('email', '=', $credentials['emailPhone'])->orWhere('phone', '=', $credentials['emailPhone'])->first();
        if ($userDetails) {
            if ($userDetails->email) {
                $credentials = array("email" => $credentials['emailPhone'], "password" => $credentials['password']);
                if (Auth::attempt($credentials, $remember_me)) {
                    $loginStatus = true;
                }
            } else {
                $credentials = array("phone" => $credentials['emailPhone'], "password" => $credentials['password']);
                if (Auth::attempt($credentials, $remember_me)) {
                    $loginStatus = true;
                }
            }
        }

        if ($loginStatus) {
            $request->session()->regenerate();

            $checkEducation = Education::where('user_id', '=', $userDetails->id)->count();
            $checkNextOfKin = NextOfKin::where('user_id', '=', $userDetails->id)->count();
            $checkGuarantor = Guarantor::where('user_id', '=', $userDetails->id)->count();

            if (!$userDetails->phone_verified_at) {
                return redirect()->intended('phone-Verification');
            }
            if (!$userDetails->address) {
                return redirect()->intended('personal-info');
            }
            if ($checkEducation == 0) {
                return redirect()->intended('education');
            }
            if ($checkNextOfKin==0) {
                return redirect()->intended('next-of-kin');
            }
            if ($checkGuarantor < 2) {
                return redirect()->intended('guarantor');
            }


            return redirect()->intended('dashboard');
        }



        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    public function register(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'firstName' => ['required'],
            'lastName' => ['required'],
            'phone' => ['required', 'unique:users'],
            'email' => ['email', 'unique:users', 'max:255'],
            'password' => ['required', 'min:8'],
        ]);
        $newPhone = $credentials['phone'];
        if (substr($newPhone, 0, 1) == 0) {
            $newPhone = "234" . substr($newPhone, 1);
        }

        try {
            $user = new User();
            $user->firstName = $credentials["firstName"];
            $user->lastName = $credentials["lastName"];
            $user->phone = $newPhone;
            $user->password = Hash::make($credentials["password"]);
            $user->email = $credentials["email"];
            $user->img = "/images/profilepictur.png";
            $user->save();
        } catch (\Throwable $th) {
            return back()->withErrors([
                'error' => 'We are unable to create your account at this time, please try again shortly',
            ])->withInput();
        }

        if (Auth::attempt(["phone" => $newPhone, "password" => $credentials["password"]])) {
            $request->session()->regenerate();
            $random = Str::random(6);

            $genToken = new Token();
            $genToken->identifier = $newPhone;
            $genToken->token = $random;
            $genToken->type = "register";
            $genToken->save();

            $data = array(
                "api_key" => config('app.TERMII_API_KEY'),
                "to" => $newPhone,
                "from" => "N-Alert",
                "sms" => "Hello  " . $credentials["firstName"] . " your SPS token is " . $random,
                "type" => "plain",
                "channel" => "dnd"
            );
            $response = Http::post('https://v3.api.termii.com/api/sms/send', $data);
            $response->json();

            return redirect()->intended('phone-Verification');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->withInput();
    }
}
