<?php
session_start();
error_reporting(E_ALL); // Enable error reporting
ini_set('display_errors', 1); // Display errors

require ("_common/global.php");
require ("_common/conn.php");
require ("_common/check_session.php");

// Initialize session variables if they don't exist
if (!isset($_SESSION['email'])) {
    $_SESSION['email'] = 0; // Initialize as integer
}

if (!isset($_SESSION['role'])) {
    $_SESSION['role'] = ''; // Initialize as string
}

// Increment email session variable safely
if (is_int($_SESSION['email'])) {
    $_SESSION['email'] += 1;
} else {
    $_SESSION['email'] = 1; // Reset if not an integer
}

// Establish database connection
$link = mysqli_connect("localhost", "dvsvigov_vacc", "DVSvacdos123", "dvsvigov_vacdos");
if ($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Assuming you get email and password from POST request
$email = mysqli_real_escape_string($link, $_POST['email']);
$pass = mysqli_real_escape_string($link, $_POST['pass']);

// Prepare and execute 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) {
    $data = mysqli_fetch_array($result);
    $_SESSION['email'] = $data["email"];
    $_SESSION['role'] = $data["role"];
    $_SESSION['status'] = $data["status"]; // Assuming you want to store status too

    // Check user status and role for redirection
    if ($data['status'] == 'Active' && $data['role'] == 'Administrator') {  
        header("Location: dashboard.php");
        exit(); // Ensure no further code is executed
    } else if ($data['status'] == 'Active' && $data['role'] == 'Evaluator') {  
        header("Location: ev/dashboard.php");
        exit(); // Ensure no further code is executed
    } else {
        echo "Access denied: Your account status or role does not allow access.";
    }
} else {
    echo "Wrong Username or Password"; 
}

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