<?php
include('mysql.php');
include('../password_compat-master/lib/password.php');

$field_err = [];
$user_level = [];

if(isset($_POST['username'], $_POST['password'])){

$fields = [
  'username' => $_POST['username'],
  'password' => $_POST['password']
];

foreach($fields as $field => $data){
  if(empty($data)){
    $field_err[] = 'Please fill in the ' . $field ;
  }
}
}

function html_escape($html_escape){
  $html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  return $html_escape;
}

if(isset($_POST['submit'])){
  $username = ($_POST['username']);
  $password = ($_POST['password']);

  $username = stripcslashes($username);
  $password = stripcslashes($password);

  $username = html_escape($username);
  $password = html_escape($password);

  $secretKey = '6LcKfjsUAAAAAG5f-RQ6cyN2EZPZxXW8UJmTsKQL';
  $responseKey = $_POST['g-recaptcha-response'];
  $userIP = $_SERVER['REMOTE_ADDR'];

  $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
  $response = file_get_contents($url);
  $response = json_decode($response);

  if ($response->success){

  }else {
    $field_err[] = "You didn't pass verification test";
  }

  if (!ctype_alnum($username)) {
    $field_err[] = "Wrong username or password";
  }


  $response = array();
  $response["success"] = false;



  if(empty($field_err)){
    $statement = mysqli_prepare($dbc, "SELECT * FROM users WHERE username = ?");
    mysqli_stmt_bind_param($statement, "s", $username);
    mysqli_stmt_execute($statement);
    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $col_id, $col_email, $col_username, $col_password);
    while(mysqli_stmt_fetch($statement)){
        if (password_verify($password, $col_password)) {

            SESSION_START();
            $_SESSION['admin'] = $username;
            header('Location: add_image.php');
        }
      }
      $field_err[] = 'Wrong username or password';
    }
  }




?>
