<?php
session_start();
include "dbcon.php";

/* CSRF CHECK */
if (
    !isset($_POST['csrf_token']) ||
    !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
) {
    die("Invalid CSRF Token");
}

$username = $_POST['username'];
$password = $_POST['password'];
$ip = $_SERVER['REMOTE_ADDR'];

$max_attempts = 5;
$lock_minutes = 15;

/* CHECK ATTEMPTS */
$stmt = $conn->prepare("SELECT attempts, last_attempt FROM login_attempts WHERE ip_address=?");
$stmt->bind_param("s",$ip);
$stmt->execute();
$res = $stmt->get_result();

if ($row = $res->fetch_assoc()) {
    if (
        $row['attempts'] >= $max_attempts &&
        strtotime($row['last_attempt']) > strtotime("-$lock_minutes minutes")
    ) {
        header("Location: index.php?blocked=1");
        exit;
    }
}

/* USER CHECK */
$stmt = $conn->prepare("SELECT id,password FROM admins WHERE username=?");
$stmt->bind_param("s",$username);
$stmt->execute();
$result = $stmt->get_result();

if ($user = $result->fetch_assoc()) {
    if (password_verify($password,$user['password'])) {

        $_SESSION['admin_id'] = $user['id'];

        // RESET ATTEMPTS
        $stmt = $conn->prepare("DELETE FROM login_attempts WHERE ip_address=?");
        $stmt->bind_param("s",$ip);
        $stmt->execute();

        header("Location: dashboard.php");
        exit;
    }
}

/* FAILED LOGIN */
$stmt = $conn->prepare(
    "INSERT INTO login_attempts (ip_address,attempts)
     VALUES (?,1)
     ON DUPLICATE KEY UPDATE attempts=attempts+1,last_attempt=NOW()"
);
$stmt->bind_param("s",$ip);
$stmt->execute();

header("Location: index.php?error=1");
exit;
?>
