<?php 
// Include database connection file
include_once("includes/db.php");
ini_set('display_errors',1);
ini_set('system_startup_errors',1);
error_reporting(E_ALL);

// Retrieve form data
$email = $_POST['email']; // Assuming the email is stored in 'email' field
$password = $_POST['password'];
// print_r($_POST);
try {
    // Prepare SQL statement to retrieve the password for the given email
    $stmt = $conn->prepare("SELECT id, fname, lname, email, role, password FROM users WHERE email = :email");
    $stmt->bindParam(':email', $email);
    $stmt->execute();

    // Check if the email exists
    if ($stmt->rowCount() > 0) {
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        // Get the stored password from the database
        $storedPassword = $row['password'];
        
        // Compare plain text passwords
        if ($password === $storedPassword) {
            session_start();
            // Password matches, set session variables
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['email'] = $row['email'];
            $_SESSION['role'] = $row['role'];
            // Redirect to dashboard.php
            echo json_encode(array("status" => "success", "message" => "Login successful.", "redirect" => "users.php"));
        } else {
            // Incorrect password
            echo json_encode(array("status" => "error", "message" => "Incorrect password."));
        }
    } else {
        // Incorrect email
        echo json_encode(array("status" => "error", "message" => "Incorrect email."));
    }
} catch(PDOException $e) {
    // Display error message
    echo json_encode(array("status" => "error", "message" => "Database error: " . $e->getMessage()));
}

// Close database connection
$conn = null;
?>
