<?php
session_start();
$username = $_POST['cand_username'] ?? '';
$password = $_POST['cand_password'] ?? '';


$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$xcentr = $_POST['xcentr'] ?? '';

include 'dbcon.php';

// Encrypt password
$password = md5($password);

// Check login
$sql = mysqli_query($conn, "SELECT * FROM matcher_usermst 
    WHERE nif_usr='$username' 
    AND nif_pass='$password' 
    AND act_vate='1'");

if (mysqli_num_rows($sql) > 0) {
    session_regenerate_id(true);
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $_POST['cand_password'] ?? '';

$_SESSION['logged_in'] = true;

    $row = mysqli_fetch_assoc($sql);
    $xadmnchk = $row['dept_x'];

    // Insert login log
    mysqli_query($conn, "INSERT INTO user_log_login 
        (log_date, user_id, ip, deprtmnt) 
        VALUES (NOW(), '$username', '$ip', '3')")
        or die(mysqli_error($conn));

    echo "<meta http-equiv='refresh' content='1;url=main_wlcm_andron.php'>";

} else {
    echo "Invalid login";
}
?>
