<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../main_db_connect.php'; // Include the DB connection file

$username = isset($_SESSION['username']) ? $_SESSION['username'] : 'Guest';
$divisionId = $_SESSION['division_id'] ?? $_POST['division_id'] ?? $_GET['division_id'] ?? null;

// Log user actions
if (!function_exists('logAction')) {
    function logAction($conn, $userId, $username, $action, $documentId = null, $documentName = null) {
        $stmt = $conn->prepare("INSERT INTO audit_logs (user_id, username, action, document_id, file_name) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("issss", $userId, $username, $action, $documentId, $documentName);
        $stmt->execute();
        $stmt->close();
    }
}
// Get division name from the central divisions table (ppdconline_ppdco.divisions)
if (!function_exists('getDivisionName')) {
    function getDivisionName($divisionId) {
        global $conn;
        if (!$divisionId) return null;
        // Prepare statement against the main (ppdconline_ppdco) DB connection
        $stmt = $conn->prepare("SELECT division_name FROM divisions WHERE division_id = ?");
        if (!$stmt) {
            error_log("getDivisionName prepare failed: " . $conn->error);
            return null;
        }
        $stmt->bind_param('i', $divisionId);
        $stmt->execute();
        $stmt->bind_result($divisionName);
        $stmt->fetch();
        $stmt->close();
        return $divisionName ?? null;
    }
}

// Determine which documents table to use for a division
if (!function_exists('getDivisionTable')) {
    function getDivisionTable($divisionId = null) {
        // Prefer pmed central table by default
        $default = 'pmed_documents';
        global $conn, $conn2;

        // If no division provided, return default
        if (!$divisionId) return $default;

        // If division is pmed (commonly id 2 in this setup), use pmed_documents
        if (intval($divisionId) === 2) {
            return $default;
        }

        // Otherwise, check for a per-division table named d{ID}_documents in either connection
        $candidate = 'd' . intval($divisionId) . '_documents';
        // Check main DB (ppdconline_ppdco)
        if (isset($conn)) {
            $escaped = $conn->real_escape_string($candidate);
            $res = $conn->query("SHOW TABLES LIKE '" . $escaped . "'");
            if ($res && $res->num_rows > 0) {
                return $candidate;
            }
        }
        // Check pmed DB (pmed_db) as a fallback for per-division tables
        if (isset($conn2)) {
            $escaped2 = $conn2->real_escape_string($candidate);
            $res2 = $conn2->query("SHOW TABLES LIKE '" . $escaped2 . "'");
            if ($res2 && $res2->num_rows > 0) {
                return $candidate;
            }
        }

        // If not found, fall back to pmed central table (in pmed_db)
        return $default;
    }
}

// Function to get the upload path based on division name
function getDivisionUploadPath($divisionId) {
    if (!$divisionId) {
        error_log("No division ID provided");
        return null;
    }
    // Query the central divisions table for the division name
    global $conn;
    $division = null;
    if (isset($conn)) {
        $stmt = $conn->prepare("SELECT division_name FROM ppdconline_ppdco.divisions WHERE division_id = ?");
        if ($stmt) {
            $stmt->bind_param('i', $divisionId);
            $stmt->execute();
            $res = $stmt->get_result();
            $division = $res->fetch_assoc();
            $stmt->close();
        }
    }
    if (!$division) {
        error_log("Division not found for ID: " . $divisionId);
        return null;
    }
    
    // Convert division name to proper format for directory
    $divisionName = $division['division_name'];
    $divisionName = strtolower($divisionName);
    $divisionName = str_replace(['&', '(', ')', ' '], ['and', '', '', '_'], $divisionName);
    $divisionName = preg_replace('/_{2,}/', '_', $divisionName); // Replace multiple underscores with single
    $divisionName = trim($divisionName, '_'); // Remove leading/trailing underscores
    
    // Debug output
    error_log("Division Name: " . $division['division_name']);
    error_log("Formatted Division Name: " . $divisionName);
    
    // Use absolute path
    $uploadPath = "../divisions/" . $divisionName . "/uploads/";
    error_log("Upload Path: " . $uploadPath);
    
    return $uploadPath;
}

// Function to ensure upload directory exists
if (!function_exists('ensureUploadDirectoryExists')) {
    function ensureUploadDirectoryExists($path) {
        if (!$path) {
            error_log("No path provided to ensureUploadDirectoryExists");
            return null;
        }
        
        error_log("Attempting to create directory: " . $path);
        
        if (!file_exists($path)) {
            $success = mkdir($path, 0777, true);
            if (!$success) {
                error_log("Failed to create directory: " . $path);
                return null;
            }
            // Set proper permissions after creation
            chmod($path, 0777);
            error_log("Successfully created directory: " . $path);
        } else {
            error_log("Directory already exists: " . $path);
        }
        
        return $path;
    }
}

// Function to get all admins
if (!function_exists('getAdmins')) {
    function getAdmins() {
        global $conn;
        $stmt = $conn->prepare("SELECT id, full_name, image_path FROM users WHERE user_type = 'admin'");
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_all(MYSQLI_ASSOC);
    }
}

// Function to get unread message count for a user
if (!function_exists('getUnreadMessageCount')) {
    function getUnreadMessageCount($userId) {
        global $conn;
        $stmt = $conn->prepare("SELECT COUNT(*) as unread_count FROM messages WHERE receiver_id = ? AND is_read = 0");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $stmt->bind_result($unreadCount);
        $stmt->fetch();
        $stmt->close();
        return $unreadCount;
    }
}

// Function to send a message
if (!function_exists('sendMessage')) {
    function sendMessage($senderId, $receiverId, $message) {
        global $conn;
        $stmt = $conn->prepare("INSERT INTO messages (sender_id, receiver_id, message) VALUES (?, ?, ?)");
        $stmt->bind_param("iis", $senderId, $receiverId, $message);
        $stmt->execute();
        $stmt->close();
    }
}

// Function to get messages between two users
if (!function_exists('getMessages')) {
    function getMessages($userId1, $userId2) {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM messages WHERE (sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?) ORDER BY timestamp ASC");
        $stmt->bind_param("iiii", $userId1, $userId2, $userId2, $userId1);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_all(MYSQLI_ASSOC);
    }
}

// Function to mark messages as read
if (!function_exists('markMessagesAsRead')) {
    function markMessagesAsRead($senderId, $receiverId) {
        global $conn;
        $stmt = $conn->prepare("UPDATE messages SET is_read = 1 WHERE sender_id = ? AND receiver_id = ?");
        $stmt->bind_param("ii", $senderId, $receiverId);
        $stmt->execute();
        $stmt->close();
    }
}

// Function to get users except the current user
if (!function_exists('getUsersExceptCurrent')) {
    function getUsersExceptCurrent($currentUserId) {
        global $conn;
        $stmt = $conn->prepare("SELECT id, full_name, image_path FROM users WHERE id != ?");
        $stmt->bind_param("i", $currentUserId);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_all(MYSQLI_ASSOC);
    }
}

// Function to get user image path
if (!function_exists('getUserImagePath')) {
    function getUserImagePath($userId) {
        global $conn;
        $stmt = $conn->prepare("SELECT image_path FROM users WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $stmt->bind_result($imagePath);
        $stmt->fetch();
        $stmt->close();
        return $imagePath;
    }
}

// Function to get username
if (!function_exists('getUsername')) {
    function getUsername($userId) {
        global $conn;
        $stmt = $conn->prepare("SELECT username FROM users WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $stmt->bind_result($username);
        $stmt->fetch();
        $stmt->close();
        return $username;
    }
}

// Function to get user details
if (!function_exists('getUserDetails')) {
    function getUserDetails($userId) {
        global $conn;
        $stmt = $conn->prepare("SELECT full_name, username, email, phone_number FROM users WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }
}
?>