<?php
require_once __DIR__ . '/functions.php';

function error_redirect($message) {
    $error = urlencode($message);
    header("Location: index.php?error=$error");
    exit;
}

$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

if(empty($username) || empty($password)) {
    error_redirect("You username/password is empty");
}

try {
    $user = User::authorize($username, $password);
    login($user);
    insertLog($user->getId());
    if($user->level == 'admin')
        header("Location: admins.php");
    else
        header("Location: photos.php");
}
catch (ValidationError $ex) {
    insertError($username, $password);
    error_redirect($ex->getMessage());
}
catch (Exception $ex) {
    error_redirect("500 - Server error");   
}

echo "AAA";