<?php
// Start the session at the very beginning
session_start();
// Include necessary files
require("_common/global.php");
require("_common/conn.php");
// Connect to the database
$link = mysqli_connect("localhost", "dvsvigov_vacc", "DVSvacdos123", "dvsvigov_vacdos");
if ($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Initialize login attempts counter
if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
}
// Get email and password from POST data, ensuring they are sanitized
$email = mysqli_real_escape_string($link, $_POST['email']);
$pass = mysqli_real_escape_string($link, $_POST['pass']);

// Prepare the SQL query
$sql = "SELECT * FROM user WHERE email='$email' AND pass='$pass'";
$result = mysqli_query($link, $sql);

if (!$result) {
    die("ERROR: Could not execute $sql. " . mysqli_error($link));
}

$num_results = mysqli_num_rows($result);

if ($num_results == 1) { // ID and password correct
    $data = mysqli_fetch_array($result);
    $_SESSION['email'] = $data["email"];
    $_SESSION['pass'] = $data["pass"];
    $_SESSION['role'] = $data["role"];
    
    // Check user status and role
    if ($data['status'] == 'Active' && $data['role'] == 'Administrator') {  
        header("Location: dashboard.php");
        exit();
    } else if ($data['status'] == 'Active' && $data['role'] == 'Evaluator') {  
        header("Location: ev/dashboard.php");
        exit();
    } else {	
        session_destroy();
        header("Location: notregister.php");
        exit();
    }
} else {
    $_SESSION['login_attempts']++;
    echo "Wrong Username or Password"; 
}

// Close the database connection
mysqli_close($link);
?>
