<?php

require_once "../../../bootstrap.php";
require_once "Group.php";

use Backend\Models\Group;
use Backend\Models\Password;
use Illuminate\Support\Str;

//Start the php session

if(isset($_POST['login'])){

    $groupName = $_POST["groupName"];
    $password = $_POST["password"];

   $group = Group::firstWhere('group_name', $groupName );
   if($group){
       $hashedPassword = $group->password->password;
       if(password_verify($password, $hashedPassword )){
           $token = Str::random(100);
           $groupPassword = Password::firstWhere('group_id', $group->id);
           $groupPassword->remember_token = $token;
           if($groupPassword->save()){
               $_SESSION['token'] = $token;
               $_SESSION['success'] = "You are now logged in";
               makeLogin($groupName,$group->id);
               //header('location:  ../../../Frontend/index.php?login=success');
               //exit();
               http_response_code(200);
           }
           else{
               session_destroy();
               http_response_code(500);
           }

       }else{
           session_destroy();
           http_response_code(401);
           echo json_encode(["message" => "Wrong password"]);
       }

   }else{
       session_destroy();
       http_response_code(401);
       echo json_encode(["message" => "group was not found"]);
   }


}else{
    http_response_code(400);
}
