<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AdminActivity;
use App\Models\AdminRole;
use App\Models\User;
use App\Models\UserAdmin;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Laravel\Passport\Passport;
use PHPMailer\PHPMailer\PHPMailer;

class AdminController extends Controller  {
    //
    private $createdStatusCode = 201;
    private $successStatusCode = 200;
    private $errorStatusCode = 422;

    public function adminRegister(Request $request) {
        $validate = Validator::make($request->all(), [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|email',
            'phone_number' => 'required||min:11',
            'admin_role' => 'nullable|string',
            'department' => 'nullable|string'
        ]);


        if ($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
        }

        $adminInput = $request->all();
        $adminId = self::generateAdminId();
        $adminPassword = self::generatePassword();

        $adminUser = new UserAdmin();
        $adminUser->id = $adminId;
        $adminUser->first_name = $adminInput['first_name'];
        $adminUser->last_name = $adminInput['last_name'];
        $adminUser->email = $adminInput['email'];
        $adminUser->phone = $adminInput['phone_number'];
        $adminUser->password = Hash::make($adminPassword);
        $adminUser->department = $request['department'];
        $adminUser->save();
        $templateData = [
            'body' => $adminPassword,
            'name' => $adminInput['first_name'],
        ];
        $templateContent = view('adminpasswordtemplate', $templateData)->render();
        $this->composeEmailV2('Password', $adminInput['email'],  $templateContent);
        return response()->json(['message' => 'Admin Registered successfully'], $this->createdStatusCode);
    }


    public function adminLogin()
    {

        if(Auth::guard('adminweb')->attempt(['email' => request('email'), 'password' => request('password')])) {

            $user = Auth::guard('adminweb')->user();

            $expiresAt = Passport::personalAccessTokensExpireIn(now()->addDays(7));
            $success['token' ] = $user->createToken('lasaa-admin', ['*'], ['expires_at' => $expiresAt])->accessToken;
            return response()->json(['success' => $success], $this->successStatusCode);
        }else{
            return  response()->json(['error' => 'Invalid email/password'], $this->errorStatusCode);
        }
    }

    public function adminLogout() {

        $token = Auth::user()->token();
        $token->revoke();
        return response()->json(['success' => true, 'message' => 'user successfully log out'], $this->successStatusCode);
    }

    public function getAllUserDetails(Request $request) {

        $keyword = $request->input('search');

        $getUser = User::where(function ($query) use ($keyword) {
            $query->where('first_name', 'like', '%'. $keyword . '%')
                ->orWhere('last_name', 'like', '%'. $keyword . '%')
                ->orWhere('email', 'like', '%'. $keyword .'%')
                ->orWhere('phone_number', 'like', '%' . $keyword . '%');
        })->with(['kycDetails', 'facilities'])->paginate(20);
        return response()->json(['data' => $getUser], $this->successStatusCode);
    }

    public function getCurrentAdmin() {

        $user = Auth::user();
        $userInfo = UserAdmin::where('id', $user->id)->get();
        if ($userInfo == null) {
            return response()->json(['data' => 'User does not exist'], $this->errorStatusCode);
        } else {
            return response()->json(['data' => $userInfo], $this->successStatusCode);
        }
    }

    public function  getAllAdmin(Request $request) {

        $keyword = $request->input('search');

        $getAdmin = UserAdmin::where(function ($query) use ($keyword) {
            $query->where('first_name', 'like', '%'. $keyword . '%')
                ->orWhere('last_name', 'like', '%'. $keyword . '%')
                ->orWhere('email', 'like', '%'. $keyword .'%')
                ->orWhere('phone', 'like', '%' .$keyword . '%');
        })->paginate(20);
        return response()->json(['data' => $getAdmin], $this->successStatusCode);
    }

    private static function generateAdminId() {
        $prefix = rand(10, 99);
        $batchKey = Carbon::now()->format('mds');
        $suffix = rand(10, 99);
        return $prefix.$batchKey.$suffix;
    }

    private static function generatePassword() {
        $length = 12;
        $character =  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_+=<>?';
        $batchKey = Str::random($length, $character);
        $prefix = Carbon::now()->format('YmdHis');
        return $batchKey.$prefix;
    }

    public function composeEmailV2($subject, $userEmail, $emailContent) {

        require base_path('vendor/autoload.php');


        $mail = new PHPMailer(true);
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'ssl://business74.web-hosting.com'; //ssl://smtp.gmail.com
        $mail->SMTPAuth = true;
        $mail->Username = 'noreply@laswarco.lg.gov.ng';
        $mail->Password = 'SH7ZL,&^^pCL';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        $mail->setFrom('noreply@laswarco.lg.gov.ng', 'Laswarco');
        $mail->addAddress($userEmail);
        $mail->addReplyTo('noreply@laswarco.lg.gov.ng', 'Laswarco');

        $mail->isHTML(true);

        $mail->Subject = $subject;
        $mail->Body = $emailContent;
        $mail->send();
    }
}
