<?php


// Unified login check
function isLoggedIn() {
    return isset($_SESSION['user']) && !empty($_SESSION['user']['id']);
}

// Updated login function
function login($email, $password) {
    global $pdo;
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user'] = [
            'id' => $user['id'],
            'email' => $user['email'],
            'user_type' => $user['user_type']
        ];
        
        // Update last login
        $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?")
            ->execute([$user['id']]);
            
        return true;
    }
    
    return false;
}

// Logout function
function logout() {
    session_unset();
    session_destroy();
}

// Check user role
function hasRole($role) {
    return isLoggedIn() && $_SESSION['user']['user_type'] === $role;
}

// Password reset token generation
function generatePasswordResetToken($email) {
    global $pdo;
    
    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    $pdo->prepare("INSERT INTO password_resets (email, token, created_at) VALUES (?, ?, ?)")
        ->execute([$email, $token, $expires]);
    
    return $token;
}

function verifyDashboardAccess() {
    if (!isLoggedIn()) {
        $_SESSION['redirect_url'] = $_SERVER['REQUEST_URI'];
        header("Location: " . BASE_URL . "dashboard/login.php");
        exit;
    }
}

function checkRoleAccess($requiredRole) {
    if ($_SESSION['user']['user_type'] !== $requiredRole) {
        $_SESSION['error'] = "You don't have permission to access this section";
        header("Location: " . BASE_URL . "dashboard/");
        exit;
    }
}

function loginUser($userData) {
    $_SESSION['user'] = [
        'id' => $userData['id'],
        'email' => $userData['email'],
        'user_type' => $userData['user_type'],
        'first_name' => $userData['first_name'] ?? '',
        'last_name' => $userData['last_name'] ?? ''
    ];
    
    // Redirect to appropriate dashboard
    $redirectUrl = $_SESSION['redirect_url'] ?? 
                  BASE_URL . 'dashboard/' . $_SESSION['user']['user_type'] . '/';
    
    unset($_SESSION['redirect_url']);
    header("Location: " . $redirectUrl);
    exit;
}
?>