<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once 'main_db_connect.php';

// Function to log actions to audit_logs table
function logAction($conn, $userId, $username, $action, $documentId = null, $documentName = null) {
    $stmt = $conn->prepare("INSERT INTO audit_logs (user_id, username, action, document_id, file_name) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("issis", $userId, $username, $action, $documentId, $documentName);
    $stmt->execute();
    $stmt->close();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $user_type = $_POST['user_type'];
    
    // Validate input
    if (empty($username) || empty($password) || empty($user_type)) {
        header("Location: index.php?error=Please fill in all fields");
        exit();
    }
    
    // Only allow accounts appointed to 'pmed' to authenticate
    // Check if user exists in accounts table and is appointed to pmed
    $appointed_division = 'pmed';
    $stmt = $conn->prepare("SELECT id, username, password, user_type, full_name, appointed_division FROM accounts 
    WHERE username = ? AND user_type = ? AND appointed_division = ?");
    $stmt->bind_param("sss", $username, $user_type, $appointed_division);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();
        
        // Verify password (assuming passwords are hashed)
        if (password_verify($password, $user['password'])) {
            // Set session variables
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['user_type'] = $user['user_type'];
            $_SESSION['full_name'] = $user['full_name'];
            
            // Log successful login
            logAction($conn, $user['id'], $username, "Logged in to Gender and Development (pmed)");
            
            // Redirect based on user type
            if ($user_type == 'admin') {
                header("Location: admin_dashboard.php");
            } else {
                header("Location: users/user_dashboard.php");
            }
            exit();
        } else {
            // Log failed login attempt
            logAction($conn, 0, $username, "Failed login attempt - Invalid password");
            header("Location: index.php?error=Invalid password");
            exit();
        }
    } else {
        // Log failed login attempt
        logAction($conn, 0, $username, "Failed login attempt - User not found, invalid user type, or not authorized for pmed");
        header("Location: index.php?error=User not found, invalid user type, or not authorized for pmed");
        exit();
    }
    
    $stmt->close();
} else {
    header("Location: index.php");
    exit();
}
?>
