<?php
// includes/auth.php - احراز هویت با password_verify

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function login($username, $password) {
    $user = fetchOne(
        "SELECT u.*, r.name as role_name, r.level as role_level 
         FROM users u 
         LEFT JOIN roles r ON u.role_id = r.id 
         WHERE u.national_code = ? AND u.is_active = 1",
        [$username]
    );
    
    if ($user) {
        // ===== بررسی رمز عبور با password_verify =====
        // اگر رمز با password_hash ذخیره شده باشد
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'] . ' ' . $user['family'];
            $_SESSION['role_id'] = $user['role_id'];
            $_SESSION['role_name'] = $user['role_name'];
            $_SESSION['role_level'] = $user['role_level'];
            
            updateData('users', ['last_login' => date('Y-m-d H:i:s')], 'id = :id', ['id' => $user['id']]);
            return true;
        }
        
        // ===== بررسی رمز عبور به صورت متن ساده (برای رمزهای قدیمی) =====
        // اگر رمز با password_hash ذخیره نشده باشد (متن ساده)
        if ($password == $user['password']) {
            // رمز را به هش تبدیل کن
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            updateData('users', ['password' => $hashedPassword], 'id = :id', ['id' => $user['id']]);
            
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'] . ' ' . $user['family'];
            $_SESSION['role_id'] = $user['role_id'];
            $_SESSION['role_name'] = $user['role_name'];
            $_SESSION['role_level'] = $user['role_level'];
            
            updateData('users', ['last_login' => date('Y-m-d H:i:s')], 'id = :id', ['id' => $user['id']]);
            return true;
        }
    }
    return false;
}

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function getCurrentUser() {
    if (!isLoggedIn()) return null;
    return fetchOne(
        "SELECT u.*, r.name as role_name, r.level as role_level 
         FROM users u 
         LEFT JOIN roles r ON u.role_id = r.id 
         WHERE u.id = ?",
        [$_SESSION['user_id']]
    );
}

function getUserRole($roleId) {
    return fetchOne("SELECT * FROM roles WHERE id = ?", [$roleId]);
}

function logout() {
    session_destroy();
    header('Location: ../login.php');
    exit;
}

function redirectToDashboard() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit;
    }
    
    $level = $_SESSION['role_level'] ?? 6;
    if ($level <= 5) {
        header('Location: admin/dashboard.php');
    } else {
        header('Location: teacher/dashboard.php');
    }
    exit;
}

function hasPermission($permission) {
    if (!isLoggedIn()) return false;
    $user = getCurrentUser();
    if (!$user) return false;
    if ($user['role_level'] == 1) return true;
    
    $perm = fetchOne(
        "SELECT * FROM permissions WHERE role_id = ? AND permission_name = ? AND is_allowed = 1",
        [$user['role_id'], $permission]
    );
    return $perm !== null;
}

function isAdmin() {
    return isLoggedIn() && isset($_SESSION['role_level']) && $_SESSION['role_level'] <= 2;
}

function isSuperAdmin() {
    return isLoggedIn() && isset($_SESSION['role_level']) && $_SESSION['role_level'] == 1;
}

function isTeacher() {
    return isLoggedIn() && isset($_SESSION['role_level']) && $_SESSION['role_level'] == 6;
}
?>