<?php
/**
 * Helper Functions
 * The Perfect Vape Admin Panel
 */

/**
 * Send JSON Response
 */
// Helper to get database connection
function getDB() {
    // Check if Database class exists (autoload or included)
    if (class_exists('Database')) {
        return Database::getInstance()->getConnection();
    }
    // Fallback if class not found but $pdo global might exist from include
    global $pdo;
    if ($pdo) {
        return $pdo;
    }
    throw new Exception("Database connection not available");
}

/**
 * Send JSON Response
 */
function sendJSON($data, $status_code = 200) {
    http_response_code($status_code);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

/**
 * Send Success Response
 */
function sendSuccess($message, $data = [], $status_code = 200) {
    sendJSON([
        'success' => true,
        'message' => $message,
        'data' => $data
    ], $status_code);
}

/**
 * Send Error Response
 */
function sendError($message, $errors = [], $status_code = 400) {
    sendJSON([
        'success' => false,
        'message' => $message,
        'errors' => $errors
    ], $status_code);
}

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

/**
 * Require Login - Redirect if not logged in
 */
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ' . ADMIN_BASE_URL . '/login.php');
        exit;
    }
}

/**
 * Get Logged In User ID
 */
function getLoggedInUserId() {
    return $_SESSION['admin_user_id'] ?? null;
}

/**
 * Get Logged In User Data
 */
function getLoggedInUser() {
    if (!isLoggedIn()) {
        return null;
    }
    
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT id, username, email, full_name, role, avatar, is_active FROM admin_users WHERE id = ? AND is_active = 1");
        $stmt->execute([getLoggedInUserId()]);
        return $stmt->fetch();
    } catch (Exception $e) {
        return null;
    }
}

/**
 * Sanitize Input
 */
function sanitize($data) {
    if (is_array($data)) {
        return array_map('sanitize', $data);
    }
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

/**
 * Validate Email
 */
function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Hash Password
 */
function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
}

/**
 * Verify Password
 */
function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

/**
 * Generate Random Token
 */
function generateToken($length = 32) {
    return bin2hex(random_bytes($length));
}

/**
 * Log Activity (for future use)
 */
function logActivity($action, $details = '') {
    // TODO: Implement activity logging
}

?>

