function [loss, grad] = loss_function(X, y, w, reg_type, lambda)
% Funkcija koja izracunava funkciju gubitka i gradijent.

N = length(y);
reg = 0;
pred = sigmoid(X * w);
grad = (X' * (pred - y)) / N;

if (strcmp(reg_type, 'l1'))
    reg = sum(abs(w(2:end)));
    for i = 2:length(w)
        if (abs(w(i)) > 0)
            grad(i) = grad(i) + lambda * sign(w(i));
        elseif (grad(i) < -lambda)
            grad(i) = grad(i) + lambda;
        elseif (grad(i) > lambda)
            grad(i) = grad(i) - lambda;
        elseif (-lambda <= grad(i) && grad(i) <= lambda)
            grad(i) = 0;
        end
    end
elseif (strcmp(reg_type, 'l2'))
    grad(2:end) = grad(2:end) + 2 * lambda .* w(2:end);
    reg = sum(w(2:end) .* w(2:end));
else
    fprintf(1, 'Warning, wrong or unsupported regularization!');
end

loss = (-y .* log(pred)) - (1 - y) .* log(1 - pred);
loss = sum(loss)/N + lambda * reg;

end
