<?php
// includes/functions.php

function redirect($url) {
    header("Location: " . $url);
    exit;
}

function clean_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

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

function requireLogin() {
    if (!isLoggedIn()) {
        redirect('index.php?page=login');
    }
}

function hasRole($role) {
    if (!isset($_SESSION['user_role'])) return false;
    $current_role = $_SESSION['user_role'];
    
    // Admin has all roles
    if ($current_role === 'admin') return true;
    
    // Hierarchy
    $hierarchy = [
        'admin' => 100,
        'coordinator' => 80,
        'roster_manager' => 60,
        'member' => 40,
        'viewer' => 20
    ];
    
    // If checking for a role not in hierarchy, exact match
    if (!isset($hierarchy[$role]) || !isset($hierarchy[$current_role])) {
        return $current_role === $role;
    }
    
    // Current role must be >= the required role
    return $hierarchy[$current_role] >= $hierarchy[$role];
}

function requireRole($role) {
    if ($role === 'any') {
        requireLogin();
        return;
    }
    if (!hasRole($role)) {
        redirect('index.php?page=dashboard&error=unauthorized');
    }
}

function json_response($data, $status = 200) {
    header('Content-Type: application/json');
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function getServiceName($date, $pdo) {
    // 1. Check if specific service exists in 'services' table
    $stmt = $pdo->prepare("SELECT type, name FROM services WHERE service_date = ?");
    $stmt->execute([$date]);
    if ($row = $stmt->fetch()) {
        $name = $row['type'];
        if ($row['name']) $name .= " (" . $row['name'] . ")";
        return $name;
    }
    
    // 2. Fallback Logic
    $dayOfWeek = date('w', strtotime($date)); // 0=Sun, 3=Wed
    if ($dayOfWeek == 0) return "Sunday Service";
    if ($dayOfWeek == 3) return "Weekly Bible Study";
    
    return "Service (" . date('D', strtotime($date)) . ")";
}

function logActivity($user_id, $action, $description) {
    global $pdo;
    try {
        $username = isset($_SESSION['username']) ? $_SESSION['username'] : (isset($_SESSION['user_role']) ? $_SESSION['user_role'] : 'System');
        // If user_id is null (e.g. login failure), we might want to capture username from context if possible, but for now stick to session.
        
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';

        $stmt = $pdo->prepare("INSERT INTO activity_logs (user_id, username, action, description, ip_address) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$user_id, $username, $action, $description, $ip]);
    } catch(Exception $e) {
        error_log("Logging Error: " . $e->getMessage());
    }
}
