<?php
// Only start session if one isn't already active
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Login function — supports both plain text (legacy) and bcrypt passwords
function loginUser($conn, $username, $password) {
    $sql = "SELECT id, username, password, full_name, role FROM users WHERE username = ? AND is_active = TRUE";
    $user = fetchOne($conn, $sql, [$username], "s");

    if (!$user) return false;

    $stored = $user['password'];
    $valid = false;

    if (password_get_info($stored)['algo']) {
        // Already bcrypt — verify normally
        $valid = password_verify($password, $stored);
    } else {
        // Legacy plain text — compare directly, then upgrade to bcrypt
        $valid = ($password === $stored);
        if ($valid) {
            $hashed = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->bind_param("si", $hashed, $user['id']);
            $stmt->execute();
            $stmt->close();
        }
    }

    if ($valid) {
        session_regenerate_id(true); // prevent session fixation
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['role'] = $user['role'];
        return true;
    }
    return false;
}

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Check if user is admin
function isAdmin() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

// Check if user is staff
function isStaff() {
    return isset($_SESSION['role']) && ($_SESSION['role'] === 'staff' || $_SESSION['role'] === 'admin');
}

// Require login
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: /cash_lending/login.php');
        exit();
    }
}

// Require admin — redirects staff to borrowers page
function requireAdmin() {
    if (!isAdmin()) {
        header('Location: /cash_lending/borrowers.php');
        exit();
    }
}

// Redirect staff away from admin-only pages (dashboard, payments, reports)
function requireAdminPage() {
    requireLogin();
    if (!isAdmin()) {
        header('Location: /cash_lending/borrowers.php');
        exit();
    }
}

// Logout function — properly clears session data and cookie
function logoutUser() {
    session_unset();
    session_destroy();
    // Remove session cookie from browser
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    header('Location: /cash_lending/login.php');
    exit();
}

// Get current user
function getCurrentUser($conn) {
    if (!isLoggedIn()) {
        return null;
    }
    $sql = "SELECT id, username, full_name, role, email, phone FROM users WHERE id = ?";
    return fetchOne($conn, $sql, [$_SESSION['user_id']], "i");
}

// Hash password securely using bcrypt
function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT);
}

// Validate password strength
function validatePassword($password) {
    return strlen($password) >= 8;
}
