<?php
// API endpoint for user management operations
error_reporting(0); // Suppress errors to prevent HTML output
ini_set('display_errors', 0);

include '../../includes/auth.php';
include '../../includes/db.php';

header('Content-Type: application/json');

// Check permissions
$allowed_roles = ['super_admin', 'admin'];
$user_role = $_SESSION['role'] ?? $_SESSION['user_type'] ?? '';

if (!in_array($user_role, $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'get_user':
            echo json_encode(getUser($pdo, $_GET['id']));
            break;
            
        case 'get_group_members':
            echo json_encode(getGroupMembers($pdo, $_GET['group_id']));
            break;
            
        case 'get_group':
            echo json_encode(getGroup($pdo, $_GET['id']));
            break;
            
        case 'search_users':
            echo json_encode(searchUsers($pdo, $_GET['q']));
            break;
            
        case 'update_user_status':
            echo json_encode(updateUserStatus($pdo, $_POST, $user_role));
            break;
            
        case 'bulk_action':
            echo json_encode(bulkAction($pdo, $_POST, $user_role));
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

function getUser($pdo, $user_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT u.*, p.full_name, p.email, p.phone, p.address, p.notes, p.is_active,
                   GROUP_CONCAT(g.id) as group_ids,
                   GROUP_CONCAT(g.name) as group_names
            FROM users u
            LEFT JOIN user_profiles p ON u.id = p.user_id
            LEFT JOIN user_group_memberships ugm ON u.id = ugm.user_id
            LEFT JOIN user_groups g ON ugm.group_id = g.id
            WHERE u.id = ?
            GROUP BY u.id
        ");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            return ['success' => true, 'user' => $user];
        } else {
            return ['success' => false, 'message' => 'User not found'];
        }
    } catch (Exception $e) {
        // Fallback to basic user info if extended tables don't exist
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            // Add default values for missing profile fields
            $user['full_name'] = $user['full_name'] ?? ucwords(str_replace('_', ' ', $user['username']));
            $user['email'] = $user['email'] ?? '';
            $user['phone'] = $user['phone'] ?? '';
            $user['is_active'] = $user['is_active'] ?? 1;
            $user['notes'] = $user['notes'] ?? '';
            return ['success' => true, 'user' => $user];
        } else {
            return ['success' => false, 'message' => 'User not found'];
        }
    }
}

function getGroupMembers($pdo, $group_id) {
    try {
        // Check if tables exist first
        $pdo->query("SELECT 1 FROM user_group_memberships LIMIT 1");
        $pdo->query("SELECT 1 FROM user_profiles LIMIT 1");
        
        // First, try to get the actual column structure
        $columns = $pdo->query("SHOW COLUMNS FROM user_group_memberships")->fetchAll(PDO::FETCH_COLUMN);
        
        // Determine which date column to use
        $dateColumn = 'NOW() as joined_at'; // Default fallback
        if (in_array('created_at', $columns)) {
            $dateColumn = 'ugm.created_at as joined_at';
        } elseif (in_array('joined_at', $columns)) {
            $dateColumn = 'ugm.joined_at';
        } elseif (in_array('added_at', $columns)) {
            $dateColumn = 'ugm.added_at as joined_at';
        }
        
        $stmt = $pdo->prepare("
            SELECT u.id, u.username, p.full_name, p.email, u.role,
                   ugm.role_in_group, $dateColumn
            FROM user_group_memberships ugm
            JOIN users u ON ugm.user_id = u.id
            LEFT JOIN user_profiles p ON u.id = p.user_id
            WHERE ugm.group_id = ?
            ORDER BY u.username
        ");
        $stmt->execute([$group_id]);
        $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return ['success' => true, 'members' => $members];
    } catch (Exception $e) {
        // If tables don't exist, return empty result
        if (strpos($e->getMessage(), "doesn't exist") !== false) {
            return ['success' => true, 'members' => [], 'message' => 'Group membership tables not yet created'];
        }
        
        // Try a simpler query without date columns
        try {
            $stmt = $pdo->prepare("
                SELECT u.id, u.username, p.full_name, p.email, u.role,
                       ugm.role_in_group, 'Member since setup' as joined_at
                FROM user_group_memberships ugm
                JOIN users u ON ugm.user_id = u.id
                LEFT JOIN user_profiles p ON u.id = p.user_id
                WHERE ugm.group_id = ?
                ORDER BY u.username
            ");
            $stmt->execute([$group_id]);
            $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            return ['success' => true, 'members' => $members];
        } catch (Exception $e2) {
            return ['success' => false, 'message' => $e2->getMessage()];
        }
    }
}

function getGroup($pdo, $group_id) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM user_groups WHERE id = ?");
        $stmt->execute([$group_id]);
        $group = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($group) {
            return ['success' => true, 'group' => $group];
        } else {
            return ['success' => false, 'message' => 'Group not found'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

function searchUsers($pdo, $query) {
    $search = "%$query%";
    $stmt = $pdo->prepare("
        SELECT u.id, u.username, u.role, p.full_name, p.email
        FROM users u
        LEFT JOIN user_profiles p ON u.id = p.user_id
        WHERE u.username LIKE ? OR p.full_name LIKE ? OR p.email LIKE ?
        ORDER BY p.full_name, u.username
        LIMIT 20
    ");
    $stmt->execute([$search, $search, $search]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    return ['success' => true, 'users' => $users];
}

function updateUserStatus($pdo, $data, $user_role) {
    $user_id = intval($data['user_id']);
    $status = $data['status'] === 'active' ? 1 : 0;
    
    $stmt = $pdo->prepare("UPDATE user_profiles SET is_active = ? WHERE user_id = ?");
    $stmt->execute([$status, $user_id]);
    
    return ['success' => true, 'message' => 'User status updated'];
}

function bulkAction($pdo, $data, $user_role) {
    $user_ids = $data['user_ids'] ?? [];
    $action = $data['bulk_action'];
    
    if (empty($user_ids)) {
        return ['success' => false, 'message' => 'No users selected'];
    }
    
    switch ($action) {
        case 'activate':
            $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
            $stmt = $pdo->prepare("UPDATE user_profiles SET is_active = 1 WHERE user_id IN ($placeholders)");
            $stmt->execute($user_ids);
            return ['success' => true, 'message' => count($user_ids) . ' users activated'];
            
        case 'deactivate':
            $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
            $stmt = $pdo->prepare("UPDATE user_profiles SET is_active = 0 WHERE user_id IN ($placeholders)");
            $stmt->execute($user_ids);
            return ['success' => true, 'message' => count($user_ids) . ' users deactivated'];
            
        case 'delete':
            if ($user_role !== 'super_admin') {
                return ['success' => false, 'message' => 'Only super admin can delete users'];
            }
            $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
            $stmt = $pdo->prepare("DELETE FROM users WHERE id IN ($placeholders)");
            $stmt->execute($user_ids);
            return ['success' => true, 'message' => count($user_ids) . ' users deleted'];
            
        default:
            return ['success' => false, 'message' => 'Invalid bulk action'];
    }
}
?>
