<?php
require_once __DIR__ . '/../../config/auth.php';
require_once __DIR__ . '/../../config/rbac.php';
define('BASE_URL', '/lms/');
function registerUser($username, $email, $password, $role) {
    $pdo = getDB();

    // Check if username or email already exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1");
    $stmt->execute([$username, $email]);
    if ($stmt->fetch()) {
        return ['success' => false, 'message' => 'Username or email already exists'];
    }

    // Hash the password
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);

    // Insert new user into database
    $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role, created_at) VALUES (?, ?, ?, ?, NOW())");
    try {
        $stmt->execute([$username, $email, $passwordHash, $role]);
        return ['success' => true, 'message' => 'Registration successful. You can now login.'];
    } catch (PDOException $e) {
        return ['success' => false, 'message' => 'Error during registration: ' . $e->getMessage()];
    }
}

function getSiteSetting($key) {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = ? LIMIT 1");
    $stmt->execute([$key]);
    $result = $stmt->fetch();
    return $result ? $result['setting_value'] : null;
}
function getAllPublishedPosts($limit = null, $search = null) {
    $pdo = getDB();
    $sql = "SELECT p.*, c.name as category_name, COALESCE(u.username, p.manual_author_name) as author_name FROM posts p LEFT JOIN categories c ON p.category_id = c.id LEFT JOIN users u ON p.author_id = u.id WHERE p.status = 'published'";
    $params = [];

    if ($search) {
        $sql .= " AND (p.title LIKE ? OR p.content LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    $sql .= " ORDER BY p.created_at DESC";

    if ($limit) {
        $sql .= " LIMIT ?";
        $params[] = $limit;
    }

    $stmt = $pdo->prepare($sql);
    $i = 1;
    if ($search) {
        $stmt->bindValue($i++, "%$search%", PDO::PARAM_STR);
        $stmt->bindValue($i++, "%$search%", PDO::PARAM_STR);
    }
    if ($limit) {
        $stmt->bindValue($i++, $limit, PDO::PARAM_INT);
    }
    $stmt->execute();
    return $stmt->fetchAll();
}

function getCategories() {
    $pdo = getDB();
    $stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
    return $stmt->fetchAll();
}

function getActiveAnnouncements() {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT * FROM announcements WHERE status = 'active' AND show_on_home = 1 ORDER BY created_at DESC");
    $stmt->execute();
    return $stmt->fetchAll();
}

function formatDate($date) {
    return date('M j, Y', strtotime($date));
}

function truncateText($text, $length = 150) {
    if (strlen($text) <= $length) {
        return $text;
    }
    return substr($text, 0, $length) . '...';
}

function createSlug($text) {
    // Convert to lowercase
    $slug = strtolower($text);

    // Replace non-letter or non-digits with hyphens
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);

    // Remove leading/trailing hyphens
    $slug = trim($slug, '-');

    // Ensure slug is not empty
    if (empty($slug)) {
        $slug = 'module-' . time();
    }

    return $slug;
}

function logUserActivity($user_id, $action_type, $description) {
    $pdo = getDB();
    $stmt = $pdo->prepare("
        INSERT INTO user_activities (user_id, action_type, action_description, ip_address, user_agent)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $user_id,
        $action_type,
        $description,
        $_SERVER['REMOTE_ADDR'] ?? '',
        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
}

function getCategoryBySlug($slug) {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE slug = ? LIMIT 1");
    $stmt->execute([$slug]);
    return $stmt->fetch();
}

function getPostsByCategory($category_slug) {
    $pdo = getDB();
    $sql = "SELECT p.*, c.name as category_name, COALESCE(u.username, p.manual_author_name) as author_name FROM posts p LEFT JOIN categories c ON p.category_id = c.id LEFT JOIN users u ON p.author_id = u.id WHERE p.status = 'published' AND c.slug = ? ORDER BY p.created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$category_slug]);
    return $stmt->fetchAll();
}

function getPostBySlug($slug) {
    $pdo = getDB();
    $sql = "SELECT p.*, c.name as category_name, COALESCE(u.username, p.manual_author_name) as author_name FROM posts p LEFT JOIN categories c ON p.category_id = c.id LEFT JOIN users u ON p.author_id = u.id WHERE p.status = 'published' AND p.slug = ? LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$slug]);
    return $stmt->fetch();
}
?>
